refactor(facade): remove useless facades

This commit is contained in:
Victor Berchet 2016-09-18 15:39:26 -07:00 committed by Rado Kirov
parent 34b31dea7c
commit 58605cf350
24 changed files with 91 additions and 159 deletions

View File

@ -6,10 +6,10 @@
* found in the LICENSE file at https://angular.io/license
*/
import {Inject, Injectable, OpaqueToken} from '@angular/core';
import {Inject, Injectable} from '@angular/core';
import {Options} from './common_options';
import {Date, DateWrapper, isBlank, isPresent} from './facade/lang';
import {isPresent} from './facade/lang';
import {MeasureValues} from './measure_values';
import {Metric} from './metric';
import {Reporter} from './reporter';

View File

@ -9,8 +9,8 @@
import {Provider} from '@angular/core';
import {AsyncTestCompleter, afterEach, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {ConsoleReporter, MeasureValues, ReflectiveInjector, Reporter, SampleDescription, SampleState} from '../../index';
import {Date, DateWrapper, isBlank, isPresent} from '../../src/facade/lang';
import {ConsoleReporter, MeasureValues, ReflectiveInjector, SampleDescription} from '../../index';
import {DateWrapper, isBlank, isPresent} from '../../src/facade/lang';
export function main() {
describe('console reporter', () => {

View File

@ -9,7 +9,7 @@
import {AsyncTestCompleter, afterEach, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {MeasureValues, Metric, Options, ReflectiveInjector, Reporter, Sampler, Validator, WebDriverAdapter} from '../index';
import {Date, DateWrapper, isBlank, isPresent, stringify} from '../src/facade/lang';
import {DateWrapper, isBlank, isPresent} from '../src/facade/lang';
export function main() {
var EMPTY_EXECUTE = () => {};

View File

@ -10,7 +10,7 @@ import {AsyncTestCompleter, afterEach, beforeEach, ddescribe, describe, expect,
import {MeasureValues, ReflectiveInjector, RegressionSlopeValidator} from '../../index';
import {ListWrapper} from '../../src/facade/collection';
import {Date, DateWrapper} from '../../src/facade/lang';
import {DateWrapper} from '../../src/facade/lang';
export function main() {
describe('regression slope validator', () => {

View File

@ -8,9 +8,9 @@
import {AsyncTestCompleter, afterEach, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {MeasureValues, ReflectiveInjector, SizeValidator, Validator} from '../../index';
import {MeasureValues, ReflectiveInjector, SizeValidator} from '../../index';
import {ListWrapper} from '../../src/facade/collection';
import {Date, DateWrapper} from '../../src/facade/lang';
import {DateWrapper} from '../../src/facade/lang';
export function main() {
describe('size validator', () => {

View File

@ -9,7 +9,7 @@
import * as chars from '../chars';
import {BaseError} from '../facade/errors';
import {StringWrapper, isPresent, resolveEnumToken} from '../facade/lang';
import {StringWrapper, isPresent} from '../facade/lang';
export enum CssTokenType {
EOF,
@ -223,8 +223,8 @@ export class CssScanner {
var error: CssScannerError = null;
if (!isMatchingType || (isPresent(value) && value != next.strValue)) {
var errorMessage = resolveEnumToken(CssTokenType, next.type) + ' does not match expected ' +
resolveEnumToken(CssTokenType, type) + ' value';
var errorMessage =
CssTokenType[next.type] + ' does not match expected ' + CssTokenType[type] + ' value';
if (isPresent(value)) {
errorMessage += ' ("' + next.strValue + '" should match "' + value + '")';

View File

@ -6,11 +6,6 @@
* found in the LICENSE file at https://angular.io/license
*/
import {Injectable} from '@angular/core';
import {Math, isBlank, isPresent} from '../facade/lang';
// asset:<package-name>/<realm>/<path-to-module>
var _ASSET_URL_RE = /asset:([^\/]+)\/([^\/]+)\/(.+)/;

View File

@ -6,14 +6,15 @@
* found in the LICENSE file at https://angular.io/license
*/
import {ChangeDetectionStrategy, ViewEncapsulation} from '@angular/core';
import {CompileDirectiveMetadata, CompileIdentifierMetadata, CompileTokenMetadata, CompileTypeMetadata} from '../compile_metadata';
import {ListWrapper, SetWrapper, StringMapWrapper} from '../facade/collection';
import {ViewEncapsulation} from '@angular/core';
import {CompileDirectiveMetadata, CompileIdentifierMetadata, CompileTokenMetadata} from '../compile_metadata';
import {ListWrapper, StringMapWrapper} from '../facade/collection';
import {StringWrapper, isPresent} from '../facade/lang';
import {Identifiers, identifierToken, resolveIdentifier, resolveIdentifierToken} from '../identifiers';
import {Identifiers, identifierToken, resolveIdentifier} from '../identifiers';
import * as o from '../output/output_ast';
import {ChangeDetectorStatus, ViewType, isDefaultChangeDetectionStrategy} from '../private_import_core';
import {AttrAst, BoundDirectivePropertyAst, BoundElementPropertyAst, BoundEventAst, BoundTextAst, DirectiveAst, ElementAst, EmbeddedTemplateAst, NgContentAst, ProviderAst, ReferenceAst, TemplateAst, TemplateAstVisitor, TextAst, VariableAst, templateVisitAll} from '../template_parser/template_ast';
import {AttrAst, BoundDirectivePropertyAst, BoundElementPropertyAst, BoundEventAst, BoundTextAst, DirectiveAst, ElementAst, EmbeddedTemplateAst, NgContentAst, ReferenceAst, TemplateAst, TemplateAstVisitor, TextAst, VariableAst, templateVisitAll} from '../template_parser/template_ast';
import {createDiTokenExpression} from '../util';
import {CompileElement, CompileNode} from './compile_element';
@ -596,15 +597,15 @@ function generateDetectChangesMethod(view: CompileView): o.Statement[] {
var varStmts: any[] = [];
var readVars = o.findReadVarNames(stmts);
if (SetWrapper.has(readVars, DetectChangesVars.changed.name)) {
if (readVars.has(DetectChangesVars.changed.name)) {
varStmts.push(DetectChangesVars.changed.set(o.literal(true)).toDeclStmt(o.BOOL_TYPE));
}
if (SetWrapper.has(readVars, DetectChangesVars.changes.name)) {
if (readVars.has(DetectChangesVars.changes.name)) {
varStmts.push(
DetectChangesVars.changes.set(o.NULL_EXPR)
.toDeclStmt(new o.MapType(o.importType(resolveIdentifier(Identifiers.SimpleChange)))));
}
if (SetWrapper.has(readVars, DetectChangesVars.valUnwrapper.name)) {
if (readVars.has(DetectChangesVars.valUnwrapper.name)) {
varStmts.push(
DetectChangesVars.valUnwrapper
.set(o.importExpr(resolveIdentifier(Identifiers.ValueUnwrapper)).instantiate([]))

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
import {Math, StringWrapper} from '../src/facade/lang';
import {StringWrapper} from '../src/facade/lang';
import {OpaqueToken} from './di';

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
import {MapWrapper, SetWrapper, StringMapWrapper} from '../facade/collection';
import {MapWrapper, StringMapWrapper} from '../facade/collection';
import {isPresent} from '../facade/lang';
import {Type} from '../type';
import {PlatformReflectionCapabilities} from './platform_reflection_capabilities';
@ -64,7 +64,7 @@ export class Reflector extends ReflectorReader {
throw new Error('Usage tracking is disabled');
}
var allTypes = MapWrapper.keys(this._injectableInfo);
return allTypes.filter(key => !SetWrapper.has(this._usedKeys, key));
return allTypes.filter(key => !this._usedKeys.has(key));
}
registerFunction(func: Function, funcInfo: ReflectionInfo): void {

View File

@ -8,9 +8,9 @@
import {AsyncTestCompleter} from './async_test_completer';
import {StringMapWrapper} from './facade/collection';
import {Math, global} from './facade/lang';
import {global} from './facade/lang';
import {isPromise} from './private_import_core';
import {TestBed, getTestBed, inject} from './test_bed';
import {getTestBed, inject} from './test_bed';
export {AsyncTestCompleter} from './async_test_completer';
export {MockAnimationPlayer} from './mock_animation_player';

View File

@ -9,13 +9,13 @@
/**
* JS version of browser APIs. This library can only run in the browser.
*/
var win = typeof window !== 'undefined' && window || <any>{};
const win = typeof window !== 'undefined' && window || <any>{};
export {win as window};
export var document = win.document;
export var location = win.location;
export var gc = win['gc'] ? () => win['gc']() : (): any => null;
export var performance = win['performance'] ? win['performance'] : null;
export const document = win.document;
export const location = win.location;
export const gc = win['gc'] ? () => win['gc']() : (): any => null;
export const performance = win['performance'] ? win['performance'] : null;
export const Event = win['Event'];
export const MouseEvent = win['MouseEvent'];
export const KeyboardEvent = win['KeyboardEvent'];

View File

@ -98,10 +98,15 @@ export class MapWrapper {
* Wraps Javascript Objects
*/
export class StringMapWrapper {
static get<V>(map: {[key: string]: V}, key: string): V {
return map.hasOwnProperty(key) ? map[key] : undefined;
static create(): {[k: /*any*/ string]: any} {
// Note: We are not using Object.create(null) here due to
// performance!
// http://jsperf.com/ng2-object-create-null
return {};
}
static contains(map: {[key: string]: any}, key: string): boolean {
return map.hasOwnProperty(key);
}
static set<V>(map: {[key: string]: V}, key: string, value: V) { map[key] = value; }
static keys(map: {[key: string]: any}): string[] { return Object.keys(map); }
static values<T>(map: {[key: string]: T}): T[] {
@ -312,28 +317,4 @@ export function iterateListLike(obj: any, fn: Function) {
fn(item.value);
}
}
}
// Safari and Internet Explorer do not support the iterable parameter to the
// Set constructor. We work around that by manually adding the items.
var createSetFromList: {(lst: any[]): Set<any>} = (function() {
var test = new Set([1, 2, 3]);
if (test.size === 3) {
return function createSetFromList(lst: any[]): Set<any> { return new Set(lst); };
} else {
return function createSetAndPopulateFromList(lst: any[]): Set<any> {
var res = new Set(lst);
if (res.size !== lst.length) {
for (var i = 0; i < lst.length; i++) {
res.add(lst[i]);
}
}
return res;
};
}
})();
export class SetWrapper {
static createFromList<T>(lst: T[]): Set<T> { return createSetFromList(lst); }
static has<T>(s: Set<T>, key: T): boolean { return s.has(key); }
static delete<K>(m: Set<K>, k: K) { m.delete(k); }
}
}

View File

@ -59,16 +59,9 @@ export {_global as global};
export function getTypeNameForDebugging(type: any): string {
if (type['name']) {
return type['name'];
}
return typeof type;
return type['name'] || typeof type;
}
export var Math = _global.Math;
export var Date = _global.Date;
// TODO: remove calls to assert in production environment
// Note: Can't just export this and import in in other files
// as `assert` is a reserved keyword in Dart
@ -139,24 +132,9 @@ export function stringify(token: any): string {
return token.name;
}
var res = token.toString();
var newLineIndex = res.indexOf('\n');
return (newLineIndex === -1) ? res : res.substring(0, newLineIndex);
}
// serialize / deserialize enum exist only for consistency with dart API
// enums in typescript don't need to be serialized
export function serializeEnum(val: any): number {
return val;
}
export function deserializeEnum(val: any, values: Map<number, any>): any {
return val;
}
export function resolveEnumToken(enumValue: any, val: any): string {
return enumValue[val];
const res = token.toString();
const newLineIndex = res.indexOf('\n');
return newLineIndex === -1 ? res : res.substring(0, newLineIndex);
}
export class StringWrapper {

View File

@ -6,12 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
import {NumberWrapper, StringWrapper, escapeRegExp, hasConstructor, isPresent, resolveEnumToken} from '../src/lang';
enum UsefulEnum {
MyToken,
MyOtherToken
}
import {NumberWrapper, StringWrapper, escapeRegExp, hasConstructor} from '../src/lang';
class MySuperclass {}
class MySubclass extends MySuperclass {}
@ -135,16 +130,6 @@ export function main() {
});
});
describe('resolveEnumToken', () => {
it('should resolve a token given an enum and index values', () => {
var token = UsefulEnum.MyToken;
expect(resolveEnumToken(UsefulEnum, token)).toEqual('MyToken');
token = UsefulEnum.MyOtherToken;
expect(resolveEnumToken(UsefulEnum, token)).toEqual('MyOtherToken');
});
});
describe('hasConstructor', () => {
it('should be true when the type matches',
() => { expect(hasConstructor(new MySuperclass(), MySuperclass)).toEqual(true); });

View File

@ -43,10 +43,8 @@ export class FormBuilder {
*/
group(controlsConfig: {[key: string]: any}, extra: {[key: string]: any} = null): FormGroup {
const controls = this._reduceControls(controlsConfig);
const validator: ValidatorFn =
isPresent(extra) ? StringMapWrapper.get(extra, 'validator') : null;
const asyncValidator: AsyncValidatorFn =
isPresent(extra) ? StringMapWrapper.get(extra, 'asyncValidator') : null;
const validator: ValidatorFn = isPresent(extra) ? extra['validator'] : null;
const asyncValidator: AsyncValidatorFn = isPresent(extra) ? extra['asyncValidator'] : null;
return new FormGroup(controls, validator, asyncValidator);
}
/**

View File

@ -492,7 +492,7 @@ export abstract class AbstractControl {
getError(errorCode: string, path: string[] = null): any {
var control = isPresent(path) && !ListWrapper.isEmpty(path) ? this.get(path) : this;
if (isPresent(control) && isPresent(control._errors)) {
return StringMapWrapper.get(control._errors, errorCode);
return control._errors[errorCode];
} else {
return null;
}

View File

@ -6,12 +6,9 @@
* found in the LICENSE file at https://angular.io/license
*/
import {ListWrapper, MapWrapper, StringMapWrapper, isListLikeIterable, iterateListLike} from '../src/facade/collection';
import {isBlank} from '../src/facade/lang';
/**
* Polyfill for [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers/Headers), as
* specified in the [Fetch Spec](https://fetch.spec.whatwg.org/#headers-class).

View File

@ -35,7 +35,7 @@ export function main() {
describe('initialization', () => {
it('should merge values in provided dictionary', () => {
var headers = new Headers({'foo': 'bar'});
const headers = new Headers({'foo': 'bar'});
expect(headers.get('foo')).toBe('bar');
expect(headers.getAll('foo')).toEqual(['bar']);
});
@ -52,7 +52,7 @@ export function main() {
describe('.set()', () => {
it('should clear all values and re-set for the provided key', () => {
var headers = new Headers({'foo': 'bar'});
const headers = new Headers({'foo': 'bar'});
expect(headers.get('foo')).toBe('bar');
expect(headers.getAll('foo')).toEqual(['bar']);
headers.set('foo', 'baz');

View File

@ -39,11 +39,10 @@ export class KeyEventsPlugin extends EventManagerPlugin {
var parsedEvent = KeyEventsPlugin.parseEventName(eventName);
var outsideHandler = KeyEventsPlugin.eventCallback(
element, StringMapWrapper.get(parsedEvent, 'fullKey'), handler, this.manager.getZone());
element, parsedEvent['fullKey'], handler, this.manager.getZone());
return this.manager.getZone().runOutsideAngular(() => {
return getDOM().onAndCancel(
element, StringMapWrapper.get(parsedEvent, 'domEventName'), outsideHandler);
return getDOM().onAndCancel(element, parsedEvent['domEventName'], outsideHandler);
});
}
@ -72,9 +71,10 @@ export class KeyEventsPlugin extends EventManagerPlugin {
// returning null instead of throwing to let another plugin process the event
return null;
}
var result = {};
StringMapWrapper.set(result, 'domEventName', domEventName);
StringMapWrapper.set(result, 'fullKey', fullKey);
var result: {[k: string]: string} = {};
result['domEventName'] = domEventName;
result['fullKey'] = fullKey;
return result;
}
@ -89,7 +89,7 @@ export class KeyEventsPlugin extends EventManagerPlugin {
}
modifierKeys.forEach(modifierName => {
if (modifierName != key) {
var modifierGetter = StringMapWrapper.get(modifierKeyGetters, modifierName);
var modifierGetter = modifierKeyGetters[modifierName];
if (modifierGetter(event)) {
fullKey += modifierName + '.';
}

View File

@ -224,17 +224,17 @@ export function main() {
];
browsers.forEach((browser: {[key: string]: any}) => {
it(`should detect ${StringMapWrapper.get(browser, 'name')}`, () => {
var bd = new BrowserDetection(<string>StringMapWrapper.get(browser, 'ua'));
expect(bd.isFirefox).toBe(StringMapWrapper.get(browser, 'isFirefox'));
expect(bd.isAndroid).toBe(StringMapWrapper.get(browser, 'isAndroid'));
expect(bd.isEdge).toBe(StringMapWrapper.get(browser, 'isEdge'));
expect(bd.isIE).toBe(StringMapWrapper.get(browser, 'isIE'));
expect(bd.isWebkit).toBe(StringMapWrapper.get(browser, 'isWebkit'));
expect(bd.isIOS7).toBe(StringMapWrapper.get(browser, 'isIOS7'));
expect(bd.isSlow).toBe(StringMapWrapper.get(browser, 'isSlow'));
expect(bd.isChromeDesktop).toBe(StringMapWrapper.get(browser, 'isChromeDesktop'));
expect(bd.isOldChrome).toBe(StringMapWrapper.get(browser, 'isOldChrome'));
it(`should detect ${browser[ 'name']}`, () => {
var bd = new BrowserDetection(<string>browser['ua']);
expect(bd.isFirefox).toBe(browser['isFirefox']);
expect(bd.isAndroid).toBe(browser['isAndroid']);
expect(bd.isEdge).toBe(browser['isEdge']);
expect(bd.isIE).toBe(browser['isIE']);
expect(bd.isWebkit).toBe(browser['isWebkit']);
expect(bd.isIOS7).toBe(browser['isIOS7']);
expect(bd.isSlow).toBe(browser['isSlow']);
expect(bd.isChromeDesktop).toBe(browser['isChromeDesktop']);
expect(bd.isOldChrome).toBe(browser['isOldChrome']);
});
});
});

View File

@ -146,16 +146,14 @@ export class Parse5DomAdapter extends DomAdapter {
el: any /** TODO #9100 */, evt: any /** TODO #9100 */,
listener: any /** TODO #9100 */): Function {
this.on(el, evt, listener);
return () => {
ListWrapper.remove(StringMapWrapper.get<any[]>(el._eventListenersMap, evt), listener);
};
return () => { ListWrapper.remove(<any[]>(el._eventListenersMap[evt]), listener); };
}
dispatchEvent(el: any /** TODO #9100 */, evt: any /** TODO #9100 */) {
if (isBlank(evt.target)) {
evt.target = el;
}
if (isPresent(el._eventListenersMap)) {
var listeners: any = StringMapWrapper.get(el._eventListenersMap, evt.type);
var listeners: any = el._eventListenersMap[evt.type];
if (isPresent(listeners)) {
for (var i = 0; i < listeners.length; i++) {
listeners[i](evt);
@ -499,9 +497,9 @@ export class Parse5DomAdapter extends DomAdapter {
var body = treeAdapter.createElement('body', 'http://www.w3.org/1999/xhtml', []);
this.appendChild(newDoc, head);
this.appendChild(newDoc, body);
StringMapWrapper.set(newDoc, 'head', head);
StringMapWrapper.set(newDoc, 'body', body);
StringMapWrapper.set(newDoc, '_window', {});
newDoc['head'] = head;
newDoc['body'] = body;
newDoc['_window'] = StringMapWrapper.create();
return newDoc;
}
defaultDoc(): Document {
@ -541,32 +539,31 @@ export class Parse5DomAdapter extends DomAdapter {
for (var i = 0; i < parsedRules.length; i++) {
var parsedRule = parsedRules[i];
var rule: {[key: string]: any} = {};
StringMapWrapper.set(rule, 'cssText', css);
StringMapWrapper.set(rule, 'style', {content: '', cssText: ''});
rule['cssText'] = css;
rule['style'] = {content: '', cssText: ''};
if (parsedRule.type == 'rule') {
StringMapWrapper.set(rule, 'type', 1);
StringMapWrapper.set(
rule, 'selectorText', parsedRule.selectors.join(', ')
.replace(/\s{2,}/g, ' ')
.replace(/\s*~\s*/g, ' ~ ')
.replace(/\s*\+\s*/g, ' + ')
.replace(/\s*>\s*/g, ' > ')
.replace(/\[(\w+)=(\w+)\]/g, '[$1="$2"]'));
rule['type'] = 1;
rule['selectorText'] =
parsedRule.selectors.join(', '.replace(/\s{2,}/g, ' ')
.replace(/\s*~\s*/g, ' ~ ')
.replace(/\s*\+\s*/g, ' + ')
.replace(/\s*>\s*/g, ' > ')
.replace(/\[(\w+)=(\w+)\]/g, '[$1="$2"]'));
if (isBlank(parsedRule.declarations)) {
continue;
}
for (var j = 0; j < parsedRule.declarations.length; j++) {
var declaration = parsedRule.declarations[j];
StringMapWrapper.set(
StringMapWrapper.get(rule, 'style'), declaration.property, declaration.value);
StringMapWrapper.get(rule, 'style').cssText +=
declaration.property + ': ' + declaration.value + ';';
rule['style'] = declaration.property[declaration.value];
rule['style'].cssText += declaration.property + ': ' + declaration.value + ';';
}
} else if (parsedRule.type == 'media') {
StringMapWrapper.set(rule, 'type', 4);
StringMapWrapper.set(rule, 'media', {mediaText: parsedRule.media});
rule['type'] = 4;
rule['media'] = {mediaText: parsedRule.media};
if (parsedRule.rules) {
StringMapWrapper.set(rule, 'cssRules', this._buildRules(parsedRule.rules));
rule['cssRules'] = this._buildRules(parsedRule.rules);
}
}
rules.push(rule);

View File

@ -150,7 +150,7 @@ class MessageData {
id: string;
constructor(data: {[key: string]: any}) {
this.type = StringMapWrapper.get(data, 'type');
this.type = data['type'];
this.id = this._getValueIfPresent(data, 'id');
this.value = this._getValueIfPresent(data, 'value');
}

View File

@ -8,7 +8,7 @@
import {Injectable, RenderComponentType, Type, ViewEncapsulation} from '@angular/core';
import {isArray, isPresent, serializeEnum} from '../../facade/lang';
import {isArray, isPresent} from '../../facade/lang';
import {VIEW_ENCAPSULATION_VALUES} from '../../private_import_core';
import {RenderStore} from './render_store';
@ -42,7 +42,7 @@ export class Serializer {
} else if (type === RenderComponentType) {
return this._serializeRenderComponentType(obj);
} else if (type === ViewEncapsulation) {
return serializeEnum(obj);
return obj;
} else if (type === LocationType) {
return this._serializeLocation(obj);
} else {