refactor: remove some facades (#12335)

This commit is contained in:
Victor Berchet
2016-10-19 13:42:39 -07:00
committed by Alex Rickabaugh
parent 0ecd9b2df0
commit 76dd026447
58 changed files with 281 additions and 429 deletions

View File

@ -9,7 +9,6 @@
import {Inject, Injectable} from '@angular/core'; import {Inject, Injectable} from '@angular/core';
import {Options} from '../common_options'; import {Options} from '../common_options';
import {isNumber} from '../facade/lang';
import {Metric} from '../metric'; import {Metric} from '../metric';
import {WebDriverAdapter} from '../web_driver_adapter'; import {WebDriverAdapter} from '../web_driver_adapter';
@ -44,7 +43,7 @@ export class UserMetric extends Metric {
function getAndClearValues() { function getAndClearValues() {
Promise.all(names.map(name => adapter.executeScript(`return window.${name}`))) Promise.all(names.map(name => adapter.executeScript(`return window.${name}`)))
.then((values: any[]) => { .then((values: any[]) => {
if (values.every(isNumber)) { if (values.every(v => typeof v === 'number')) {
Promise.all(names.map(name => adapter.executeScript(`delete window.${name}`))) Promise.all(names.map(name => adapter.executeScript(`delete window.${name}`)))
.then((_: any[]) => { .then((_: any[]) => {
let map: {[k: string]: any} = {}; let map: {[k: string]: any} = {};

View File

@ -9,7 +9,6 @@
import {Inject, Injectable, OpaqueToken} from '@angular/core'; import {Inject, Injectable, OpaqueToken} from '@angular/core';
import {Options} from '../common_options'; import {Options} from '../common_options';
import {Json} from '../facade/lang';
import {MeasureValues} from '../measure_values'; import {MeasureValues} from '../measure_values';
import {Reporter} from '../reporter'; import {Reporter} from '../reporter';
import {SampleDescription} from '../sample_description'; import {SampleDescription} from '../sample_description';
@ -39,12 +38,14 @@ export class JsonFileReporter extends Reporter {
sortedProps(this._description.metrics).forEach((metricName) => { sortedProps(this._description.metrics).forEach((metricName) => {
stats[metricName] = formatStats(validSample, metricName); stats[metricName] = formatStats(validSample, metricName);
}); });
var content = Json.stringify({ var content = JSON.stringify(
'description': this._description, {
'stats': stats, 'description': this._description,
'completeSample': completeSample, 'stats': stats,
'validSample': validSample, 'completeSample': completeSample,
}); 'validSample': validSample,
},
null, 2);
var filePath = `${this._path}/${this._description.id}_${this._now().getTime()}.json`; var filePath = `${this._path}/${this._description.id}_${this._now().getTime()}.json`;
return this._writeFile(filePath, content); return this._writeFile(filePath, content);
} }

View File

@ -6,20 +6,15 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {NumberWrapper} from '../facade/lang';
import {MeasureValues} from '../measure_values'; import {MeasureValues} from '../measure_values';
import {Statistic} from '../statistic'; import {Statistic} from '../statistic';
export function formatNum(n: number) { export function formatNum(n: number) {
return NumberWrapper.toFixed(n, 2); return n.toFixed(2);
} }
export function sortedProps(obj: {[key: string]: any}) { export function sortedProps(obj: {[key: string]: any}) {
var props: string[] = []; return Object.keys(obj).sort();
props.push(...Object.keys(obj));
props.sort();
return props;
} }
export function formatStats(validSamples: MeasureValues[], metricName: string): string { export function formatStats(validSamples: MeasureValues[], metricName: string): string {
@ -29,5 +24,5 @@ export function formatStats(validSamples: MeasureValues[], metricName: string):
var formattedMean = formatNum(mean); var formattedMean = formatNum(mean);
// Note: Don't use the unicode character for +- as it might cause // Note: Don't use the unicode character for +- as it might cause
// hickups for consoles... // hickups for consoles...
return NumberWrapper.isNaN(cv) ? formattedMean : `${formattedMean}+-${Math.floor(cv)}%`; return isNaN(cv) ? formattedMean : `${formattedMean}+-${Math.floor(cv)}%`;
} }

View File

@ -6,8 +6,6 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {Math} from './facade/math';
export class Statistic { export class Statistic {
static calculateCoefficientOfVariation(sample: number[], mean: number) { static calculateCoefficientOfVariation(sample: number[], mean: number) {
return Statistic.calculateStandardDeviation(sample, mean) / mean * 100; return Statistic.calculateStandardDeviation(sample, mean) / mean * 100;

View File

@ -9,7 +9,7 @@
import {AsyncTestCompleter, describe, expect, inject, it} from '@angular/core/testing/testing_internal'; import {AsyncTestCompleter, describe, expect, inject, it} from '@angular/core/testing/testing_internal';
import {JsonFileReporter, MeasureValues, Options, ReflectiveInjector, SampleDescription} from '../../index'; import {JsonFileReporter, MeasureValues, Options, ReflectiveInjector, SampleDescription} from '../../index';
import {Json, isPresent} from '../../src/facade/lang'; import {isPresent} from '../../src/facade/lang';
export function main() { export function main() {
describe('file reporter', () => { describe('file reporter', () => {
@ -51,7 +51,7 @@ export function main() {
[mv(0, 0, {'a': 3, 'b': 6}), mv(1, 1, {'a': 5, 'b': 9})]); [mv(0, 0, {'a': 3, 'b': 6}), mv(1, 1, {'a': 5, 'b': 9})]);
var regExp = /somePath\/someId_\d+\.json/; var regExp = /somePath\/someId_\d+\.json/;
expect(isPresent(loggedFile['filename'].match(regExp))).toBe(true); expect(isPresent(loggedFile['filename'].match(regExp))).toBe(true);
var parsedContent = Json.parse(loggedFile['content']); var parsedContent = JSON.parse(loggedFile['content']);
expect(parsedContent).toEqual({ expect(parsedContent).toEqual({
'description': { 'description': {
'id': 'someId', 'id': 'someId',

View File

@ -9,7 +9,7 @@
import {AsyncTestCompleter, describe, expect, inject, it} from '@angular/core/testing/testing_internal'; import {AsyncTestCompleter, describe, expect, inject, it} from '@angular/core/testing/testing_internal';
import {ChromeDriverExtension, Options, ReflectiveInjector, WebDriverAdapter, WebDriverExtension} from '../../index'; import {ChromeDriverExtension, Options, ReflectiveInjector, WebDriverAdapter, WebDriverExtension} from '../../index';
import {Json, isBlank} from '../../src/facade/lang'; import {isBlank} from '../../src/facade/lang';
import {TraceEventFactory} from '../trace_event_factory'; import {TraceEventFactory} from '../trace_event_factory';
export function main() { export function main() {
@ -398,8 +398,8 @@ class MockDriverAdapter extends WebDriverAdapter {
if (type === 'performance') { if (type === 'performance') {
return Promise.resolve(this._events.map( return Promise.resolve(this._events.map(
(event) => ({ (event) => ({
'message': 'message': JSON.stringify(
Json.stringify({'message': {'method': this._messageMethod, 'params': event}}) {'message': {'method': this._messageMethod, 'params': event}}, null, 2)
}))); })));
} else { } else {
return null; return null;

View File

@ -9,7 +9,6 @@
import {AsyncTestCompleter, describe, expect, inject, it} from '@angular/core/testing/testing_internal'; import {AsyncTestCompleter, describe, expect, inject, it} from '@angular/core/testing/testing_internal';
import {IOsDriverExtension, ReflectiveInjector, WebDriverAdapter, WebDriverExtension} from '../../index'; import {IOsDriverExtension, ReflectiveInjector, WebDriverAdapter, WebDriverExtension} from '../../index';
import {Json} from '../../src/facade/lang';
import {TraceEventFactory} from '../trace_event_factory'; import {TraceEventFactory} from '../trace_event_factory';
export function main() { export function main() {
@ -184,8 +183,9 @@ class MockDriverAdapter extends WebDriverAdapter {
if (type === 'performance') { if (type === 'performance') {
return Promise.resolve(this._perfRecords.map(function(record) { return Promise.resolve(this._perfRecords.map(function(record) {
return { return {
'message': Json.stringify( 'message': JSON.stringify(
{'message': {'method': 'Timeline.eventRecorded', 'params': {'record': record}}}) {'message': {'method': 'Timeline.eventRecorded', 'params': {'record': record}}}, null,
2)
}; };
})); }));
} else { } else {

View File

@ -7,7 +7,7 @@
*/ */
import {Pipe, PipeTransform} from '@angular/core'; import {Pipe, PipeTransform} from '@angular/core';
import {isBlank, isStringMap} from '../facade/lang'; import {isBlank} from '../facade/lang';
import {NgLocalization, getPluralCategory} from '../localization'; import {NgLocalization, getPluralCategory} from '../localization';
import {InvalidPipeArgumentError} from './invalid_pipe_argument_error'; import {InvalidPipeArgumentError} from './invalid_pipe_argument_error';
@ -37,7 +37,7 @@ export class I18nPluralPipe implements PipeTransform {
transform(value: number, pluralMap: {[count: string]: string}): string { transform(value: number, pluralMap: {[count: string]: string}): string {
if (isBlank(value)) return ''; if (isBlank(value)) return '';
if (!isStringMap(pluralMap)) { if (typeof pluralMap !== 'object' || pluralMap === null) {
throw new InvalidPipeArgumentError(I18nPluralPipe, pluralMap); throw new InvalidPipeArgumentError(I18nPluralPipe, pluralMap);
} }

View File

@ -7,7 +7,7 @@
*/ */
import {Pipe, PipeTransform} from '@angular/core'; import {Pipe, PipeTransform} from '@angular/core';
import {isBlank, isStringMap} from '../facade/lang'; import {isBlank} from '../facade/lang';
import {InvalidPipeArgumentError} from './invalid_pipe_argument_error'; import {InvalidPipeArgumentError} from './invalid_pipe_argument_error';
/** /**
@ -31,10 +31,10 @@ export class I18nSelectPipe implements PipeTransform {
transform(value: string, mapping: {[key: string]: string}): string { transform(value: string, mapping: {[key: string]: string}): string {
if (isBlank(value)) return ''; if (isBlank(value)) return '';
if (!isStringMap(mapping)) { if (typeof mapping !== 'object' || mapping === null) {
throw new InvalidPipeArgumentError(I18nSelectPipe, mapping); throw new InvalidPipeArgumentError(I18nSelectPipe, mapping);
} }
return mapping.hasOwnProperty(value) ? mapping[value] : ''; return mapping[value] || '';
} }
} }

View File

@ -8,10 +8,6 @@
import {Pipe, PipeTransform} from '@angular/core'; import {Pipe, PipeTransform} from '@angular/core';
import {Json} from '../facade/lang';
/** /**
* @ngModule CommonModule * @ngModule CommonModule
* @whatItDoes Converts value into JSON string. * @whatItDoes Converts value into JSON string.
@ -27,5 +23,5 @@ import {Json} from '../facade/lang';
*/ */
@Pipe({name: 'json', pure: false}) @Pipe({name: 'json', pure: false})
export class JsonPipe implements PipeTransform { export class JsonPipe implements PipeTransform {
transform(value: any): string { return Json.stringify(value); } transform(value: any): string { return JSON.stringify(value, null, 2); }
} }

View File

@ -11,8 +11,6 @@ import {Component} from '@angular/core';
import {TestBed, async} from '@angular/core/testing'; import {TestBed, async} from '@angular/core/testing';
import {expect} from '@angular/platform-browser/testing/matchers'; import {expect} from '@angular/platform-browser/testing/matchers';
import {Json} from '../../src/facade/lang';
export function main() { export function main() {
describe('JsonPipe', () => { describe('JsonPipe', () => {
var regNewLine = '\n'; var regNewLine = '\n';
@ -48,7 +46,7 @@ export function main() {
it('should return JSON-formatted string similar to Json.stringify', () => { it('should return JSON-formatted string similar to Json.stringify', () => {
var dream1 = normalize(pipe.transform(inceptionObj)); var dream1 = normalize(pipe.transform(inceptionObj));
var dream2 = normalize(Json.stringify(inceptionObj)); var dream2 = normalize(JSON.stringify(inceptionObj, null, 2));
expect(dream1).toEqual(dream2); expect(dream1).toEqual(dream2);
}); });
}); });
@ -74,7 +72,6 @@ export function main() {
mutable.push(2); mutable.push(2);
fixture.detectChanges(); fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('[\n 1,\n 2\n]'); expect(fixture.nativeElement).toHaveText('[\n 1,\n 2\n]');
})); }));
}); });
}); });

View File

@ -8,8 +8,7 @@
import {CompileAnimationAnimateMetadata, CompileAnimationEntryMetadata, CompileAnimationGroupMetadata, CompileAnimationKeyframesSequenceMetadata, CompileAnimationMetadata, CompileAnimationSequenceMetadata, CompileAnimationStateDeclarationMetadata, CompileAnimationStateTransitionMetadata, CompileAnimationStyleMetadata, CompileAnimationWithStepsMetadata, CompileDirectiveMetadata} from '../compile_metadata'; import {CompileAnimationAnimateMetadata, CompileAnimationEntryMetadata, CompileAnimationGroupMetadata, CompileAnimationKeyframesSequenceMetadata, CompileAnimationMetadata, CompileAnimationSequenceMetadata, CompileAnimationStateDeclarationMetadata, CompileAnimationStateTransitionMetadata, CompileAnimationStyleMetadata, CompileAnimationWithStepsMetadata, CompileDirectiveMetadata} from '../compile_metadata';
import {ListWrapper, StringMapWrapper} from '../facade/collection'; import {ListWrapper, StringMapWrapper} from '../facade/collection';
import {isArray, isBlank, isPresent, isString, isStringMap} from '../facade/lang'; import {isBlank, isPresent} from '../facade/lang';
import {Math} from '../facade/math';
import {ParseError} from '../parse_util'; import {ParseError} from '../parse_util';
import {ANY_STATE, FILL_STYLE_FLAG} from '../private_import_core'; import {ANY_STATE, FILL_STYLE_FLAG} from '../private_import_core';
@ -97,7 +96,7 @@ function _parseAnimationDeclarationStates(
var styleValues: Styles[] = []; var styleValues: Styles[] = [];
stateMetadata.styles.styles.forEach(stylesEntry => { stateMetadata.styles.styles.forEach(stylesEntry => {
// TODO (matsko): change this when we get CSS class integration support // TODO (matsko): change this when we get CSS class integration support
if (isStringMap(stylesEntry)) { if (typeof stylesEntry === 'object' && stylesEntry !== null) {
styleValues.push(stylesEntry as Styles); styleValues.push(stylesEntry as Styles);
} else { } else {
errors.push(new AnimationParseError( errors.push(new AnimationParseError(
@ -172,8 +171,7 @@ function _parseAnimationTransitionExpr(
function _normalizeAnimationEntry(entry: CompileAnimationMetadata | CompileAnimationMetadata[]): function _normalizeAnimationEntry(entry: CompileAnimationMetadata | CompileAnimationMetadata[]):
CompileAnimationMetadata { CompileAnimationMetadata {
return isArray(entry) ? new CompileAnimationSequenceMetadata(<CompileAnimationMetadata[]>entry) : return Array.isArray(entry) ? new CompileAnimationSequenceMetadata(entry) : entry;
<CompileAnimationMetadata>entry;
} }
function _normalizeStyleMetadata( function _normalizeStyleMetadata(
@ -181,7 +179,7 @@ function _normalizeStyleMetadata(
errors: AnimationParseError[]): {[key: string]: string | number}[] { errors: AnimationParseError[]): {[key: string]: string | number}[] {
var normalizedStyles: {[key: string]: string | number}[] = []; var normalizedStyles: {[key: string]: string | number}[] = [];
entry.styles.forEach(styleEntry => { entry.styles.forEach(styleEntry => {
if (isString(styleEntry)) { if (typeof styleEntry === 'string') {
ListWrapper.addAll( ListWrapper.addAll(
normalizedStyles, _resolveStylesFromState(<string>styleEntry, stateStyles, errors)); normalizedStyles, _resolveStylesFromState(<string>styleEntry, stateStyles, errors));
} else { } else {
@ -202,10 +200,10 @@ function _normalizeStyleSteps(
function _mergeAnimationStyles( function _mergeAnimationStyles(
stylesList: any[], newItem: {[key: string]: string | number} | string) { stylesList: any[], newItem: {[key: string]: string | number} | string) {
if (isStringMap(newItem) && stylesList.length > 0) { if (typeof newItem === 'object' && newItem !== null && stylesList.length > 0) {
var lastIndex = stylesList.length - 1; var lastIndex = stylesList.length - 1;
var lastItem = stylesList[lastIndex]; var lastItem = stylesList[lastIndex];
if (isStringMap(lastItem)) { if (typeof lastItem === 'object' && lastItem !== null) {
stylesList[lastIndex] = StringMapWrapper.merge( stylesList[lastIndex] = StringMapWrapper.merge(
<{[key: string]: string | number}>lastItem, <{[key: string]: string | number}>newItem); <{[key: string]: string | number}>lastItem, <{[key: string]: string | number}>newItem);
return; return;
@ -292,7 +290,7 @@ function _resolveStylesFromState(
`Unable to apply styles due to missing a state: "${normalizedStateName}"`)); `Unable to apply styles due to missing a state: "${normalizedStateName}"`));
} else { } else {
value.styles.forEach(stylesEntry => { value.styles.forEach(stylesEntry => {
if (isStringMap(stylesEntry)) { if (typeof stylesEntry === 'object' && stylesEntry !== null) {
styles.push(stylesEntry as Styles); styles.push(stylesEntry as Styles);
} }
}); });
@ -504,7 +502,7 @@ function _parseTimeExpression(
var duration: number; var duration: number;
var delay: number = 0; var delay: number = 0;
var easing: string = null; var easing: string = null;
if (isString(exp)) { if (typeof exp === 'string') {
const matches = exp.match(regex); const matches = exp.match(regex);
if (matches === null) { if (matches === null) {
errors.push(new AnimationParseError(`The provided timing value "${exp}" is invalid.`)); errors.push(new AnimationParseError(`The provided timing value "${exp}" is invalid.`));

View File

@ -8,17 +8,17 @@
import {isDevMode} from '@angular/core'; import {isDevMode} from '@angular/core';
import {isArray, isBlank, isPresent, isString} from '../src/facade/lang'; import {isBlank, isPresent} from '../src/facade/lang';
export function assertArrayOfStrings(identifier: string, value: any) { export function assertArrayOfStrings(identifier: string, value: any) {
if (!isDevMode() || isBlank(value)) { if (!isDevMode() || isBlank(value)) {
return; return;
} }
if (!isArray(value)) { if (!Array.isArray(value)) {
throw new Error(`Expected '${identifier}' to be an array of strings.`); throw new Error(`Expected '${identifier}' to be an array of strings.`);
} }
for (var i = 0; i < value.length; i += 1) { for (var i = 0; i < value.length; i += 1) {
if (!isString(value[i])) { if (typeof value[i] !== 'string') {
throw new Error(`Expected '${identifier}' to be an array of strings.`); throw new Error(`Expected '${identifier}' to be an array of strings.`);
} }
} }
@ -33,7 +33,7 @@ const INTERPOLATION_BLACKLIST_REGEXPS = [
]; ];
export function assertInterpolationSymbols(identifier: string, value: any): void { export function assertInterpolationSymbols(identifier: string, value: any): void {
if (isPresent(value) && !(isArray(value) && value.length == 2)) { if (isPresent(value) && !(Array.isArray(value) && value.length == 2)) {
throw new Error(`Expected '${identifier}' to be an array, [start, end].`); throw new Error(`Expected '${identifier}' to be an array, [start, end].`);
} else if (isDevMode() && !isBlank(value)) { } else if (isDevMode() && !isBlank(value)) {
const start = value[0] as string; const start = value[0] as string;

View File

@ -9,7 +9,7 @@
import {ChangeDetectionStrategy, SchemaMetadata, Type, ViewEncapsulation} from '@angular/core'; import {ChangeDetectionStrategy, SchemaMetadata, Type, ViewEncapsulation} from '@angular/core';
import {ListWrapper, MapWrapper} from './facade/collection'; import {ListWrapper, MapWrapper} from './facade/collection';
import {isPresent, isStringMap, normalizeBlank, normalizeBool} from './facade/lang'; import {isPresent, normalizeBlank, normalizeBool} from './facade/lang';
import {LifecycleHooks} from './private_import_core'; import {LifecycleHooks} from './private_import_core';
import {CssSelector} from './selector'; import {CssSelector} from './selector';
import {sanitizeIdentifier, splitAtColon} from './util'; import {sanitizeIdentifier, splitAtColon} from './util';
@ -594,7 +594,7 @@ function _normalizeArray(obj: any[]): any[] {
} }
export function isStaticSymbol(value: any): value is StaticSymbol { export function isStaticSymbol(value: any): value is StaticSymbol {
return isStringMap(value) && isPresent(value['name']) && isPresent(value['filePath']); return typeof value === 'object' && value !== null && value['name'] && value['filePath'];
} }
export interface StaticSymbol { export interface StaticSymbol {

View File

@ -8,7 +8,7 @@
import {Injectable} from '@angular/core'; import {Injectable} from '@angular/core';
import * as chars from '../chars'; import * as chars from '../chars';
import {NumberWrapper, StringJoiner, isPresent} from '../facade/lang'; import {NumberWrapper, isPresent} from '../facade/lang';
export enum TokenType { export enum TokenType {
Character, Character,
@ -274,42 +274,41 @@ class _Scanner {
} }
this.advance(); this.advance();
} }
var str: string = this.input.substring(start, this.index); const str: string = this.input.substring(start, this.index);
var value: number = simple ? NumberWrapper.parseIntAutoRadix(str) : parseFloat(str); const value: number = simple ? NumberWrapper.parseIntAutoRadix(str) : parseFloat(str);
return newNumberToken(start, value); return newNumberToken(start, value);
} }
scanString(): Token { scanString(): Token {
var start: number = this.index; const start: number = this.index;
var quote: number = this.peek; const quote: number = this.peek;
this.advance(); // Skip initial quote. this.advance(); // Skip initial quote.
var buffer: StringJoiner; let buffer: string = '';
var marker: number = this.index; let marker: number = this.index;
var input: string = this.input; let input: string = this.input;
while (this.peek != quote) { while (this.peek != quote) {
if (this.peek == chars.$BACKSLASH) { if (this.peek == chars.$BACKSLASH) {
if (buffer == null) buffer = new StringJoiner(); buffer += input.substring(marker, this.index);
buffer.add(input.substring(marker, this.index));
this.advance(); this.advance();
var unescapedCode: number; let unescapedCode: number;
if (this.peek == chars.$u) { if (this.peek == chars.$u) {
// 4 character hex code for unicode character. // 4 character hex code for unicode character.
var hex: string = input.substring(this.index + 1, this.index + 5); const hex: string = input.substring(this.index + 1, this.index + 5);
try { try {
unescapedCode = NumberWrapper.parseInt(hex, 16); unescapedCode = NumberWrapper.parseInt(hex, 16);
} catch (e) { } catch (e) {
return this.error(`Invalid unicode escape [\\u${hex}]`, 0); return this.error(`Invalid unicode escape [\\u${hex}]`, 0);
} }
for (var i: number = 0; i < 5; i++) { for (let i: number = 0; i < 5; i++) {
this.advance(); this.advance();
} }
} else { } else {
unescapedCode = unescape(this.peek); unescapedCode = unescape(this.peek);
this.advance(); this.advance();
} }
buffer.add(String.fromCharCode(unescapedCode)); buffer += String.fromCharCode(unescapedCode);
marker = this.index; marker = this.index;
} else if (this.peek == chars.$EOF) { } else if (this.peek == chars.$EOF) {
return this.error('Unterminated quote', 0); return this.error('Unterminated quote', 0);
@ -318,16 +317,10 @@ class _Scanner {
} }
} }
var last: string = input.substring(marker, this.index); const last: string = input.substring(marker, this.index);
this.advance(); // Skip terminating quote. this.advance(); // Skip terminating quote.
// Compute the unescaped string value. return newStringToken(start, buffer + last);
var unescaped: string = last;
if (buffer != null) {
buffer.add(last);
unescaped = buffer.toString();
}
return newStringToken(start, unescaped);
} }
error(message: string, offset: number): Token { error(message: string, offset: number): Token {

View File

@ -11,7 +11,7 @@ import {AnimationAnimateMetadata, AnimationEntryMetadata, AnimationGroupMetadata
import {assertArrayOfStrings, assertInterpolationSymbols} from './assertions'; import {assertArrayOfStrings, assertInterpolationSymbols} from './assertions';
import * as cpl from './compile_metadata'; import * as cpl from './compile_metadata';
import {DirectiveResolver} from './directive_resolver'; import {DirectiveResolver} from './directive_resolver';
import {isBlank, isPresent, isString, stringify} from './facade/lang'; import {isBlank, isPresent, stringify} from './facade/lang';
import {Identifiers, resolveIdentifierToken} from './identifiers'; import {Identifiers, resolveIdentifierToken} from './identifiers';
import {hasLifecycleHook} from './lifecycle_reflector'; import {hasLifecycleHook} from './lifecycle_reflector';
import {NgModuleResolver} from './ng_module_resolver'; import {NgModuleResolver} from './ng_module_resolver';
@ -569,7 +569,7 @@ export class CompileMetadataResolver {
getTokenMetadata(token: any): cpl.CompileTokenMetadata { getTokenMetadata(token: any): cpl.CompileTokenMetadata {
token = resolveForwardRef(token); token = resolveForwardRef(token);
let compileToken: cpl.CompileTokenMetadata; let compileToken: cpl.CompileTokenMetadata;
if (isString(token)) { if (typeof token === 'string') {
compileToken = new cpl.CompileTokenMetadata({value: token}); compileToken = new cpl.CompileTokenMetadata({value: token});
} else { } else {
compileToken = new cpl.CompileTokenMetadata({ compileToken = new cpl.CompileTokenMetadata({

View File

@ -6,14 +6,14 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {isBlank, isPresent, isString} from '../facade/lang'; import {isBlank, isPresent} from '../facade/lang';
import * as o from './output_ast'; import * as o from './output_ast';
var _SINGLE_QUOTE_ESCAPE_STRING_RE = /'|\\|\n|\r|\$/g; const _SINGLE_QUOTE_ESCAPE_STRING_RE = /'|\\|\n|\r|\$/g;
var _LEGAL_IDENTIFIER_RE = /^[$A-Z_][0-9A-Z_$]*$/i; const _LEGAL_IDENTIFIER_RE = /^[$A-Z_][0-9A-Z_$]*$/i;
export var CATCH_ERROR_VAR = o.variable('error'); export const CATCH_ERROR_VAR = o.variable('error');
export var CATCH_STACK_VAR = o.variable('stack'); export const CATCH_STACK_VAR = o.variable('stack');
export abstract class OutputEmitter { export abstract class OutputEmitter {
abstract emitStatements(moduleUrl: string, stmts: o.Statement[], exportedVars: string[]): string; abstract emitStatements(moduleUrl: string, stmts: o.Statement[], exportedVars: string[]): string;
@ -253,7 +253,7 @@ export abstract class AbstractEmitterVisitor implements o.StatementVisitor, o.Ex
visitLiteralExpr(ast: o.LiteralExpr, ctx: EmitterVisitorContext, absentValue: string = 'null'): visitLiteralExpr(ast: o.LiteralExpr, ctx: EmitterVisitorContext, absentValue: string = 'null'):
any { any {
var value = ast.value; var value = ast.value;
if (isString(value)) { if (typeof value === 'string') {
ctx.print(escapeIdentifier(value, this._escapeDollarInStrings)); ctx.print(escapeIdentifier(value, this._escapeDollarInStrings));
} else if (isBlank(value)) { } else if (isBlank(value)) {
ctx.print(absentValue); ctx.print(absentValue);

View File

@ -8,9 +8,7 @@
import {CompileIdentifierMetadata} from '../compile_metadata'; import {CompileIdentifierMetadata} from '../compile_metadata';
import {isPresent, isString} from '../facade/lang'; import {isPresent} from '../facade/lang';
//// Types //// Types
export enum TypeModifier { export enum TypeModifier {
@ -196,7 +194,7 @@ export class ReadVarExpr extends Expression {
constructor(name: string|BuiltinVar, type: Type = null) { constructor(name: string|BuiltinVar, type: Type = null) {
super(type); super(type);
if (isString(name)) { if (typeof name === 'string') {
this.name = name; this.name = name;
this.builtin = null; this.builtin = null;
} else { } else {
@ -267,7 +265,7 @@ export class InvokeMethodExpr extends Expression {
public receiver: Expression, method: string|BuiltinMethod, public args: Expression[], public receiver: Expression, method: string|BuiltinMethod, public args: Expression[],
type: Type = null) { type: Type = null) {
super(type); super(type);
if (isString(method)) { if (typeof method === 'string') {
this.name = method; this.name = method;
this.builtin = null; this.builtin = null;
} else { } else {

View File

@ -6,13 +6,26 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {evalExpression, isPresent} from '../facade/lang'; import {isPresent} from '../facade/lang';
import {sanitizeIdentifier} from '../util'; import {sanitizeIdentifier} from '../util';
import {EmitterVisitorContext} from './abstract_emitter'; import {EmitterVisitorContext} from './abstract_emitter';
import {AbstractJsEmitterVisitor} from './abstract_js_emitter'; import {AbstractJsEmitterVisitor} from './abstract_js_emitter';
import * as o from './output_ast'; import * as o from './output_ast';
function evalExpression(
sourceUrl: string, expr: string, declarations: string, vars: {[key: string]: any}): any {
const fnBody = `${declarations}\nreturn ${expr}\n//# sourceURL=${sourceUrl}`;
const fnArgNames: string[] = [];
const fnArgValues: any[] = [];
for (const argName in vars) {
fnArgNames.push(argName);
fnArgValues.push(vars[argName]);
}
return new Function(...fnArgNames.concat(fnBody))(...fnArgValues);
}
export function jitStatements( export function jitStatements(
sourceUrl: string, statements: o.Statement[], resultVar: string): any { sourceUrl: string, statements: o.Statement[], resultVar: string): any {
var converter = new JitEmitterVisitor(); var converter = new JitEmitterVisitor();

View File

@ -8,24 +8,20 @@
import {CompileIdentifierMetadata} from '../compile_metadata'; import {CompileIdentifierMetadata} from '../compile_metadata';
import {isArray, isBlank, isPresent} from '../facade/lang'; import {isBlank, isPresent} from '../facade/lang';
import {AbstractEmitterVisitor, CATCH_ERROR_VAR, CATCH_STACK_VAR, EmitterVisitorContext, OutputEmitter} from './abstract_emitter'; import {AbstractEmitterVisitor, CATCH_ERROR_VAR, CATCH_STACK_VAR, EmitterVisitorContext, OutputEmitter} from './abstract_emitter';
import * as o from './output_ast'; import * as o from './output_ast';
import {ImportGenerator} from './path_util'; import {ImportGenerator} from './path_util';
var _debugModuleUrl = 'asset://debug/lib'; const _debugModuleUrl = 'asset://debug/lib';
export function debugOutputAstAsTypeScript(ast: o.Statement | o.Expression | o.Type | any[]): export function debugOutputAstAsTypeScript(ast: o.Statement | o.Expression | o.Type | any[]):
string { string {
var converter = new _TsEmitterVisitor(_debugModuleUrl); const converter = new _TsEmitterVisitor(_debugModuleUrl);
var ctx = EmitterVisitorContext.createRoot([]); const ctx = EmitterVisitorContext.createRoot([]);
var asts: any[]; const asts: any[] = Array.isArray(ast) ? ast : [ast];
if (isArray(ast)) {
asts = <any[]>ast;
} else {
asts = [ast];
}
asts.forEach((ast) => { asts.forEach((ast) => {
if (ast instanceof o.Statement) { if (ast instanceof o.Statement) {
ast.visitStatement(converter, ctx); ast.visitStatement(converter, ctx);

View File

@ -9,7 +9,7 @@
import {CompileDiDependencyMetadata, CompileDirectiveMetadata, CompileNgModuleMetadata, CompileProviderMetadata, CompileQueryMetadata, CompileTokenMetadata, CompileTypeMetadata} from './compile_metadata'; import {CompileDiDependencyMetadata, CompileDirectiveMetadata, CompileNgModuleMetadata, CompileProviderMetadata, CompileQueryMetadata, CompileTokenMetadata, CompileTypeMetadata} from './compile_metadata';
import {ListWrapper, MapWrapper} from './facade/collection'; import {ListWrapper, MapWrapper} from './facade/collection';
import {isArray, isBlank, isPresent, normalizeBlank} from './facade/lang'; import {isBlank, isPresent, normalizeBlank} from './facade/lang';
import {Identifiers, resolveIdentifierToken} from './identifiers'; import {Identifiers, resolveIdentifierToken} from './identifiers';
import {ParseError, ParseSourceSpan} from './parse_util'; import {ParseError, ParseSourceSpan} from './parse_util';
import {AttrAst, DirectiveAst, ProviderAst, ProviderAstType, ReferenceAst} from './template_parser/template_ast'; import {AttrAst, DirectiveAst, ProviderAst, ProviderAstType, ReferenceAst} from './template_parser/template_ast';
@ -418,7 +418,7 @@ function _normalizeProviders(
} }
if (isPresent(providers)) { if (isPresent(providers)) {
providers.forEach((provider) => { providers.forEach((provider) => {
if (isArray(provider)) { if (Array.isArray(provider)) {
_normalizeProviders(<any[]>provider, sourceSpan, targetErrors, targetProviders); _normalizeProviders(<any[]>provider, sourceSpan, targetErrors, targetProviders);
} else { } else {
let normalizeProvider: CompileProviderMetadata; let normalizeProvider: CompileProviderMetadata;

View File

@ -11,7 +11,7 @@ import {Inject, Injectable, OpaqueToken, Optional, SchemaMetadata, SecurityConte
import {CompileDirectiveMetadata, CompilePipeMetadata, CompileTemplateMetadata, CompileTokenMetadata, removeIdentifierDuplicates} from '../compile_metadata'; import {CompileDirectiveMetadata, CompilePipeMetadata, CompileTemplateMetadata, CompileTokenMetadata, removeIdentifierDuplicates} from '../compile_metadata';
import {AST, ASTWithSource, BindingPipe, EmptyExpr, Interpolation, ParserError, RecursiveAstVisitor, TemplateBinding} from '../expression_parser/ast'; import {AST, ASTWithSource, BindingPipe, EmptyExpr, Interpolation, ParserError, RecursiveAstVisitor, TemplateBinding} from '../expression_parser/ast';
import {Parser} from '../expression_parser/parser'; import {Parser} from '../expression_parser/parser';
import {isPresent, isString} from '../facade/lang'; import {isPresent} from '../facade/lang';
import {I18NHtmlParser} from '../i18n/i18n_html_parser'; import {I18NHtmlParser} from '../i18n/i18n_html_parser';
import {Identifiers, identifierToken, resolveIdentifierToken} from '../identifiers'; import {Identifiers, identifierToken, resolveIdentifierToken} from '../identifiers';
import * as html from '../ml_parser/ast'; import * as html from '../ml_parser/ast';
@ -844,7 +844,7 @@ class TemplateParseVisitor implements html.Visitor {
if (hostProps) { if (hostProps) {
Object.keys(hostProps).forEach(propName => { Object.keys(hostProps).forEach(propName => {
const expression = hostProps[propName]; const expression = hostProps[propName];
if (isString(expression)) { if (typeof expression === 'string') {
const exprAst = this._parseBinding(expression, sourceSpan); const exprAst = this._parseBinding(expression, sourceSpan);
targetPropertyAsts.push( targetPropertyAsts.push(
this._createElementPropertyAst(elementName, propName, exprAst, sourceSpan)); this._createElementPropertyAst(elementName, propName, exprAst, sourceSpan));
@ -863,7 +863,7 @@ class TemplateParseVisitor implements html.Visitor {
if (hostListeners) { if (hostListeners) {
Object.keys(hostListeners).forEach(propName => { Object.keys(hostListeners).forEach(propName => {
const expression = hostListeners[propName]; const expression = hostListeners[propName];
if (isString(expression)) { if (typeof expression === 'string') {
this._parseEventOrAnimationEvent(propName, expression, sourceSpan, [], targetEventAsts); this._parseEventOrAnimationEvent(propName, expression, sourceSpan, [], targetEventAsts);
} else { } else {
this._reportError( this._reportError(

View File

@ -7,12 +7,12 @@
*/ */
import {CompileTokenMetadata} from './compile_metadata'; import {CompileTokenMetadata} from './compile_metadata';
import {isArray, isBlank, isPresent, isPrimitive, isStrictStringMap} from './facade/lang'; import {isBlank, isPresent, isPrimitive, isStrictStringMap} from './facade/lang';
import * as o from './output/output_ast'; import * as o from './output/output_ast';
export const MODULE_SUFFIX = ''; export const MODULE_SUFFIX = '';
var CAMEL_CASE_REGEXP = /([A-Z])/g; const CAMEL_CASE_REGEXP = /([A-Z])/g;
export function camelCaseToDashCase(input: string): string { export function camelCaseToDashCase(input: string): string {
return input.replace(CAMEL_CASE_REGEXP, (...m: any[]) => '-' + m[1].toLowerCase()); return input.replace(CAMEL_CASE_REGEXP, (...m: any[]) => '-' + m[1].toLowerCase());
@ -37,15 +37,19 @@ export function sanitizeIdentifier(name: string): string {
} }
export function visitValue(value: any, visitor: ValueVisitor, context: any): any { export function visitValue(value: any, visitor: ValueVisitor, context: any): any {
if (isArray(value)) { if (Array.isArray(value)) {
return visitor.visitArray(<any[]>value, context); return visitor.visitArray(<any[]>value, context);
} else if (isStrictStringMap(value)) {
return visitor.visitStringMap(<{[key: string]: any}>value, context);
} else if (isBlank(value) || isPrimitive(value)) {
return visitor.visitPrimitive(value, context);
} else {
return visitor.visitOther(value, context);
} }
if (isStrictStringMap(value)) {
return visitor.visitStringMap(<{[key: string]: any}>value, context);
}
if (isBlank(value) || isPrimitive(value)) {
return visitor.visitPrimitive(value, context);
}
return visitor.visitOther(value, context);
} }
export interface ValueVisitor { export interface ValueVisitor {

View File

@ -8,7 +8,7 @@
import * as cdAst from '../expression_parser/ast'; import * as cdAst from '../expression_parser/ast';
import {isArray, isBlank, isPresent} from '../facade/lang'; import {isBlank, isPresent} from '../facade/lang';
import {Identifiers, resolveIdentifier} from '../identifiers'; import {Identifiers, resolveIdentifier} from '../identifiers';
import * as o from '../output/output_ast'; import * as o from '../output/output_ast';
@ -471,7 +471,7 @@ class _AstToIrVisitor implements cdAst.AstVisitor {
} }
function flattenStatements(arg: any, output: o.Statement[]) { function flattenStatements(arg: any, output: o.Statement[]) {
if (isArray(arg)) { if (Array.isArray(arg)) {
(<any[]>arg).forEach((entry) => flattenStatements(entry, output)); (<any[]>arg).forEach((entry) => flattenStatements(entry, output));
} else { } else {
output.push(arg); output.push(arg);

View File

@ -7,7 +7,6 @@
*/ */
import {AST, AstVisitor, Binary, BindingPipe, Chain, Conditional, FunctionCall, ImplicitReceiver, Interpolation, KeyedRead, KeyedWrite, LiteralArray, LiteralMap, LiteralPrimitive, MethodCall, PrefixNot, PropertyRead, PropertyWrite, Quote, SafeMethodCall, SafePropertyRead} from '../../src/expression_parser/ast'; import {AST, AstVisitor, Binary, BindingPipe, Chain, Conditional, FunctionCall, ImplicitReceiver, Interpolation, KeyedRead, KeyedWrite, LiteralArray, LiteralMap, LiteralPrimitive, MethodCall, PrefixNot, PropertyRead, PropertyWrite, Quote, SafeMethodCall, SafePropertyRead} from '../../src/expression_parser/ast';
import {isString} from '../../src/facade/lang';
import {DEFAULT_INTERPOLATION_CONFIG, InterpolationConfig} from '../../src/ml_parser/interpolation_config'; import {DEFAULT_INTERPOLATION_CONFIG, InterpolationConfig} from '../../src/ml_parser/interpolation_config';
class Unparser implements AstVisitor { class Unparser implements AstVisitor {
@ -133,7 +132,7 @@ class Unparser implements AstVisitor {
} }
visitLiteralPrimitive(ast: LiteralPrimitive, context: any) { visitLiteralPrimitive(ast: LiteralPrimitive, context: any) {
if (isString(ast.value)) { if (typeof ast.value === 'string') {
this._expression += `"${ast.value.replace( Unparser._quoteRegExp, '\"')}"`; this._expression += `"${ast.value.replace( Unparser._quoteRegExp, '\"')}"`;
} else { } else {
this._expression += `${ast.value}`; this._expression += `${ast.value}`;

View File

@ -7,7 +7,6 @@
*/ */
import {isPresent, scheduleMicroTask} from '../facade/lang'; import {isPresent, scheduleMicroTask} from '../facade/lang';
import {Math} from '../facade/math';
import {AnimationPlayer} from './animation_player'; import {AnimationPlayer} from './animation_player';

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {isArray, isPresent, isString} from '../facade/lang'; import {isPresent} from '../facade/lang';
/** /**
* @experimental Animation support is experimental. * @experimental Animation support is experimental.
@ -328,10 +328,10 @@ export function style(
Array<string|{[key: string]: string | number}>): AnimationStyleMetadata { Array<string|{[key: string]: string | number}>): AnimationStyleMetadata {
var input: Array<{[key: string]: string | number}|string>; var input: Array<{[key: string]: string | number}|string>;
var offset: number = null; var offset: number = null;
if (isString(tokens)) { if (typeof tokens === 'string') {
input = [<string>tokens]; input = [<string>tokens];
} else { } else {
if (isArray(tokens)) { if (Array.isArray(tokens)) {
input = <Array<{[key: string]: string | number}>>tokens; input = <Array<{[key: string]: string | number}>>tokens;
} else { } else {
input = [<{[key: string]: string | number}>tokens]; input = [<{[key: string]: string | number}>tokens];
@ -564,8 +564,7 @@ export function keyframes(steps: AnimationStyleMetadata[]): AnimationKeyframesSe
*/ */
export function transition(stateChangeExpr: string, steps: AnimationMetadata | AnimationMetadata[]): export function transition(stateChangeExpr: string, steps: AnimationMetadata | AnimationMetadata[]):
AnimationStateTransitionMetadata { AnimationStateTransitionMetadata {
var animationData = isArray(steps) ? new AnimationSequenceMetadata(<AnimationMetadata[]>steps) : var animationData = Array.isArray(steps) ? new AnimationSequenceMetadata(steps) : steps;
<AnimationMetadata>steps;
return new AnimationStateTransitionMetadata(stateChangeExpr, animationData); return new AnimationStateTransitionMetadata(stateChangeExpr, animationData);
} }

View File

@ -7,7 +7,7 @@
*/ */
import {isListLikeIterable, iterateListLike} from '../../facade/collection'; import {isListLikeIterable, iterateListLike} from '../../facade/collection';
import {getMapKey, isArray, isBlank, isPresent, looseIdentical, stringify} from '../../facade/lang'; import {isBlank, looseIdentical, stringify} from '../../facade/lang';
import {ChangeDetectorRef} from '../change_detector_ref'; import {ChangeDetectorRef} from '../change_detector_ref';
import {IterableDiffer, IterableDifferFactory, TrackByFn} from './iterable_differs'; import {IterableDiffer, IterableDifferFactory, TrackByFn} from './iterable_differs';
@ -168,13 +168,13 @@ export class DefaultIterableDiffer implements IterableDiffer {
var record: CollectionChangeRecord = this._itHead; var record: CollectionChangeRecord = this._itHead;
var mayBeDirty: boolean = false; var mayBeDirty: boolean = false;
var index: number; var index: number;
var item: any /** TODO #9100 */; var item: any;
var itemTrackBy: any /** TODO #9100 */; var itemTrackBy: any;
if (isArray(collection)) { if (Array.isArray(collection)) {
var list = collection; const list = collection;
this._length = collection.length; this._length = collection.length;
for (index = 0; index < this._length; index++) { for (let index = 0; index < this._length; index++) {
item = list[index]; item = list[index];
itemTrackBy = this._trackByFn(index, item); itemTrackBy = this._trackByFn(index, item);
if (record === null || !looseIdentical(record.trackById, itemTrackBy)) { if (record === null || !looseIdentical(record.trackById, itemTrackBy)) {
@ -700,11 +700,10 @@ class _DuplicateMap {
map = new Map<any, _DuplicateItemRecordList>(); map = new Map<any, _DuplicateItemRecordList>();
put(record: CollectionChangeRecord) { put(record: CollectionChangeRecord) {
// todo(vicb) handle corner cases const key = record.trackById;
var key = getMapKey(record.trackById);
var duplicates = this.map.get(key); let duplicates = this.map.get(key);
if (!isPresent(duplicates)) { if (!duplicates) {
duplicates = new _DuplicateItemRecordList(); duplicates = new _DuplicateItemRecordList();
this.map.set(key, duplicates); this.map.set(key, duplicates);
} }
@ -719,9 +718,8 @@ class _DuplicateMap {
* have any more `a`s needs to return the last `a` not the first or second. * have any more `a`s needs to return the last `a` not the first or second.
*/ */
get(trackById: any, afterIndex: number = null): CollectionChangeRecord { get(trackById: any, afterIndex: number = null): CollectionChangeRecord {
var key = getMapKey(trackById); const key = trackById;
const recordList = this.map.get(key);
var recordList = this.map.get(key);
return recordList ? recordList.get(trackById, afterIndex) : null; return recordList ? recordList.get(trackById, afterIndex) : null;
} }
@ -731,10 +729,8 @@ class _DuplicateMap {
* The list of duplicates also is removed from the map if it gets empty. * The list of duplicates also is removed from the map if it gets empty.
*/ */
remove(record: CollectionChangeRecord): CollectionChangeRecord { remove(record: CollectionChangeRecord): CollectionChangeRecord {
var key = getMapKey(record.trackById); const key = record.trackById;
// todo(vicb) const recordList: _DuplicateItemRecordList = this.map.get(key);
// assert(this.map.containsKey(key));
var recordList: _DuplicateItemRecordList = this.map.get(key);
// Remove the list of duplicates when it gets empty // Remove the list of duplicates when it gets empty
if (recordList.remove(record)) { if (recordList.remove(record)) {
this.map.delete(key); this.map.delete(key);

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {isFunction, stringify} from '../facade/lang'; import {stringify} from '../facade/lang';
import {Type} from '../type'; import {Type} from '../type';
@ -51,7 +51,7 @@ export function forwardRef(forwardRefFn: ForwardRefFn): Type<any> {
* @experimental * @experimental
*/ */
export function resolveForwardRef(type: any): any { export function resolveForwardRef(type: any): any {
if (isFunction(type) && type.hasOwnProperty('__forward_ref__') && if (typeof type === 'function' && type.hasOwnProperty('__forward_ref__') &&
type.__forward_ref__ === forwardRef) { type.__forward_ref__ === forwardRef) {
return (<ForwardRefFn>type)(); return (<ForwardRefFn>type)();
} else { } else {

View File

@ -7,7 +7,7 @@
*/ */
import {ListWrapper, MapWrapper} from '../facade/collection'; import {ListWrapper, MapWrapper} from '../facade/collection';
import {isArray, isBlank, isPresent} from '../facade/lang'; import {isBlank, isPresent} from '../facade/lang';
import {reflector} from '../reflection/reflection'; import {reflector} from '../reflection/reflection';
import {Type} from '../type'; import {Type} from '../type';
@ -225,7 +225,7 @@ function _extractToken(
var token: any /** TODO #9100 */ = null; var token: any /** TODO #9100 */ = null;
var optional = false; var optional = false;
if (!isArray(metadata)) { if (!Array.isArray(metadata)) {
if (metadata instanceof Inject) { if (metadata instanceof Inject) {
return _createDependency(metadata.token, optional, null, null, depProps); return _createDependency(metadata.token, optional, null, null, depProps);
} else { } else {

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {global, isFunction, isPresent, stringify} from '../facade/lang'; import {global, isPresent, stringify} from '../facade/lang';
import {Type} from '../type'; import {Type} from '../type';
import {PlatformReflectionCapabilities} from './platform_reflection_capabilities'; import {PlatformReflectionCapabilities} from './platform_reflection_capabilities';
@ -81,7 +81,7 @@ export class ReflectionCapabilities implements PlatformReflectionCapabilities {
// Prefer the direct API. // Prefer the direct API.
if ((<any>typeOrFunc).annotations) { if ((<any>typeOrFunc).annotations) {
let annotations = (<any>typeOrFunc).annotations; let annotations = (<any>typeOrFunc).annotations;
if (isFunction(annotations) && annotations.annotations) { if (typeof annotations === 'function' && annotations.annotations) {
annotations = annotations.annotations; annotations = annotations.annotations;
} }
return annotations; return annotations;
@ -104,7 +104,7 @@ export class ReflectionCapabilities implements PlatformReflectionCapabilities {
// Prefer the direct API. // Prefer the direct API.
if ((<any>typeOrFunc).propMetadata) { if ((<any>typeOrFunc).propMetadata) {
let propMetadata = (<any>typeOrFunc).propMetadata; let propMetadata = (<any>typeOrFunc).propMetadata;
if (isFunction(propMetadata) && propMetadata.propMetadata) { if (typeof propMetadata === 'function' && propMetadata.propMetadata) {
propMetadata = propMetadata.propMetadata; propMetadata = propMetadata.propMetadata;
} }
return propMetadata; return propMetadata;

View File

@ -10,7 +10,6 @@ import {DefaultIterableDiffer, DefaultIterableDifferFactory} from '@angular/core
import {beforeEach, describe, expect, it} from '@angular/core/testing/testing_internal'; import {beforeEach, describe, expect, it} from '@angular/core/testing/testing_internal';
import {ListWrapper} from '../../../src/facade/collection'; import {ListWrapper} from '../../../src/facade/collection';
import {NumberWrapper} from '../../../src/facade/lang';
import {TestIterable} from '../../change_detection/iterable'; import {TestIterable} from '../../change_detection/iterable';
import {iterableChangesAsString} from '../../change_detection/util'; import {iterableChangesAsString} from '../../change_detection/util';
@ -207,17 +206,15 @@ export function main() {
}); });
it('should ignore [NaN] != [NaN] (JS)', () => { it('should ignore [NaN] != [NaN] (JS)', () => {
let l = [NumberWrapper.NaN]; let l = [NaN];
differ.check(l); differ.check(l);
differ.check(l); differ.check(l);
expect(differ.toString()).toEqual(iterableChangesAsString({ expect(differ.toString())
collection: [NumberWrapper.NaN], .toEqual(iterableChangesAsString({collection: [NaN], previous: [NaN]}));
previous: [NumberWrapper.NaN]
}));
}); });
it('should detect [NaN] moves', () => { it('should detect [NaN] moves', () => {
let l = [NumberWrapper.NaN, NumberWrapper.NaN]; let l = [NaN, NaN];
differ.check(l); differ.check(l);
ListWrapper.insert<any>(l, 0, 'foo'); ListWrapper.insert<any>(l, 0, 'foo');

View File

@ -17,7 +17,6 @@ import {DomRootRenderer} from '@angular/platform-browser/src/dom/dom_renderer';
import {MockSchemaRegistry} from '../../../compiler/testing/index'; import {MockSchemaRegistry} from '../../../compiler/testing/index';
import {EventEmitter} from '../../src/facade/async'; import {EventEmitter} from '../../src/facade/async';
import {NumberWrapper} from '../../src/facade/lang';
export function main() { export function main() {
let elSchema: MockSchemaRegistry; let elSchema: MockSchemaRegistry;
@ -338,7 +337,7 @@ export function main() {
it('should support NaN', fakeAsync(() => { it('should support NaN', fakeAsync(() => {
var ctx = _bindSimpleValue('age', Person); var ctx = _bindSimpleValue('age', Person);
ctx.componentInstance.age = NumberWrapper.NaN; ctx.componentInstance.age = NaN;
ctx.detectChanges(false); ctx.detectChanges(false);
expect(renderLog.log).toEqual(['someProp=NaN']); expect(renderLog.log).toEqual(['someProp=NaN']);

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {getSymbolIterator, isArray, isBlank, isJsObject, isPresent} from './lang'; import {getSymbolIterator, isBlank, isJsObject, isPresent} from './lang';
// Safari doesn't implement MapIterator.next(), which is used is Traceur's polyfill of Array.from // Safari doesn't implement MapIterator.next(), which is used is Traceur's polyfill of Array.from
// TODO(mlaval): remove the work around once we have a working polyfill of Array.from // TODO(mlaval): remove the work around once we have a working polyfill of Array.from
@ -193,9 +193,9 @@ export class ListWrapper {
function _flattenArray(source: any[], target: any[]): any[] { function _flattenArray(source: any[], target: any[]): any[] {
if (isPresent(source)) { if (isPresent(source)) {
for (var i = 0; i < source.length; i++) { for (let i = 0; i < source.length; i++) {
var item = source[i]; const item = source[i];
if (isArray(item)) { if (Array.isArray(item)) {
_flattenArray(item, target); _flattenArray(item, target);
} else { } else {
target.push(item); target.push(item);
@ -208,14 +208,14 @@ function _flattenArray(source: any[], target: any[]): any[] {
export function isListLikeIterable(obj: any): boolean { export function isListLikeIterable(obj: any): boolean {
if (!isJsObject(obj)) return false; if (!isJsObject(obj)) return false;
return isArray(obj) || return Array.isArray(obj) ||
(!(obj instanceof Map) && // JS Map are iterables but return entries as [k, v] (!(obj instanceof Map) && // JS Map are iterables but return entries as [k, v]
getSymbolIterator() in obj); // JS Iterable have a Symbol.iterator prop getSymbolIterator() in obj); // JS Iterable have a Symbol.iterator prop
} }
export function areIterablesEqual(a: any, b: any, comparator: Function): boolean { export function areIterablesEqual(a: any, b: any, comparator: Function): boolean {
var iterator1 = a[getSymbolIterator()](); const iterator1 = a[getSymbolIterator()]();
var iterator2 = b[getSymbolIterator()](); const iterator2 = b[getSymbolIterator()]();
while (true) { while (true) {
let item1 = iterator1.next(); let item1 = iterator1.next();
@ -227,13 +227,13 @@ export function areIterablesEqual(a: any, b: any, comparator: Function): boolean
} }
export function iterateListLike(obj: any, fn: Function) { export function iterateListLike(obj: any, fn: Function) {
if (isArray(obj)) { if (Array.isArray(obj)) {
for (var i = 0; i < obj.length; i++) { for (var i = 0; i < obj.length; i++) {
fn(obj[i]); fn(obj[i]);
} }
} else { } else {
var iterator = obj[getSymbolIterator()](); const iterator = obj[getSymbolIterator()]();
var item: any /** TODO #???? */; let item: any;
while (!((item = iterator.next()).done)) { while (!((item = iterator.next()).done)) {
fn(item.value); fn(item.value);
} }

View File

@ -77,37 +77,9 @@ export function isBlank(obj: any): boolean {
return obj === undefined || obj === null; return obj === undefined || obj === null;
} }
export function isBoolean(obj: any): boolean {
return typeof obj === 'boolean';
}
export function isNumber(obj: any): boolean {
return typeof obj === 'number';
}
export function isString(obj: any): obj is string {
return typeof obj === 'string';
}
export function isFunction(obj: any): boolean {
return typeof obj === 'function';
}
export function isType(obj: any): boolean {
return isFunction(obj);
}
export function isStringMap(obj: any): obj is Object {
return typeof obj === 'object' && obj !== null;
}
const STRING_MAP_PROTO = Object.getPrototypeOf({}); const STRING_MAP_PROTO = Object.getPrototypeOf({});
export function isStrictStringMap(obj: any): boolean { export function isStrictStringMap(obj: any): boolean {
return isStringMap(obj) && Object.getPrototypeOf(obj) === STRING_MAP_PROTO; return typeof obj === 'object' && obj !== null && Object.getPrototypeOf(obj) === STRING_MAP_PROTO;
}
export function isArray(obj: any): boolean {
return Array.isArray(obj);
} }
export function isDate(obj: any): obj is Date { export function isDate(obj: any): obj is Date {
@ -137,22 +109,9 @@ export function stringify(token: any): string {
return newLineIndex === -1 ? res : res.substring(0, newLineIndex); return newLineIndex === -1 ? res : res.substring(0, newLineIndex);
} }
export class StringJoiner {
constructor(public parts: string[] = []) {}
add(part: string): void { this.parts.push(part); }
toString(): string { return this.parts.join(''); }
}
export class NumberWrapper { export class NumberWrapper {
static toFixed(n: number, fractionDigits: number): string { return n.toFixed(fractionDigits); }
static equal(a: number, b: number): boolean { return a === b; }
static parseIntAutoRadix(text: string): number { static parseIntAutoRadix(text: string): number {
var result: number = parseInt(text); const result: number = parseInt(text);
if (isNaN(result)) { if (isNaN(result)) {
throw new Error('Invalid integer literal when parsing ' + text); throw new Error('Invalid integer literal when parsing ' + text);
} }
@ -169,7 +128,7 @@ export class NumberWrapper {
return parseInt(text, radix); return parseInt(text, radix);
} }
} else { } else {
var result: number = parseInt(text, radix); const result = parseInt(text, radix);
if (!isNaN(result)) { if (!isNaN(result)) {
return result; return result;
} }
@ -177,21 +136,7 @@ export class NumberWrapper {
throw new Error('Invalid integer literal when parsing ' + text + ' in base ' + radix); throw new Error('Invalid integer literal when parsing ' + text + ' in base ' + radix);
} }
static get NaN(): number { return NaN; }
static isNumeric(value: any): boolean { return !isNaN(value - parseFloat(value)); } static isNumeric(value: any): boolean { return !isNaN(value - parseFloat(value)); }
static isNaN(value: any): boolean { return isNaN(value); }
static isInteger(value: any): boolean { return Number.isInteger(value); }
}
export var RegExp = _global.RegExp;
export class FunctionWrapper {
static apply(fn: Function, posArgs: any): any { return fn.apply(null, posArgs); }
static bind(fn: Function, scope: any): Function { return fn.bind(scope); }
} }
// JS has NaN !== NaN // JS has NaN !== NaN
@ -199,12 +144,6 @@ export function looseIdentical(a: any, b: any): boolean {
return a === b || typeof a === 'number' && typeof b === 'number' && isNaN(a) && isNaN(b); return a === b || typeof a === 'number' && typeof b === 'number' && isNaN(a) && isNaN(b);
} }
// JS considers NaN is the same as NaN for map Key (while NaN !== NaN otherwise)
// see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
export function getMapKey<T>(value: T): T {
return value;
}
export function normalizeBlank(obj: Object): any { export function normalizeBlank(obj: Object): any {
return isBlank(obj) ? null : obj; return isBlank(obj) ? null : obj;
} }
@ -225,15 +164,6 @@ export function warn(obj: Error | Object) {
console.warn(obj); console.warn(obj);
} }
// Can't be all uppercase as our transpiler would think it is a special directive...
export class Json {
static parse(s: string): Object { return _global.JSON.parse(s); }
static stringify(data: Object): string {
// Dart doesn't take 3 arguments
return _global.JSON.stringify(data, null, 2);
}
}
export function setValueOnPath(global: any, path: string, value: any) { export function setValueOnPath(global: any, path: string, value: any) {
var parts = path.split('.'); var parts = path.split('.');
var obj: any = global; var obj: any = global;
@ -273,30 +203,10 @@ export function getSymbolIterator(): string|symbol {
return _symbolIterator; return _symbolIterator;
} }
export function evalExpression(
sourceUrl: string, expr: string, declarations: string, vars: {[key: string]: any}): any {
var fnBody = `${declarations}\nreturn ${expr}\n//# sourceURL=${sourceUrl}`;
var fnArgNames: string[] = [];
var fnArgValues: any[] = [];
for (var argName in vars) {
fnArgNames.push(argName);
fnArgValues.push(vars[argName]);
}
return new Function(...fnArgNames.concat(fnBody))(...fnArgValues);
}
export function isPrimitive(obj: any): boolean { export function isPrimitive(obj: any): boolean {
return !isJsObject(obj); return !isJsObject(obj);
} }
export function hasConstructor(value: Object, type: any): boolean {
return value.constructor === type;
}
export function escape(s: string): string {
return _global.encodeURI(s);
}
export function escapeRegExp(s: string): string { export function escapeRegExp(s: string): string {
return s.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1'); return s.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
} }

View File

@ -1,12 +0,0 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {global} from './lang';
export var Math = global.Math;
export var NaN: any /** TODO #???? */ = typeof NaN;

View File

@ -6,10 +6,7 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {NumberWrapper, escapeRegExp, hasConstructor} from '../src/lang'; import {NumberWrapper, escapeRegExp} from '../src/lang';
class MySuperclass {}
class MySubclass extends MySuperclass {}
export function main() { export function main() {
describe('RegExp', () => { describe('RegExp', () => {
@ -22,13 +19,6 @@ export function main() {
}); });
describe('const', () => {
it('should support const expressions both in TS and Dart', () => {
const numbers = [1, 2, 3];
expect(numbers).toEqual([1, 2, 3]);
});
});
describe('Number', () => { describe('Number', () => {
describe('isNumeric', () => { describe('isNumeric', () => {
it('should return true when passing correct numeric string', it('should return true when passing correct numeric string',

View File

@ -9,7 +9,7 @@
import {Directive, ElementRef, Host, Input, OnDestroy, OpaqueToken, Optional, Renderer, Type, forwardRef} from '@angular/core'; import {Directive, ElementRef, Host, Input, OnDestroy, OpaqueToken, Optional, Renderer, Type, forwardRef} from '@angular/core';
import {MapWrapper} from '../facade/collection'; import {MapWrapper} from '../facade/collection';
import {isBlank, isPresent, isPrimitive, isString, looseIdentical} from '../facade/lang'; import {isBlank, isPresent, isPrimitive, looseIdentical} from '../facade/lang';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor'; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor';
@ -21,7 +21,7 @@ export const SELECT_MULTIPLE_VALUE_ACCESSOR = {
function _buildValueString(id: string, value: any): string { function _buildValueString(id: string, value: any): string {
if (isBlank(id)) return `${value}`; if (isBlank(id)) return `${value}`;
if (isString(value)) value = `'${value}'`; if (typeof value === 'string') value = `'${value}'`;
if (!isPrimitive(value)) value = 'Object'; if (!isPrimitive(value)) value = 'Object';
return `${id}: ${value}`.slice(0, 50); return `${id}: ${value}`.slice(0, 50);
} }

View File

@ -6,9 +6,7 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {isBlank, isPresent, looseIdentical} from '../facade/lang';
import {ListWrapper} from '../facade/collection';
import {hasConstructor, isBlank, isPresent, looseIdentical} from '../facade/lang';
import {FormArray, FormControl, FormGroup} from '../model'; import {FormArray, FormControl, FormGroup} from '../model';
import {Validators} from '../validators'; import {Validators} from '../validators';
@ -30,9 +28,7 @@ import {AsyncValidatorFn, Validator, ValidatorFn} from './validators';
export function controlPath(name: string, parent: ControlContainer): string[] { export function controlPath(name: string, parent: ControlContainer): string[] {
var p = ListWrapper.clone(parent.path); return [...parent.path, name];
p.push(name);
return p;
} }
export function setUpControl(control: FormControl, dir: NgControl): void { export function setUpControl(control: FormControl, dir: NgControl): void {
@ -128,14 +124,17 @@ export function isPropertyUpdated(changes: {[key: string]: any}, viewModel: any)
return !looseIdentical(viewModel, change.currentValue); return !looseIdentical(viewModel, change.currentValue);
} }
const BUILTIN_ACCESSORS = [
CheckboxControlValueAccessor,
RangeValueAccessor,
NumberValueAccessor,
SelectControlValueAccessor,
SelectMultipleControlValueAccessor,
RadioControlValueAccessor,
];
export function isBuiltInAccessor(valueAccessor: ControlValueAccessor): boolean { export function isBuiltInAccessor(valueAccessor: ControlValueAccessor): boolean {
return ( return BUILTIN_ACCESSORS.some(a => valueAccessor.constructor === a);
hasConstructor(valueAccessor, CheckboxControlValueAccessor) ||
hasConstructor(valueAccessor, RangeValueAccessor) ||
hasConstructor(valueAccessor, NumberValueAccessor) ||
hasConstructor(valueAccessor, SelectControlValueAccessor) ||
hasConstructor(valueAccessor, SelectMultipleControlValueAccessor) ||
hasConstructor(valueAccessor, RadioControlValueAccessor));
} }
// TODO: vsavkin remove it once https://github.com/angular/angular/issues/3011 is implemented // TODO: vsavkin remove it once https://github.com/angular/angular/issues/3011 is implemented
@ -147,24 +146,24 @@ export function selectValueAccessor(
var builtinAccessor: ControlValueAccessor; var builtinAccessor: ControlValueAccessor;
var customAccessor: ControlValueAccessor; var customAccessor: ControlValueAccessor;
valueAccessors.forEach((v: ControlValueAccessor) => { valueAccessors.forEach((v: ControlValueAccessor) => {
if (hasConstructor(v, DefaultValueAccessor)) { if (v.constructor === DefaultValueAccessor) {
defaultAccessor = v; defaultAccessor = v;
} else if (isBuiltInAccessor(v)) { } else if (isBuiltInAccessor(v)) {
if (isPresent(builtinAccessor)) if (builtinAccessor)
_throwError(dir, 'More than one built-in value accessor matches form control with'); _throwError(dir, 'More than one built-in value accessor matches form control with');
builtinAccessor = v; builtinAccessor = v;
} else { } else {
if (isPresent(customAccessor)) if (customAccessor)
_throwError(dir, 'More than one custom value accessor matches form control with'); _throwError(dir, 'More than one custom value accessor matches form control with');
customAccessor = v; customAccessor = v;
} }
}); });
if (isPresent(customAccessor)) return customAccessor; if (customAccessor) return customAccessor;
if (isPresent(builtinAccessor)) return builtinAccessor; if (builtinAccessor) return builtinAccessor;
if (isPresent(defaultAccessor)) return defaultAccessor; if (defaultAccessor) return defaultAccessor;
_throwError(dir, 'No valid value accessor for form control with'); _throwError(dir, 'No valid value accessor for form control with');
return null; return null;

View File

@ -9,7 +9,7 @@
import {Injectable} from '@angular/core'; import {Injectable} from '@angular/core';
import {AsyncValidatorFn, ValidatorFn} from './directives/validators'; import {AsyncValidatorFn, ValidatorFn} from './directives/validators';
import {isArray, isPresent} from './facade/lang'; import {isPresent} from './facade/lang';
import {AbstractControl, FormArray, FormControl, FormGroup} from './model'; import {AbstractControl, FormArray, FormControl, FormGroup} from './model';
/** /**
@ -86,10 +86,10 @@ export class FormBuilder {
controlConfig instanceof FormArray) { controlConfig instanceof FormArray) {
return controlConfig; return controlConfig;
} else if (isArray(controlConfig)) { } else if (Array.isArray(controlConfig)) {
var value = controlConfig[0]; const value = controlConfig[0];
var validator: ValidatorFn = controlConfig.length > 1 ? controlConfig[1] : null; const validator: ValidatorFn = controlConfig.length > 1 ? controlConfig[1] : null;
var asyncValidator: AsyncValidatorFn = controlConfig.length > 2 ? controlConfig[2] : null; const asyncValidator: AsyncValidatorFn = controlConfig.length > 2 ? controlConfig[2] : null;
return this.control(value, validator, asyncValidator); return this.control(value, validator, asyncValidator);
} else { } else {

View File

@ -11,8 +11,7 @@ import {fromPromise} from 'rxjs/observable/fromPromise';
import {composeAsyncValidators, composeValidators} from './directives/shared'; import {composeAsyncValidators, composeValidators} from './directives/shared';
import {AsyncValidatorFn, ValidatorFn} from './directives/validators'; import {AsyncValidatorFn, ValidatorFn} from './directives/validators';
import {EventEmitter, Observable} from './facade/async'; import {EventEmitter, Observable} from './facade/async';
import {StringMapWrapper} from './facade/collection'; import {isBlank, isPresent, normalizeBool} from './facade/lang';
import {isBlank, isPresent, isStringMap, normalizeBool} from './facade/lang';
import {isPromise} from './private_import_core'; import {isPromise} from './private_import_core';
@ -605,8 +604,8 @@ export abstract class AbstractControl {
/** @internal */ /** @internal */
_isBoxedValue(formState: any): boolean { _isBoxedValue(formState: any): boolean {
return isStringMap(formState) && Object.keys(formState).length === 2 && 'value' in formState && return typeof formState === 'object' && formState !== null &&
'disabled' in formState; Object.keys(formState).length === 2 && 'value' in formState && 'disabled' in formState;
} }
/** @internal */ /** @internal */

View File

@ -13,7 +13,7 @@ import {Observer} from 'rxjs/Observer';
import {ResponseOptions} from '../base_response_options'; import {ResponseOptions} from '../base_response_options';
import {ContentType, ReadyState, RequestMethod, ResponseContentType, ResponseType} from '../enums'; import {ContentType, ReadyState, RequestMethod, ResponseContentType, ResponseType} from '../enums';
import {isPresent, isString} from '../facade/lang'; import {isPresent} from '../facade/lang';
import {Headers} from '../headers'; import {Headers} from '../headers';
import {getResponseURL, isSuccess} from '../http_utils'; import {getResponseURL, isSuccess} from '../http_utils';
import {Connection, ConnectionBackend, XSRFStrategy} from '../interfaces'; import {Connection, ConnectionBackend, XSRFStrategy} from '../interfaces';
@ -57,7 +57,7 @@ export class XHRConnection implements Connection {
// by IE10) // by IE10)
let body = _xhr.response === undefined ? _xhr.responseText : _xhr.response; let body = _xhr.response === undefined ? _xhr.responseText : _xhr.response;
// Implicitly strip a potential XSSI prefix. // Implicitly strip a potential XSSI prefix.
if (isString(body)) body = body.replace(XSSI_PREFIX, ''); if (typeof body === 'string') body = body.replace(XSSI_PREFIX, '');
let headers = Headers.fromResponseHeaderString(_xhr.getAllResponseHeaders()); let headers = Headers.fromResponseHeaderString(_xhr.getAllResponseHeaders());
let url = getResponseURL(_xhr); let url = getResponseURL(_xhr);

View File

@ -8,7 +8,7 @@
import {Injectable} from '@angular/core'; import {Injectable} from '@angular/core';
import {isPresent, isString} from '../src/facade/lang'; import {isPresent} from '../src/facade/lang';
import {RequestMethod, ResponseContentType} from './enums'; import {RequestMethod, ResponseContentType} from './enums';
import {Headers} from './headers'; import {Headers} from './headers';
@ -82,7 +82,8 @@ export class RequestOptions {
this.body = isPresent(body) ? body : null; this.body = isPresent(body) ? body : null;
this.url = isPresent(url) ? url : null; this.url = isPresent(url) ? url : null;
this.search = isPresent(search) ? this.search = isPresent(search) ?
(isString(search) ? new URLSearchParams(<string>(search)) : <URLSearchParams>(search)) : (typeof search === 'string' ? new URLSearchParams(<string>(search)) :
<URLSearchParams>(search)) :
null; null;
this.withCredentials = isPresent(withCredentials) ? withCredentials : null; this.withCredentials = isPresent(withCredentials) ? withCredentials : null;
this.responseType = isPresent(responseType) ? responseType : null; this.responseType = isPresent(responseType) ? responseType : null;
@ -115,19 +116,18 @@ export class RequestOptions {
*/ */
merge(options?: RequestOptionsArgs): RequestOptions { merge(options?: RequestOptionsArgs): RequestOptions {
return new RequestOptions({ return new RequestOptions({
method: isPresent(options) && isPresent(options.method) ? options.method : this.method, method: options && isPresent(options.method) ? options.method : this.method,
headers: isPresent(options) && isPresent(options.headers) ? options.headers : this.headers, headers: options && isPresent(options.headers) ? options.headers : this.headers,
body: isPresent(options) && isPresent(options.body) ? options.body : this.body, body: options && isPresent(options.body) ? options.body : this.body,
url: isPresent(options) && isPresent(options.url) ? options.url : this.url, url: options && isPresent(options.url) ? options.url : this.url,
search: isPresent(options) && isPresent(options.search) ? search: options && isPresent(options.search) ?
(isString(options.search) ? new URLSearchParams(<string>(options.search)) : (typeof options.search === 'string' ? new URLSearchParams(options.search) :
(<URLSearchParams>(options.search)).clone()) : (<URLSearchParams>(options.search)).clone()) :
this.search, this.search,
withCredentials: isPresent(options) && isPresent(options.withCredentials) ? withCredentials: options && isPresent(options.withCredentials) ? options.withCredentials :
options.withCredentials : this.withCredentials,
this.withCredentials, responseType: options && isPresent(options.responseType) ? options.responseType :
responseType: isPresent(options) && isPresent(options.responseType) ? options.responseType : this.responseType
this.responseType
}); });
} }
} }

View File

@ -6,8 +6,6 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {Json, isString} from '../src/facade/lang';
import {isJsObject, stringToArrayBuffer} from './http_utils'; import {isJsObject, stringToArrayBuffer} from './http_utils';
import {URLSearchParams} from './url_search_params'; import {URLSearchParams} from './url_search_params';
@ -26,12 +24,12 @@ export abstract class Body {
* Attempts to return body as parsed `JSON` object, or raises an exception. * Attempts to return body as parsed `JSON` object, or raises an exception.
*/ */
json(): any { json(): any {
if (isString(this._body)) { if (typeof this._body === 'string') {
return Json.parse(<string>this._body); return JSON.parse(<string>this._body);
} }
if (this._body instanceof ArrayBuffer) { if (this._body instanceof ArrayBuffer) {
return Json.parse(this.text()); return JSON.parse(this.text());
} }
return this._body; return this._body;
@ -54,7 +52,7 @@ export abstract class Body {
} }
if (isJsObject(this._body)) { if (isJsObject(this._body)) {
return Json.stringify(this._body); return JSON.stringify(this._body, null, 2);
} }
return this._body.toString(); return this._body.toString();

View File

@ -8,7 +8,7 @@
import {Injectable} from '@angular/core'; import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable'; import {Observable} from 'rxjs/Observable';
import {isPresent, isString} from '../src/facade/lang'; import {isPresent} from '../src/facade/lang';
import {BaseRequestOptions, RequestOptions} from './base_request_options'; import {BaseRequestOptions, RequestOptions} from './base_request_options';
import {RequestMethod} from './enums'; import {RequestMethod} from './enums';
import {ConnectionBackend, RequestOptionsArgs} from './interfaces'; import {ConnectionBackend, RequestOptionsArgs} from './interfaces';
@ -114,7 +114,7 @@ export class Http {
*/ */
request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> { request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
let responseObservable: any; let responseObservable: any;
if (isString(url)) { if (typeof url === 'string') {
responseObservable = httpRequest( responseObservable = httpRequest(
this._backend, this._backend,
new Request(mergeOptions(this._defaultOptions, options, RequestMethod.Get, <string>url))); new Request(mergeOptions(this._defaultOptions, options, RequestMethod.Get, <string>url)));
@ -212,7 +212,7 @@ export class Jsonp extends Http {
*/ */
request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> { request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
let responseObservable: any; let responseObservable: any;
if (isString(url)) { if (typeof url === 'string') {
url = url =
new Request(mergeOptions(this._defaultOptions, options, RequestMethod.Get, <string>url)); new Request(mergeOptions(this._defaultOptions, options, RequestMethod.Get, <string>url));
} }

View File

@ -6,12 +6,11 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {isString} from '../src/facade/lang';
import {RequestMethod} from './enums'; import {RequestMethod} from './enums';
export function normalizeMethodName(method: string | RequestMethod): RequestMethod { export function normalizeMethodName(method: string | RequestMethod): RequestMethod {
if (!isString(method)) return method; if (typeof method !== 'string') return method;
switch (method.toUpperCase()) { switch (method.toUpperCase()) {
case 'GET': case 'GET':
return RequestMethod.Get; return RequestMethod.Get;

View File

@ -15,7 +15,6 @@ import {CookieXSRFStrategy, XHRBackend, XHRConnection} from '../../src/backends/
import {BaseRequestOptions, RequestOptions} from '../../src/base_request_options'; import {BaseRequestOptions, RequestOptions} from '../../src/base_request_options';
import {BaseResponseOptions, ResponseOptions} from '../../src/base_response_options'; import {BaseResponseOptions, ResponseOptions} from '../../src/base_response_options';
import {ResponseContentType, ResponseType} from '../../src/enums'; import {ResponseContentType, ResponseType} from '../../src/enums';
import {Json} from '../../src/facade/lang';
import {Headers} from '../../src/headers'; import {Headers} from '../../src/headers';
import {XSRFStrategy} from '../../src/interfaces'; import {XSRFStrategy} from '../../src/interfaces';
import {Request} from '../../src/static_request'; import {Request} from '../../src/static_request';
@ -257,7 +256,7 @@ export function main() {
var connection = new XHRConnection( var connection = new XHRConnection(
new Request(base.merge(new RequestOptions({body: body}))), new MockBrowserXHR()); new Request(base.merge(new RequestOptions({body: body}))), new MockBrowserXHR());
connection.response.subscribe(); connection.response.subscribe();
expect(sendSpy).toHaveBeenCalledWith(Json.stringify(body)); expect(sendSpy).toHaveBeenCalledWith(JSON.stringify(body, null, 2));
expect(setRequestHeaderSpy).toHaveBeenCalledWith('content-type', 'application/json'); expect(setRequestHeaderSpy).toHaveBeenCalledWith('content-type', 'application/json');
}); });

View File

@ -14,7 +14,6 @@ import {Observable} from 'rxjs/Observable';
import {zip} from 'rxjs/observable/zip'; import {zip} from 'rxjs/observable/zip';
import {BaseRequestOptions, ConnectionBackend, Http, HttpModule, JSONPBackend, Jsonp, JsonpModule, Request, RequestMethod, RequestOptions, Response, ResponseContentType, ResponseOptions, URLSearchParams, XHRBackend} from '../index'; import {BaseRequestOptions, ConnectionBackend, Http, HttpModule, JSONPBackend, Jsonp, JsonpModule, Request, RequestMethod, RequestOptions, Response, ResponseContentType, ResponseOptions, URLSearchParams, XHRBackend} from '../index';
import {Json} from '../src/facade/lang';
import {stringToArrayBuffer} from '../src/http_utils'; import {stringToArrayBuffer} from '../src/http_utils';
import {MockBackend, MockConnection} from '../testing/mock_backend'; import {MockBackend, MockConnection} from '../testing/mock_backend';
@ -460,7 +459,7 @@ export function main() {
c.mockRespond(new Response(new ResponseOptions({body: simpleObject})))); c.mockRespond(new Response(new ResponseOptions({body: simpleObject}))));
http.get('https://www.google.com').subscribe((res: Response) => { http.get('https://www.google.com').subscribe((res: Response) => {
expect(res.arrayBuffer()).toBeAnInstanceOf(ArrayBuffer); expect(res.arrayBuffer()).toBeAnInstanceOf(ArrayBuffer);
expect(res.text()).toEqual(Json.stringify(simpleObject)); expect(res.text()).toEqual(JSON.stringify(simpleObject, null, 2));
expect(res.json()).toBe(simpleObject); expect(res.json()).toBe(simpleObject);
async.done(); async.done();
}); });
@ -500,11 +499,11 @@ export function main() {
let body = (): any => { let body = (): any => {
switch (c.request.responseType) { switch (c.request.responseType) {
case ResponseContentType.Text: case ResponseContentType.Text:
return Json.stringify(message); return JSON.stringify(message, null, 2);
case ResponseContentType.Json: case ResponseContentType.Json:
return message; return message;
case ResponseContentType.ArrayBuffer: case ResponseContentType.ArrayBuffer:
return stringToArrayBuffer(Json.stringify(message)); return stringToArrayBuffer(JSON.stringify(message, null, 2));
} }
}; };
c.mockRespond(new Response(new ResponseOptions({body: body()}))); c.mockRespond(new Response(new ResponseOptions({body: body()})));

View File

@ -53,20 +53,20 @@ export class AngularProfiler {
* ``` * ```
*/ */
timeChangeDetection(config: any): ChangeDetectionPerfRecord { timeChangeDetection(config: any): ChangeDetectionPerfRecord {
var record = isPresent(config) && config['record']; var record = config && config['record'];
var profileName = 'Change Detection'; var profileName = 'Change Detection';
// Profiler is not available in Android browsers, nor in IE 9 without dev tools opened // Profiler is not available in Android browsers, nor in IE 9 without dev tools opened
var isProfilerAvailable = isPresent(window.console.profile); var isProfilerAvailable = isPresent(window.console.profile);
if (record && isProfilerAvailable) { if (record && isProfilerAvailable) {
window.console.profile(profileName); window.console.profile(profileName);
} }
var start = getDOM().performanceNow(); const start = getDOM().performanceNow();
var numTicks = 0; var numTicks = 0;
while (numTicks < 5 || (getDOM().performanceNow() - start) < 500) { while (numTicks < 5 || (getDOM().performanceNow() - start) < 500) {
this.appRef.tick(); this.appRef.tick();
numTicks++; numTicks++;
} }
var end = getDOM().performanceNow(); const end = getDOM().performanceNow();
if (record && isProfilerAvailable) { if (record && isProfilerAvailable) {
// need to cast to <any> because type checker thinks there's no argument // need to cast to <any> because type checker thinks there's no argument
// while in fact there is: // while in fact there is:
@ -74,9 +74,9 @@ export class AngularProfiler {
// https://developer.mozilla.org/en-US/docs/Web/API/Console/profileEnd // https://developer.mozilla.org/en-US/docs/Web/API/Console/profileEnd
(<any>window.console.profileEnd)(profileName); (<any>window.console.profileEnd)(profileName);
} }
var msPerTick = (end - start) / numTicks; const msPerTick = (end - start) / numTicks;
window.console.log(`ran ${numTicks} change detection cycles`); window.console.log(`ran ${numTicks} change detection cycles`);
window.console.log(`${NumberWrapper.toFixed(msPerTick, 2)} ms per check`); window.console.log(`${msPerTick.toFixed(2)} ms per check`);
return new ChangeDetectionPerfRecord(msPerTick, numTicks); return new ChangeDetectionPerfRecord(msPerTick, numTicks);
} }

View File

@ -7,7 +7,7 @@
*/ */
import {Inject, Injectable, RenderComponentType, Renderer, RootRenderer, ViewEncapsulation} from '@angular/core'; import {Inject, Injectable, RenderComponentType, Renderer, RootRenderer, ViewEncapsulation} from '@angular/core';
import {Json, isArray, isBlank, isPresent, isString, stringify} from '../facade/lang'; import {isBlank, isPresent, stringify} from '../facade/lang';
import {AnimationKeyframe, AnimationPlayer, AnimationStyles, RenderDebugInfo} from '../private_import_core'; import {AnimationKeyframe, AnimationPlayer, AnimationStyles, RenderDebugInfo} from '../private_import_core';
import {AnimationDriver} from './animation_driver'; import {AnimationDriver} from './animation_driver';
@ -74,7 +74,7 @@ export class DomRenderer implements Renderer {
selectRootElement(selectorOrNode: string|any, debugInfo: RenderDebugInfo): Element { selectRootElement(selectorOrNode: string|any, debugInfo: RenderDebugInfo): Element {
var el: any /** TODO #9100 */; var el: any /** TODO #9100 */;
if (isString(selectorOrNode)) { if (typeof selectorOrNode === 'string') {
el = getDOM().querySelector(this._rootRenderer.document, selectorOrNode); el = getDOM().querySelector(this._rootRenderer.document, selectorOrNode);
if (isBlank(el)) { if (isBlank(el)) {
throw new Error(`The selector "${selectorOrNode}" did not match any elements`); throw new Error(`The selector "${selectorOrNode}" did not match any elements`);
@ -194,10 +194,11 @@ export class DomRenderer implements Renderer {
if (getDOM().isCommentNode(renderElement)) { if (getDOM().isCommentNode(renderElement)) {
const existingBindings = const existingBindings =
getDOM().getText(renderElement).replace(/\n/g, '').match(TEMPLATE_BINDINGS_EXP); getDOM().getText(renderElement).replace(/\n/g, '').match(TEMPLATE_BINDINGS_EXP);
var parsedBindings = Json.parse(existingBindings[1]); var parsedBindings = JSON.parse(existingBindings[1]);
(parsedBindings as any /** TODO #9100 */)[dashCasedPropertyName] = propertyValue; (parsedBindings as any /** TODO #9100 */)[dashCasedPropertyName] = propertyValue;
getDOM().setText( getDOM().setText(
renderElement, TEMPLATE_COMMENT_TEXT.replace('{}', Json.stringify(parsedBindings))); renderElement,
TEMPLATE_COMMENT_TEXT.replace('{}', JSON.stringify(parsedBindings, null, 2)));
} else { } else {
this.setElementAttribute(renderElement, propertyName, propertyValue); this.setElementAttribute(renderElement, propertyName, propertyValue);
} }
@ -279,9 +280,10 @@ function _shimHostAttribute(componentShortId: string): string {
} }
function _flattenStyles(compId: string, styles: Array<any|any[]>, target: string[]): string[] { function _flattenStyles(compId: string, styles: Array<any|any[]>, target: string[]): string[] {
for (var i = 0; i < styles.length; i++) { for (let i = 0; i < styles.length; i++) {
var style = styles[i]; let style = styles[i];
if (isArray(style)) {
if (Array.isArray(style)) {
_flattenStyles(compId, style, target); _flattenStyles(compId, style, target);
} else { } else {
style = style.replace(COMPONENT_REGEX, compId); style = style.replace(COMPONENT_REGEX, compId);

View File

@ -8,7 +8,7 @@
import {AUTO_STYLE} from '@angular/core'; import {AUTO_STYLE} from '@angular/core';
import {isNumber, isPresent} from '../facade/lang'; import {isPresent} from '../facade/lang';
import {AnimationKeyframe, AnimationStyles} from '../private_import_core'; import {AnimationKeyframe, AnimationStyles} from '../private_import_core';
import {AnimationDriver} from './animation_driver'; import {AnimationDriver} from './animation_driver';
@ -83,7 +83,7 @@ function _resolveStyleUnit(
val: string | number, userProvidedProp: string, formattedProp: string): string { val: string | number, userProvidedProp: string, formattedProp: string): string {
var unit = ''; var unit = '';
if (_isPixelDimensionStyle(formattedProp) && val != 0 && val != '0') { if (_isPixelDimensionStyle(formattedProp) && val != 0 && val != '0') {
if (isNumber(val)) { if (typeof val === 'number') {
unit = 'px'; unit = 'px';
} else if (_findDimensionalSuffix(val.toString()).length == 0) { } else if (_findDimensionalSuffix(val.toString()).length == 0) {
throw new Error('Please provide a CSS unit value for ' + userProvidedProp + ':' + val); throw new Error('Please provide a CSS unit value for ' + userProvidedProp + ':' + val);

View File

@ -9,7 +9,7 @@
import {NgZone} from '@angular/core'; import {NgZone} from '@angular/core';
import {ListWrapper} from './facade/collection'; import {ListWrapper} from './facade/collection';
import {global, isPresent, isString} from './facade/lang'; import {global, isPresent} from './facade/lang';
import {getDOM} from './private_import_platform-browser'; import {getDOM} from './private_import_platform-browser';
export class BrowserDetection { export class BrowserDetection {
@ -108,7 +108,7 @@ export function stringifyElement(el: any /** TODO #9100 */): string {
for (let i = 0; i < keys.length; i++) { for (let i = 0; i < keys.length; i++) {
var key = keys[i]; var key = keys[i];
var attValue = attributeMap.get(key); var attValue = attributeMap.get(key);
if (!isString(attValue)) { if (typeof attValue !== 'string') {
result += ` ${key}`; result += ` ${key}`;
} else { } else {
result += ` ${key}="${attValue}"`; result += ` ${key}="${attValue}"`;

View File

@ -7,7 +7,7 @@
*/ */
import {global, isString} from './facade/lang'; import {global} from './facade/lang';
import {getDOM} from './private_import_platform-browser'; import {getDOM} from './private_import_platform-browser';
@ -187,7 +187,7 @@ _global.beforeEach(function() {
return { return {
compare: function(actual: any, styles: {[k: string]: string}|string) { compare: function(actual: any, styles: {[k: string]: string}|string) {
let allPassed: boolean; let allPassed: boolean;
if (isString(styles)) { if (typeof styles === 'string') {
allPassed = getDOM().hasStyle(actual, styles); allPassed = getDOM().hasStyle(actual, styles);
} else { } else {
allPassed = Object.keys(styles).length !== 0; allPassed = Object.keys(styles).length !== 0;
@ -199,9 +199,9 @@ _global.beforeEach(function() {
return { return {
pass: allPassed, pass: allPassed,
get message() { get message() {
const expectedValueStr = isString(styles) ? styles : JSON.stringify(styles); const expectedValueStr = typeof styles === 'string' ? styles : JSON.stringify(styles);
return `Expected ${actual.outerHTML} ${!allPassed ? ' ' : 'not '}to contain the return `Expected ${actual.outerHTML} ${!allPassed ? ' ' : 'not '}to contain the
CSS ${isString(styles) ? 'property' : 'styles'} "${expectedValueStr}"`; CSS ${typeof styles === 'string' ? 'property' : 'styles'} "${expectedValueStr}"`;
} }
}; };
} }

View File

@ -8,7 +8,7 @@
import {Injectable, RenderComponentType, Type, ViewEncapsulation} from '@angular/core'; import {Injectable, RenderComponentType, Type, ViewEncapsulation} from '@angular/core';
import {isArray, isPresent} from '../../facade/lang'; import {isPresent} from '../../facade/lang';
import {RenderStore} from './render_store'; import {RenderStore} from './render_store';
import {LocationType} from './serialized_types'; import {LocationType} from './serialized_types';
@ -30,7 +30,7 @@ export class Serializer {
if (!isPresent(obj)) { if (!isPresent(obj)) {
return null; return null;
} }
if (isArray(obj)) { if (Array.isArray(obj)) {
return (<any[]>obj).map(v => this.serialize(v, type)); return (<any[]>obj).map(v => this.serialize(v, type));
} }
if (type == PRIMITIVE) { if (type == PRIMITIVE) {
@ -38,15 +38,17 @@ export class Serializer {
} }
if (type == RenderStoreObject) { if (type == RenderStoreObject) {
return this._renderStore.serialize(obj); return this._renderStore.serialize(obj);
} else if (type === RenderComponentType) {
return this._serializeRenderComponentType(obj);
} else if (type === ViewEncapsulation) {
return obj;
} else if (type === LocationType) {
return this._serializeLocation(obj);
} else {
throw new Error('No serializer for ' + type.toString());
} }
if (type === RenderComponentType) {
return this._serializeRenderComponentType(obj);
}
if (type === ViewEncapsulation) {
return obj;
}
if (type === LocationType) {
return this._serializeLocation(obj);
}
throw new Error('No serializer for ' + type.toString());
} }
deserialize(map: any, type: any, data?: any): any { deserialize(map: any, type: any, data?: any): any {

View File

@ -9,7 +9,7 @@
import {Injectable, Type} from '@angular/core'; import {Injectable, Type} from '@angular/core';
import {EventEmitter} from '../../facade/async'; import {EventEmitter} from '../../facade/async';
import {FunctionWrapper, isPresent} from '../../facade/lang'; import {isPresent} from '../../facade/lang';
import {MessageBus} from '../shared/message_bus'; import {MessageBus} from '../shared/message_bus';
import {Serializer} from '../shared/serializer'; import {Serializer} from '../shared/serializer';
@ -69,16 +69,16 @@ export class ServiceMessageBroker_ extends ServiceMessageBroker {
methodName: string, signature: Type<any>[], method: (..._: any[]) => Promise<any>| void, methodName: string, signature: Type<any>[], method: (..._: any[]) => Promise<any>| void,
returnType?: Type<any>): void { returnType?: Type<any>): void {
this._methods.set(methodName, (message: ReceivedMessage) => { this._methods.set(methodName, (message: ReceivedMessage) => {
var serializedArgs = message.args; const serializedArgs = message.args;
let numArgs = signature === null ? 0 : signature.length; let numArgs = signature === null ? 0 : signature.length;
var deserializedArgs: any[] = new Array(numArgs); const deserializedArgs: any[] = new Array(numArgs);
for (var i = 0; i < numArgs; i++) { for (let i = 0; i < numArgs; i++) {
var serializedArg = serializedArgs[i]; const serializedArg = serializedArgs[i];
deserializedArgs[i] = this._serializer.deserialize(serializedArg, signature[i]); deserializedArgs[i] = this._serializer.deserialize(serializedArg, signature[i]);
} }
var promise = FunctionWrapper.apply(method, deserializedArgs); const promise = method(...deserializedArgs);
if (isPresent(returnType) && isPresent(promise)) { if (isPresent(returnType) && promise) {
this._wrapWebWorkerPromise(message.id, promise, returnType); this._wrapWebWorkerPromise(message.id, promise, returnType);
} }
}); });

View File

@ -10,7 +10,6 @@ import {LocationChangeListener} from '@angular/common';
import {Injectable} from '@angular/core'; import {Injectable} from '@angular/core';
import {EventEmitter} from '../../facade/async'; import {EventEmitter} from '../../facade/async';
import {FunctionWrapper} from '../../facade/lang';
import {BrowserPlatformLocation} from '../../private_import_platform-browser'; import {BrowserPlatformLocation} from '../../private_import_platform-browser';
import {MessageBus} from '../shared/message_bus'; import {MessageBus} from '../shared/message_bus';
import {ROUTER_CHANNEL} from '../shared/messaging_api'; import {ROUTER_CHANNEL} from '../shared/messaging_api';
@ -27,30 +26,26 @@ export class MessageBasedPlatformLocation {
private _brokerFactory: ServiceMessageBrokerFactory, private _brokerFactory: ServiceMessageBrokerFactory,
private _platformLocation: BrowserPlatformLocation, bus: MessageBus, private _platformLocation: BrowserPlatformLocation, bus: MessageBus,
private _serializer: Serializer) { private _serializer: Serializer) {
this._platformLocation.onPopState( this._platformLocation.onPopState(<LocationChangeListener>this._sendUrlChangeEvent.bind(this));
<LocationChangeListener>FunctionWrapper.bind(this._sendUrlChangeEvent, this));
this._platformLocation.onHashChange( this._platformLocation.onHashChange(
<LocationChangeListener>FunctionWrapper.bind(this._sendUrlChangeEvent, this)); <LocationChangeListener>this._sendUrlChangeEvent.bind(this));
this._broker = this._brokerFactory.createMessageBroker(ROUTER_CHANNEL); this._broker = this._brokerFactory.createMessageBroker(ROUTER_CHANNEL);
this._channelSink = bus.to(ROUTER_CHANNEL); this._channelSink = bus.to(ROUTER_CHANNEL);
} }
start(): void { start(): void {
this._broker.registerMethod( this._broker.registerMethod('getLocation', null, this._getLocation.bind(this), LocationType);
'getLocation', null, FunctionWrapper.bind(this._getLocation, this), LocationType); this._broker.registerMethod('setPathname', [PRIMITIVE], this._setPathname.bind(this));
this._broker.registerMethod(
'setPathname', [PRIMITIVE], FunctionWrapper.bind(this._setPathname, this));
this._broker.registerMethod( this._broker.registerMethod(
'pushState', [PRIMITIVE, PRIMITIVE, PRIMITIVE], 'pushState', [PRIMITIVE, PRIMITIVE, PRIMITIVE],
FunctionWrapper.bind(this._platformLocation.pushState, this._platformLocation)); this._platformLocation.pushState.bind(this._platformLocation));
this._broker.registerMethod( this._broker.registerMethod(
'replaceState', [PRIMITIVE, PRIMITIVE, PRIMITIVE], 'replaceState', [PRIMITIVE, PRIMITIVE, PRIMITIVE],
FunctionWrapper.bind(this._platformLocation.replaceState, this._platformLocation)); this._platformLocation.replaceState.bind(this._platformLocation));
this._broker.registerMethod( this._broker.registerMethod(
'forward', null, 'forward', null, this._platformLocation.forward.bind(this._platformLocation));
FunctionWrapper.bind(this._platformLocation.forward, this._platformLocation));
this._broker.registerMethod( this._broker.registerMethod(
'back', null, FunctionWrapper.bind(this._platformLocation.back, this._platformLocation)); 'back', null, this._platformLocation.back.bind(this._platformLocation));
} }
private _getLocation(): Promise<Location> { private _getLocation(): Promise<Location> {

View File

@ -8,7 +8,6 @@
import {Injectable, RenderComponentType, Renderer, RootRenderer} from '@angular/core'; import {Injectable, RenderComponentType, Renderer, RootRenderer} from '@angular/core';
import {FunctionWrapper} from '../../facade/lang';
import {MessageBus} from '../shared/message_bus'; import {MessageBus} from '../shared/message_bus';
import {EVENT_CHANNEL, RENDERER_CHANNEL} from '../shared/messaging_api'; import {EVENT_CHANNEL, RENDERER_CHANNEL} from '../shared/messaging_api';
import {RenderStore} from '../shared/render_store'; import {RenderStore} from '../shared/render_store';
@ -31,70 +30,66 @@ export class MessageBasedRenderer {
this._eventDispatcher = new EventDispatcher(this._bus.to(EVENT_CHANNEL), this._serializer); this._eventDispatcher = new EventDispatcher(this._bus.to(EVENT_CHANNEL), this._serializer);
broker.registerMethod( broker.registerMethod(
'renderComponent', [RenderComponentType, PRIMITIVE], 'renderComponent', [RenderComponentType, PRIMITIVE], this._renderComponent.bind(this));
FunctionWrapper.bind(this._renderComponent, this));
broker.registerMethod( broker.registerMethod(
'selectRootElement', [RenderStoreObject, PRIMITIVE, PRIMITIVE], 'selectRootElement', [RenderStoreObject, PRIMITIVE, PRIMITIVE],
FunctionWrapper.bind(this._selectRootElement, this)); this._selectRootElement.bind(this));
broker.registerMethod( broker.registerMethod(
'createElement', [RenderStoreObject, RenderStoreObject, PRIMITIVE, PRIMITIVE], 'createElement', [RenderStoreObject, RenderStoreObject, PRIMITIVE, PRIMITIVE],
FunctionWrapper.bind(this._createElement, this)); this._createElement.bind(this));
broker.registerMethod( broker.registerMethod(
'createViewRoot', [RenderStoreObject, RenderStoreObject, PRIMITIVE], 'createViewRoot', [RenderStoreObject, RenderStoreObject, PRIMITIVE],
FunctionWrapper.bind(this._createViewRoot, this)); this._createViewRoot.bind(this));
broker.registerMethod( broker.registerMethod(
'createTemplateAnchor', [RenderStoreObject, RenderStoreObject, PRIMITIVE], 'createTemplateAnchor', [RenderStoreObject, RenderStoreObject, PRIMITIVE],
FunctionWrapper.bind(this._createTemplateAnchor, this)); this._createTemplateAnchor.bind(this));
broker.registerMethod( broker.registerMethod(
'createText', [RenderStoreObject, RenderStoreObject, PRIMITIVE, PRIMITIVE], 'createText', [RenderStoreObject, RenderStoreObject, PRIMITIVE, PRIMITIVE],
FunctionWrapper.bind(this._createText, this)); this._createText.bind(this));
broker.registerMethod( broker.registerMethod(
'projectNodes', [RenderStoreObject, RenderStoreObject, RenderStoreObject], 'projectNodes', [RenderStoreObject, RenderStoreObject, RenderStoreObject],
FunctionWrapper.bind(this._projectNodes, this)); this._projectNodes.bind(this));
broker.registerMethod( broker.registerMethod(
'attachViewAfter', [RenderStoreObject, RenderStoreObject, RenderStoreObject], 'attachViewAfter', [RenderStoreObject, RenderStoreObject, RenderStoreObject],
FunctionWrapper.bind(this._attachViewAfter, this)); this._attachViewAfter.bind(this));
broker.registerMethod( broker.registerMethod(
'detachView', [RenderStoreObject, RenderStoreObject], 'detachView', [RenderStoreObject, RenderStoreObject], this._detachView.bind(this));
FunctionWrapper.bind(this._detachView, this));
broker.registerMethod( broker.registerMethod(
'destroyView', [RenderStoreObject, RenderStoreObject, RenderStoreObject], 'destroyView', [RenderStoreObject, RenderStoreObject, RenderStoreObject],
FunctionWrapper.bind(this._destroyView, this)); this._destroyView.bind(this));
broker.registerMethod( broker.registerMethod(
'setElementProperty', [RenderStoreObject, RenderStoreObject, PRIMITIVE, PRIMITIVE], 'setElementProperty', [RenderStoreObject, RenderStoreObject, PRIMITIVE, PRIMITIVE],
FunctionWrapper.bind(this._setElementProperty, this)); this._setElementProperty.bind(this));
broker.registerMethod( broker.registerMethod(
'setElementAttribute', [RenderStoreObject, RenderStoreObject, PRIMITIVE, PRIMITIVE], 'setElementAttribute', [RenderStoreObject, RenderStoreObject, PRIMITIVE, PRIMITIVE],
FunctionWrapper.bind(this._setElementAttribute, this)); this._setElementAttribute.bind(this));
broker.registerMethod( broker.registerMethod(
'setBindingDebugInfo', [RenderStoreObject, RenderStoreObject, PRIMITIVE, PRIMITIVE], 'setBindingDebugInfo', [RenderStoreObject, RenderStoreObject, PRIMITIVE, PRIMITIVE],
FunctionWrapper.bind(this._setBindingDebugInfo, this)); this._setBindingDebugInfo.bind(this));
broker.registerMethod( broker.registerMethod(
'setElementClass', [RenderStoreObject, RenderStoreObject, PRIMITIVE, PRIMITIVE], 'setElementClass', [RenderStoreObject, RenderStoreObject, PRIMITIVE, PRIMITIVE],
FunctionWrapper.bind(this._setElementClass, this)); this._setElementClass.bind(this));
broker.registerMethod( broker.registerMethod(
'setElementStyle', [RenderStoreObject, RenderStoreObject, PRIMITIVE, PRIMITIVE], 'setElementStyle', [RenderStoreObject, RenderStoreObject, PRIMITIVE, PRIMITIVE],
FunctionWrapper.bind(this._setElementStyle, this)); this._setElementStyle.bind(this));
broker.registerMethod( broker.registerMethod(
'invokeElementMethod', [RenderStoreObject, RenderStoreObject, PRIMITIVE, PRIMITIVE], 'invokeElementMethod', [RenderStoreObject, RenderStoreObject, PRIMITIVE, PRIMITIVE],
FunctionWrapper.bind(this._invokeElementMethod, this)); this._invokeElementMethod.bind(this));
broker.registerMethod( broker.registerMethod(
'setText', [RenderStoreObject, RenderStoreObject, PRIMITIVE], 'setText', [RenderStoreObject, RenderStoreObject, PRIMITIVE], this._setText.bind(this));
FunctionWrapper.bind(this._setText, this));
broker.registerMethod( broker.registerMethod(
'listen', [RenderStoreObject, RenderStoreObject, PRIMITIVE, PRIMITIVE], 'listen', [RenderStoreObject, RenderStoreObject, PRIMITIVE, PRIMITIVE],
FunctionWrapper.bind(this._listen, this)); this._listen.bind(this));
broker.registerMethod( broker.registerMethod(
'listenGlobal', [RenderStoreObject, PRIMITIVE, PRIMITIVE, PRIMITIVE], 'listenGlobal', [RenderStoreObject, PRIMITIVE, PRIMITIVE, PRIMITIVE],
FunctionWrapper.bind(this._listenGlobal, this)); this._listenGlobal.bind(this));
broker.registerMethod( broker.registerMethod(
'listenDone', [RenderStoreObject, RenderStoreObject], 'listenDone', [RenderStoreObject, RenderStoreObject], this._listenDone.bind(this));
FunctionWrapper.bind(this._listenDone, this));
} }
private _renderComponent(renderComponentType: RenderComponentType, rendererId: number) { private _renderComponent(renderComponentType: RenderComponentType, rendererId: number) {
var renderer = this._rootRenderer.renderComponent(renderComponentType); const renderer = this._rootRenderer.renderComponent(renderComponentType);
this._renderStore.store(renderer, rendererId); this._renderStore.store(renderer, rendererId);
} }
@ -107,7 +102,7 @@ export class MessageBasedRenderer {
} }
private _createViewRoot(renderer: Renderer, hostElement: any, elId: number) { private _createViewRoot(renderer: Renderer, hostElement: any, elId: number) {
var viewRoot = renderer.createViewRoot(hostElement); const viewRoot = renderer.createViewRoot(hostElement);
if (this._renderStore.serialize(hostElement) !== elId) { if (this._renderStore.serialize(hostElement) !== elId) {
this._renderStore.store(viewRoot, elId); this._renderStore.store(viewRoot, elId);
} }
@ -135,7 +130,7 @@ export class MessageBasedRenderer {
private _destroyView(renderer: Renderer, hostElement: any, viewAllNodes: any[]) { private _destroyView(renderer: Renderer, hostElement: any, viewAllNodes: any[]) {
renderer.destroyView(hostElement, viewAllNodes); renderer.destroyView(hostElement, viewAllNodes);
for (var i = 0; i < viewAllNodes.length; i++) { for (let i = 0; i < viewAllNodes.length; i++) {
this._renderStore.remove(viewAllNodes[i]); this._renderStore.remove(viewAllNodes[i]);
} }
} }

View File

@ -92,7 +92,7 @@ function routerFactory($q, $location, $browser, $rootScope, $injector, $routerRo
// Override this method to actually get hold of the child routes // Override this method to actually get hold of the child routes
RouteRegistry.prototype.configFromComponent = function (component) { RouteRegistry.prototype.configFromComponent = function (component) {
var that = this; var that = this;
if (isString(component)) { if (typeof component === 'string') {
// Don't read the annotations component a type more than once // Don't read the annotations component a type more than once
// this prevents an infinite loop if a component routes recursively. // this prevents an infinite loop if a component routes recursively.
if (this._rules.has(component)) { if (this._rules.has(component)) {