refactor: misc cleanup

This commit is contained in:
Victor Berchet 2016-09-20 14:14:57 -07:00 committed by Rado Kirov
parent 0ca971c5bd
commit f23b22a0f4
10 changed files with 55 additions and 88 deletions

View File

@ -115,27 +115,27 @@ export class DirectiveNormalizer {
const templateStyles = this.normalizeStylesheet(new CompileStylesheetMetadata( const templateStyles = this.normalizeStylesheet(new CompileStylesheetMetadata(
{styles: visitor.styles, styleUrls: visitor.styleUrls, moduleUrl: templateAbsUrl})); {styles: visitor.styles, styleUrls: visitor.styleUrls, moduleUrl: templateAbsUrl}));
const allStyles = templateMetadataStyles.styles.concat(templateStyles.styles);
const allStyleUrls = templateMetadataStyles.styleUrls.concat(templateStyles.styleUrls);
let encapsulation = templateMeta.encapsulation; let encapsulation = templateMeta.encapsulation;
if (isBlank(encapsulation)) { if (isBlank(encapsulation)) {
encapsulation = this._config.defaultEncapsulation; encapsulation = this._config.defaultEncapsulation;
} }
if (encapsulation === ViewEncapsulation.Emulated && allStyles.length === 0 &&
allStyleUrls.length === 0) { const styles = templateMetadataStyles.styles.concat(templateStyles.styles);
const styleUrls = templateMetadataStyles.styleUrls.concat(templateStyles.styleUrls);
if (encapsulation === ViewEncapsulation.Emulated && styles.length === 0 &&
styleUrls.length === 0) {
encapsulation = ViewEncapsulation.None; encapsulation = ViewEncapsulation.None;
} }
return new CompileTemplateMetadata({ return new CompileTemplateMetadata({
encapsulation, encapsulation,
template: template, template,
templateUrl: templateAbsUrl, templateUrl: templateAbsUrl, styles, styleUrls,
styles: allStyles,
styleUrls: allStyleUrls,
externalStylesheets: templateMeta.externalStylesheets, externalStylesheets: templateMeta.externalStylesheets,
ngContentSelectors: visitor.ngContentSelectors, ngContentSelectors: visitor.ngContentSelectors,
animations: templateMeta.animations, animations: templateMeta.animations,
interpolation: templateMeta.interpolation interpolation: templateMeta.interpolation,
}); });
} }
@ -251,7 +251,6 @@ function _cloneDirectiveWithTemplate(
viewProviders: directive.viewProviders, viewProviders: directive.viewProviders,
queries: directive.queries, queries: directive.queries,
viewQueries: directive.viewQueries, viewQueries: directive.viewQueries,
entryComponents: directive.entryComponents, entryComponents: directive.entryComponents, template,
template: template
}); });
} }

View File

@ -14,7 +14,6 @@ import {LOCALE_ID} from './i18n/tokens';
import {Compiler} from './linker/compiler'; import {Compiler} from './linker/compiler';
import {ViewUtils} from './linker/view_utils'; import {ViewUtils} from './linker/view_utils';
import {NgModule} from './metadata'; import {NgModule} from './metadata';
import {Type} from './type';
export function _iterableDiffersFactory() { export function _iterableDiffersFactory() {
return defaultIterableDiffers; return defaultIterableDiffers;

View File

@ -9,7 +9,7 @@
import {ErrorHandler} from '../src/error_handler'; import {ErrorHandler} from '../src/error_handler';
import {ListWrapper} from '../src/facade/collection'; import {ListWrapper} from '../src/facade/collection';
import {unimplemented} from '../src/facade/errors'; import {unimplemented} from '../src/facade/errors';
import {isBlank, isPresent, stringify} from '../src/facade/lang'; import {stringify} from '../src/facade/lang';
import {isPromise} from '../src/util/lang'; import {isPromise} from '../src/util/lang';
import {ApplicationInitStatus} from './application_init'; import {ApplicationInitStatus} from './application_init';
@ -26,9 +26,9 @@ import {Testability, TestabilityRegistry} from './testability/testability';
import {Type} from './type'; import {Type} from './type';
import {NgZone} from './zone/ng_zone'; import {NgZone} from './zone/ng_zone';
var _devMode: boolean = true; let _devMode: boolean = true;
var _runModeLocked: boolean = false; let _runModeLocked: boolean = false;
var _platform: PlatformRef; let _platform: PlatformRef;
/** /**
* Disable Angular's development mode, which turns off assertions and other * Disable Angular's development mode, which turns off assertions and other
@ -67,13 +67,13 @@ export function isDevMode(): boolean {
* @experimental APIs related to application bootstrap are currently under review. * @experimental APIs related to application bootstrap are currently under review.
*/ */
export function createPlatform(injector: Injector): PlatformRef { export function createPlatform(injector: Injector): PlatformRef {
if (isPresent(_platform) && !_platform.destroyed) { if (_platform && !_platform.destroyed) {
throw new Error( throw new Error(
'There can be only one platform. Destroy the previous one to create a new one.'); 'There can be only one platform. Destroy the previous one to create a new one.');
} }
_platform = injector.get(PlatformRef); _platform = injector.get(PlatformRef);
const inits: Function[] = <Function[]>injector.get(PLATFORM_INITIALIZER, null); const inits: Function[] = <Function[]>injector.get(PLATFORM_INITIALIZER, null);
if (isPresent(inits)) inits.forEach(init => init()); if (inits) inits.forEach(init => init());
return _platform; return _platform;
} }
@ -107,14 +107,17 @@ export function createPlatformFactory(
* @experimental APIs related to application bootstrap are currently under review. * @experimental APIs related to application bootstrap are currently under review.
*/ */
export function assertPlatform(requiredToken: any): PlatformRef { export function assertPlatform(requiredToken: any): PlatformRef {
var platform = getPlatform(); const platform = getPlatform();
if (isBlank(platform)) {
if (!platform) {
throw new Error('No platform exists!'); throw new Error('No platform exists!');
} }
if (isPresent(platform) && isBlank(platform.injector.get(requiredToken, null))) {
if (!platform.injector.get(requiredToken, null)) {
throw new Error( throw new Error(
'A platform with a different configuration has been created. Please destroy it first.'); 'A platform with a different configuration has been created. Please destroy it first.');
} }
return platform; return platform;
} }
@ -124,7 +127,7 @@ export function assertPlatform(requiredToken: any): PlatformRef {
* @experimental APIs related to application bootstrap are currently under review. * @experimental APIs related to application bootstrap are currently under review.
*/ */
export function destroyPlatform(): void { export function destroyPlatform(): void {
if (isPresent(_platform) && !_platform.destroyed) { if (_platform && !_platform.destroyed) {
_platform.destroy(); _platform.destroy();
} }
} }
@ -135,7 +138,7 @@ export function destroyPlatform(): void {
* @experimental APIs related to application bootstrap are currently under review. * @experimental APIs related to application bootstrap are currently under review.
*/ */
export function getPlatform(): PlatformRef { export function getPlatform(): PlatformRef {
return isPresent(_platform) && !_platform.destroyed ? _platform : null; return _platform && !_platform.destroyed ? _platform : null;
} }
/** /**
@ -224,9 +227,9 @@ function _callAndReportToErrorHandler(errorHandler: ErrorHandler, callback: () =
// rethrow as the exception handler might not do it // rethrow as the exception handler might not do it
throw e; throw e;
}); });
} else {
return result;
} }
return result;
} catch (e) { } catch (e) {
errorHandler.handleError(e); errorHandler.handleError(e);
// rethrow as the exception handler might not do it // rethrow as the exception handler might not do it
@ -238,7 +241,6 @@ function _callAndReportToErrorHandler(errorHandler: ErrorHandler, callback: () =
export class PlatformRef_ extends PlatformRef { export class PlatformRef_ extends PlatformRef {
private _modules: NgModuleRef<any>[] = []; private _modules: NgModuleRef<any>[] = [];
private _destroyListeners: Function[] = []; private _destroyListeners: Function[] = [];
private _destroyed: boolean = false; private _destroyed: boolean = false;
constructor(private _injector: Injector) { super(); } constructor(private _injector: Injector) { super(); }
@ -253,8 +255,8 @@ export class PlatformRef_ extends PlatformRef {
if (this._destroyed) { if (this._destroyed) {
throw new Error('The platform has already been destroyed!'); throw new Error('The platform has already been destroyed!');
} }
ListWrapper.clone(this._modules).forEach((app) => app.destroy()); this._modules.slice().forEach(module => module.destroy());
this._destroyListeners.forEach((dispose) => dispose()); this._destroyListeners.forEach(listener => listener());
this._destroyed = true; this._destroyed = true;
} }
@ -301,7 +303,7 @@ export class PlatformRef_ extends PlatformRef {
componentFactoryCallback?: any): Promise<NgModuleRef<M>> { componentFactoryCallback?: any): Promise<NgModuleRef<M>> {
const compilerFactory: CompilerFactory = this.injector.get(CompilerFactory); const compilerFactory: CompilerFactory = this.injector.get(CompilerFactory);
const compiler = compilerFactory.createCompiler( const compiler = compilerFactory.createCompiler(
compilerOptions instanceof Array ? compilerOptions : [compilerOptions]); Array.isArray(compilerOptions) ? compilerOptions : [compilerOptions]);
// ugly internal api hack: generate host component factories for all declared components and // ugly internal api hack: generate host component factories for all declared components and
// pass the factories into the callback - this is used by UpdateAdapter to get hold of all // pass the factories into the callback - this is used by UpdateAdapter to get hold of all
@ -424,10 +426,10 @@ export class ApplicationRef_ extends ApplicationRef {
componentFactory = this._componentFactoryResolver.resolveComponentFactory(componentOrFactory); componentFactory = this._componentFactoryResolver.resolveComponentFactory(componentOrFactory);
} }
this._rootComponentTypes.push(componentFactory.componentType); this._rootComponentTypes.push(componentFactory.componentType);
var compRef = componentFactory.create(this._injector, [], componentFactory.selector); const compRef = componentFactory.create(this._injector, [], componentFactory.selector);
compRef.onDestroy(() => { this._unloadComponent(compRef); }); compRef.onDestroy(() => { this._unloadComponent(compRef); });
var testability = compRef.injector.get(Testability, null); const testability = compRef.injector.get(Testability, null);
if (isPresent(testability)) { if (testability) {
compRef.injector.get(TestabilityRegistry) compRef.injector.get(TestabilityRegistry)
.registerApplication(compRef.location.nativeElement, testability); .registerApplication(compRef.location.nativeElement, testability);
} }
@ -454,7 +456,7 @@ export class ApplicationRef_ extends ApplicationRef {
/** @internal */ /** @internal */
_unloadComponent(componentRef: ComponentRef<any>): void { _unloadComponent(componentRef: ComponentRef<any>): void {
if (!ListWrapper.contains(this._rootComponents, componentRef)) { if (this._rootComponents.indexOf(componentRef) == -1) {
return; return;
} }
this.unregisterChangeDetector(componentRef.changeDetectorRef); this.unregisterChangeDetector(componentRef.changeDetectorRef);
@ -466,7 +468,7 @@ export class ApplicationRef_ extends ApplicationRef {
throw new Error('ApplicationRef.tick is called recursively'); throw new Error('ApplicationRef.tick is called recursively');
} }
var s = ApplicationRef_._tickScope(); const scope = ApplicationRef_._tickScope();
try { try {
this._runningTick = true; this._runningTick = true;
this._changeDetectorRefs.forEach((detector) => detector.detectChanges()); this._changeDetectorRefs.forEach((detector) => detector.detectChanges());
@ -475,13 +477,13 @@ export class ApplicationRef_ extends ApplicationRef {
} }
} finally { } finally {
this._runningTick = false; this._runningTick = false;
wtfLeave(s); wtfLeave(scope);
} }
} }
ngOnDestroy() { ngOnDestroy() {
// TODO(alxhub): Dispose of the NgZone. // TODO(alxhub): Dispose of the NgZone.
ListWrapper.clone(this._rootComponents).forEach((ref) => ref.destroy()); this._rootComponents.slice().forEach((component) => component.destroy());
} }
get componentTypes(): Type<any>[] { return this._rootComponentTypes; } get componentTypes(): Type<any>[] { return this._rootComponentTypes; }

View File

@ -34,7 +34,7 @@ export function _appIdRandomProviderFactory() {
export const APP_ID_RANDOM_PROVIDER = { export const APP_ID_RANDOM_PROVIDER = {
provide: APP_ID, provide: APP_ID,
useFactory: _appIdRandomProviderFactory, useFactory: _appIdRandomProviderFactory,
deps: <any[]>[] deps: <any[]>[],
}; };
function _randomChar(): string { function _randomChar(): string {

View File

@ -10,7 +10,6 @@ import {APP_ID} from '../application_tokens';
import {devModeEqual} from '../change_detection/change_detection'; import {devModeEqual} from '../change_detection/change_detection';
import {UNINITIALIZED} from '../change_detection/change_detection_util'; import {UNINITIALIZED} from '../change_detection/change_detection_util';
import {Inject, Injectable} from '../di'; import {Inject, Injectable} from '../di';
import {ListWrapper} from '../facade/collection';
import {isBlank, isPresent, looseIdentical} from '../facade/lang'; import {isBlank, isPresent, looseIdentical} from '../facade/lang';
import {ViewEncapsulation} from '../metadata/view'; import {ViewEncapsulation} from '../metadata/view';
import {RenderComponentType, Renderer, RootRenderer} from '../render/api'; import {RenderComponentType, Renderer, RootRenderer} from '../render/api';

View File

@ -15,8 +15,6 @@ import {Attribute, ContentChild, ContentChildren, Query, ViewChild, ViewChildren
import {Component, Directive, HostBinding, HostListener, Input, Output, Pipe} from './metadata/directives'; import {Component, Directive, HostBinding, HostListener, Input, Output, Pipe} from './metadata/directives';
import {ModuleWithProviders, NgModule, SchemaMetadata} from './metadata/ng_module'; import {ModuleWithProviders, NgModule, SchemaMetadata} from './metadata/ng_module';
import {ViewEncapsulation} from './metadata/view'; import {ViewEncapsulation} from './metadata/view';
import {Type} from './type';
import {TypeDecorator, makeParamDecorator, makePropDecorator} from './util/decorators';
export {ANALYZE_FOR_ENTRY_COMPONENTS, Attribute, ContentChild, ContentChildDecorator, ContentChildren, ContentChildrenDecorator, Query, ViewChild, ViewChildDecorator, ViewChildren, ViewChildrenDecorator} from './metadata/di'; export {ANALYZE_FOR_ENTRY_COMPONENTS, Attribute, ContentChild, ContentChildDecorator, ContentChildren, ContentChildrenDecorator, Query, ViewChild, ViewChildDecorator, ViewChildren, ViewChildrenDecorator} from './metadata/di';
export {Component, ComponentDecorator, Directive, DirectiveDecorator, HostBinding, HostListener, Input, Output, Pipe} from './metadata/directives'; export {Component, ComponentDecorator, Directive, DirectiveDecorator, HostBinding, HostListener, Input, Output, Pipe} from './metadata/directives';

View File

@ -7,8 +7,6 @@
*/ */
import {AnimationEntryMetadata} from '../animation/metadata'; import {AnimationEntryMetadata} from '../animation/metadata';
import {Type} from '../type';
/** /**
* Defines template and style encapsulation options available for Component's {@link Component}. * Defines template and style encapsulation options available for Component's {@link Component}.
@ -46,13 +44,6 @@ export var VIEW_ENCAPSULATION_VALUES =
/** /**
* Metadata properties available for configuring Views. * Metadata properties available for configuring Views.
* *
* Each Angular component requires a single `@Component` and at least one `@View` annotation. The
* `@View` annotation specifies the HTML template to use, and lists the directives that are active
* within the template.
*
* When a component is instantiated, the template is loaded into the component's shadow root, and
* the expressions and statements in the template are evaluated against the component.
*
* For details on the `@Component` annotation, see {@link Component}. * For details on the `@Component` annotation, see {@link Component}.
* *
* ### Example * ### Example
@ -61,7 +52,6 @@ export var VIEW_ENCAPSULATION_VALUES =
* @Component({ * @Component({
* selector: 'greet', * selector: 'greet',
* template: 'Hello {{name}}!', * template: 'Hello {{name}}!',
* directives: [GreetUser, Bold]
* }) * })
* class Greet { * class Greet {
* name: string; * name: string;
@ -73,46 +63,23 @@ export var VIEW_ENCAPSULATION_VALUES =
* ``` * ```
* *
* @deprecated Use Component instead. * @deprecated Use Component instead.
*
* {@link Component}
*/ */
export class ViewMetadata { export class ViewMetadata {
/** /** {@link Component.templateUrl} */
* Specifies a template URL for an Angular component.
*
* NOTE: Only one of `templateUrl` or `template` can be defined per View.
*
* <!-- TODO: what's the url relative to? -->
*/
templateUrl: string; templateUrl: string;
/** {@link Component.template} */
/**
* Specifies an inline template for an Angular component.
*
* NOTE: Only one of `templateUrl` or `template` can be defined per View.
*/
template: string; template: string;
/** {@link Component.stylesUrl} */
/**
* Specifies stylesheet URLs for an Angular component.
*
* <!-- TODO: what's the url relative to? -->
*/
styleUrls: string[]; styleUrls: string[];
/** {@link Component.styles} */
/**
* Specifies an inline stylesheet for an Angular component.
*/
styles: string[]; styles: string[];
/** {@link Component.encapsulation} */
/**
* Specify how the template and the styles should be encapsulated.
* The default is {@link ViewEncapsulation#Emulated `ViewEncapsulation.Emulated`} if the view
* has styles,
* otherwise {@link ViewEncapsulation#None `ViewEncapsulation.None`}.
*/
encapsulation: ViewEncapsulation; encapsulation: ViewEncapsulation;
/** {@link Component.animation} */
animations: AnimationEntryMetadata[]; animations: AnimationEntryMetadata[];
/** {@link Component.interpolation} */
interpolation: [string, string]; interpolation: [string, string];
constructor( constructor(

View File

@ -8,7 +8,7 @@
import {PlatformRef, PlatformRef_, createPlatformFactory} from './application_ref'; import {PlatformRef, PlatformRef_, createPlatformFactory} from './application_ref';
import {Console} from './console'; import {Console} from './console';
import {ClassProvider, ExistingProvider, FactoryProvider, Provider, TypeProvider, ValueProvider} from './di'; import {Provider} from './di';
import {Reflector, reflector} from './reflection/reflection'; import {Reflector, reflector} from './reflection/reflection';
import {ReflectorReader} from './reflection/reflector_reader'; import {ReflectorReader} from './reflection/reflector_reader';
import {TestabilityRegistry} from './testability/testability'; import {TestabilityRegistry} from './testability/testability';
@ -18,9 +18,12 @@ function _reflector(): Reflector {
} }
const _CORE_PLATFORM_PROVIDERS: Provider[] = [ const _CORE_PLATFORM_PROVIDERS: Provider[] = [
PlatformRef_, {provide: PlatformRef, useExisting: PlatformRef_}, PlatformRef_,
{provide: PlatformRef, useExisting: PlatformRef_},
{provide: Reflector, useFactory: _reflector, deps: []}, {provide: Reflector, useFactory: _reflector, deps: []},
{provide: ReflectorReader, useExisting: Reflector}, TestabilityRegistry, Console {provide: ReflectorReader, useExisting: Reflector},
TestabilityRegistry,
Console,
]; ];
/** /**

View File

@ -16,7 +16,7 @@
* *
* @stable * @stable
*/ */
export var Type = Function; export const Type = Function;
export interface Type<T> extends Function { new (...args: any[]): T; } export interface Type<T> extends Function { new (...args: any[]): T; }

View File

@ -916,7 +916,7 @@ export declare const TRANSLATIONS_FORMAT: OpaqueToken;
export declare function trigger(name: string, animation: AnimationMetadata[]): AnimationEntryMetadata; export declare function trigger(name: string, animation: AnimationMetadata[]): AnimationEntryMetadata;
/** @stable */ /** @stable */
export declare var Type: FunctionConstructor; export declare const Type: FunctionConstructor;
/** @stable */ /** @stable */
export interface TypeDecorator { export interface TypeDecorator {