chore(typing): extract abstract superclasses to replace @private constructors

This commit is contained in:
Alex Eagle 2015-10-06 06:53:39 -07:00 committed by vsavkin
parent ee32b1bc37
commit 6075509f26
65 changed files with 994 additions and 797 deletions

View File

@ -1,4 +1,4 @@
import {NgZone} from 'angular2/src/core/zone/ng_zone';
import {NgZone, NgZone_} from 'angular2/src/core/zone/ng_zone';
import {Type, isBlank, isPresent, assertionsEnabled} from 'angular2/src/core/facade/lang';
import {bind, Binding, Injector, OpaqueToken} from 'angular2/src/core/di';
import {
@ -17,11 +17,12 @@ import {
import {
BaseException,
WrappedException,
ExceptionHandler
ExceptionHandler,
unimplemented
} from 'angular2/src/core/facade/exceptions';
import {DOM} from 'angular2/src/core/dom/dom_adapter';
import {internalView} from 'angular2/src/core/linker/view_ref';
import {LifeCycle} from 'angular2/src/core/life_cycle/life_cycle';
import {LifeCycle, LifeCycle_} from 'angular2/src/core/life_cycle/life_cycle';
import {
IterableDiffers,
defaultIterableDiffers,
@ -98,7 +99,7 @@ export function applicationCommonBindings(): Array<Type | Binding | any[]> {
DirectiveResolver,
PipeResolver,
DynamicComponentLoader,
bind(LifeCycle).toFactory((exceptionHandler) => new LifeCycle(null, assertionsEnabled()),
bind(LifeCycle).toFactory((exceptionHandler) => new LifeCycle_(null, assertionsEnabled()),
[ExceptionHandler]),
];
}
@ -107,7 +108,7 @@ export function applicationCommonBindings(): Array<Type | Binding | any[]> {
* Create an Angular zone.
*/
export function createNgZone(): NgZone {
return new NgZone({enableLongStackTrace: assertionsEnabled()});
return new NgZone_({enableLongStackTrace: assertionsEnabled()});
}
var _platform: PlatformRef;
@ -131,7 +132,7 @@ export function platformCommon(bindings?: Array<Type | Binding | any[]>, initial
if (isBlank(bindings)) {
bindings = platformBindings();
}
_platform = new PlatformRef(Injector.resolveAndCreate(bindings), () => { _platform = null; });
_platform = new PlatformRef_(Injector.resolveAndCreate(bindings), () => { _platform = null; });
return _platform;
}
@ -143,22 +144,12 @@ export function platformCommon(bindings?: Array<Type | Binding | any[]>, initial
* A page's platform is initialized implicitly when {@link bootstrap}() is called, or
* explicitly by calling {@link platform}().
*/
export class PlatformRef {
/**
* @internal
*/
_applications: ApplicationRef[] = [];
/**
* @internal
*/
constructor(private _injector: Injector, private _dispose: () => void) {}
export abstract class PlatformRef {
/**
* Retrieve the platform {@link Injector}, which is the parent injector for
* every Angular application on the page and provides singleton bindings.
*/
get injector(): Injector { return this._injector; }
get injector(): Injector { return unimplemented(); };
/**
* Instantiate a new Angular application on the page.
@ -188,10 +179,7 @@ export class PlatformRef {
*
* See the {@link bootstrap} documentation for more details.
*/
application(bindings: Array<Type | Binding | any[]>): ApplicationRef {
var app = this._initApp(createNgZone(), bindings);
return app;
}
abstract application(bindings: Array<Type | Binding | any[]>): ApplicationRef;
/**
* Instantiate a new Angular application on the page, using bindings which
@ -205,6 +193,27 @@ export class PlatformRef {
* new application. Once this promise resolves, the application will be
* constructed in the same manner as a normal `application()`.
*/
abstract asyncApplication(bindingFn: (zone: NgZone) => Promise<Array<Type | Binding | any[]>>):
Promise<ApplicationRef>;
/**
* Destroy the Angular platform and all Angular applications on the page.
*/
abstract dispose(): void;
}
export class PlatformRef_ extends PlatformRef {
_applications: ApplicationRef[] = [];
constructor(private _injector: Injector, private _dispose: () => void) { super(); }
get injector(): Injector { return this._injector; }
application(bindings: Array<Type | Binding | any[]>): ApplicationRef {
var app = this._initApp(createNgZone(), bindings);
return app;
}
asyncApplication(bindingFn: (zone: NgZone) =>
Promise<Array<Type | Binding | any[]>>): Promise<ApplicationRef> {
var zone = createNgZone();
@ -227,7 +236,7 @@ export class PlatformRef {
try {
injector = this.injector.resolveAndCreateChild(bindings);
exceptionHandler = injector.get(ExceptionHandler);
zone.overrideOnErrorHandler((e, s) => exceptionHandler.call(e, s));
(<NgZone_>zone).overrideOnErrorHandler((e, s) => exceptionHandler.call(e, s));
} catch (e) {
if (isPresent(exceptionHandler)) {
exceptionHandler.call(e, e.stack);
@ -236,23 +245,16 @@ export class PlatformRef {
}
}
});
var app = new ApplicationRef(this, zone, injector);
var app = new ApplicationRef_(this, zone, injector);
this._applications.push(app);
return app;
}
/**
* Destroy the Angular platform and all Angular applications on the page.
*/
dispose(): void {
this._applications.forEach((app) => app.dispose());
this._dispose();
}
/**
* @internal
*/
_applicationDisposed(app: ApplicationRef): void { ListWrapper.remove(this._applications, app); }
}
@ -261,22 +263,12 @@ export class PlatformRef {
*
* For more about Angular applications, see the documentation for {@link bootstrap}.
*/
export class ApplicationRef {
private _bootstrapListeners: Function[] = [];
private _rootComponents: ComponentRef[] = [];
/**
* @internal
*/
constructor(private _platform: PlatformRef, private _zone: NgZone, private _injector: Injector) {}
export abstract class ApplicationRef {
/**
* Register a listener to be called each time `bootstrap()` is called to bootstrap
* a new root component.
*/
registerBootstrapListener(listener: (ref: ComponentRef) => void): void {
this._bootstrapListeners.push(listener);
}
abstract registerBootstrapListener(listener: (ref: ComponentRef) => void): void;
/**
* Bootstrap a new component at the root level of the application.
@ -300,6 +292,37 @@ export class ApplicationRef {
* app.bootstrap(SecondRootComponent, [bind(OverrideBinding).toClass(OverriddenBinding)]);
* ```
*/
abstract bootstrap(componentType: Type, bindings?: Array<Type | Binding | any[]>):
Promise<ComponentRef>;
/**
* Retrieve the application {@link Injector}.
*/
get injector(): Injector { return unimplemented(); };
/**
* Retrieve the application {@link NgZone}.
*/
get zone(): NgZone { return unimplemented(); };
/**
* Dispose of this application and all of its components.
*/
abstract dispose(): void;
}
export class ApplicationRef_ extends ApplicationRef {
private _bootstrapListeners: Function[] = [];
private _rootComponents: ComponentRef[] = [];
constructor(private _platform: PlatformRef_, private _zone: NgZone, private _injector: Injector) {
super();
}
registerBootstrapListener(listener: (ref: ComponentRef) => void): void {
this._bootstrapListeners.push(listener);
}
bootstrap(componentType: Type, bindings?: Array<Type | Binding | any[]>): Promise<ComponentRef> {
var completer = PromiseWrapper.completer();
this._zone.run(() => {
@ -334,19 +357,10 @@ export class ApplicationRef {
return completer.promise;
}
/**
* Retrieve the application {@link Injector}.
*/
get injector(): Injector { return this._injector; }
/**
* Retrieve the application {@link NgZone}.
*/
get zone(): NgZone { return this._zone; }
/**
* Dispose of this application and all of its components.
*/
dispose(): void {
// TODO(alxhub): Dispose of the NgZone.
this._rootComponents.forEach((ref) => ref.dispose());

View File

@ -2,7 +2,7 @@ import {isPresent, isBlank, StringWrapper} from 'angular2/src/core/facade/lang';
import {BaseException} from 'angular2/src/core/facade/exceptions';
import {ListWrapper} from 'angular2/src/core/facade/collection';
import {ChangeDetectionUtil} from './change_detection_util';
import {ChangeDetectorRef} from './change_detector_ref';
import {ChangeDetectorRef, ChangeDetectorRef_} from './change_detector_ref';
import {DirectiveIndex} from './directive_record';
import {ChangeDetector, ChangeDispatcher} from './interfaces';
import {Pipes} from './pipes';
@ -47,7 +47,7 @@ export class AbstractChangeDetector<T> implements ChangeDetector {
constructor(public id: string, public dispatcher: ChangeDispatcher,
public numberOfPropertyProtoRecords: number, public bindingTargets: BindingTarget[],
public directiveIndices: DirectiveIndex[], public strategy: ChangeDetectionStrategy) {
this.ref = new ChangeDetectorRef(this);
this.ref = new ChangeDetectorRef_(this);
}
addChild(cd: ChangeDetector): void {

View File

@ -1,15 +1,7 @@
import {ChangeDetector} from './interfaces';
import {ChangeDetectionStrategy} from './constants';
/**
* Reference to a component's change detection object.
*/
export class ChangeDetectorRef {
/**
* @internal
*/
constructor(private _cd: ChangeDetector) {}
export abstract class ChangeDetectorRef {
/**
* Marks all {@link OnPush} ancestors as to be checked.
*
@ -48,7 +40,7 @@ export class ChangeDetectorRef {
* bootstrap(App);
* ```
*/
markForCheck(): void { this._cd.markPathToRootAsCheckOnce(); }
abstract markForCheck(): void;
/**
* Detaches the change detector from the change detector tree.
@ -107,7 +99,7 @@ export class ChangeDetectorRef {
* bootstrap(App);
* ```
*/
detach(): void { this._cd.mode = ChangeDetectionStrategy.Detached; }
abstract detach(): void;
/**
* Checks the change detector and its children.
@ -130,7 +122,7 @@ export class ChangeDetectorRef {
*
* See {@link detach} for more information.
*/
detectChanges(): void { this._cd.detectChanges(); }
abstract detectChanges(): void;
/**
* Reattach the change detector to the change detector tree.
@ -190,6 +182,15 @@ export class ChangeDetectorRef {
* bootstrap(App);
* ```
*/
abstract reattach(): void;
}
export class ChangeDetectorRef_ extends ChangeDetectorRef {
constructor(private _cd: ChangeDetector) { super(); }
markForCheck(): void { this._cd.markPathToRootAsCheckOnce(); }
detach(): void { this._cd.mode = ChangeDetectionStrategy.Detached; }
detectChanges(): void { this._cd.detectChanges(); }
reattach(): void {
this._cd.mode = ChangeDetectionStrategy.CheckAlways;
this.markForCheck();

View File

@ -1,4 +1,4 @@
import {Compiler, internalCreateProtoView} from 'angular2/src/core/linker/compiler';
import {Compiler, Compiler_, internalCreateProtoView} from 'angular2/src/core/linker/compiler';
import {ProtoViewRef} from 'angular2/src/core/linker/view_ref';
import {ProtoViewFactory} from 'angular2/src/core/linker/proto_view_factory';
import {TemplateCompiler} from './template_compiler';
@ -7,11 +7,10 @@ import {Injectable} from 'angular2/src/core/di';
import {Type} from 'angular2/src/core/facade/lang';
import {Promise, PromiseWrapper} from 'angular2/src/core/facade/async';
export abstract class RuntimeCompiler extends Compiler {}
@Injectable()
export class RuntimeCompiler extends Compiler {
/**
* @internal
*/
export class RuntimeCompiler_ extends Compiler_ {
constructor(_protoViewFactory: ProtoViewFactory, private _templateCompiler: TemplateCompiler) {
super(_protoViewFactory);
}

View File

@ -1,25 +1,86 @@
import {Type, isPresent, isBlank} from 'angular2/src/core/facade/lang';
import {ListWrapper, MapWrapper, Predicate} from 'angular2/src/core/facade/collection';
import {unimplemented} from 'angular2/src/core/facade/exceptions';
import {DOM} from 'angular2/src/core/dom/dom_adapter';
import {ElementInjector} from 'angular2/src/core/linker/element_injector';
import {AppView} from 'angular2/src/core/linker/view';
import {internalView} from 'angular2/src/core/linker/view_ref';
import {ElementRef} from 'angular2/src/core/linker/element_ref';
import {ElementRef, ElementRef_} from 'angular2/src/core/linker/element_ref';
/**
* A DebugElement contains information from the Angular compiler about an
* element and provides access to the corresponding ElementInjector and
* underlying DOM Element, as well as a way to query for children.
*/
export class DebugElement {
_elementInjector: ElementInjector;
export abstract class DebugElement {
get componentInstance(): any { return unimplemented(); };
get nativeElement(): any { return unimplemented(); };
get elementRef(): ElementRef { return unimplemented(); };
abstract getDirectiveInstance(directiveIndex: number): any;
/**
* @internal
* Get child DebugElements from within the Light DOM.
*
* @return {DebugElement[]}
*/
get children(): DebugElement[] { return unimplemented(); };
/**
* Get the root DebugElement children of a component. Returns an empty
* list if the current DebugElement is not a component root.
*
* @return {DebugElement[]}
*/
get componentViewChildren(): DebugElement[] { return unimplemented(); };
abstract triggerEventHandler(eventName: string, eventObj: Event): void;
abstract hasDirective(type: Type): boolean;
abstract inject(type: Type): any;
abstract getLocal(name: string): any;
/**
* Return the first descendant TestElement matching the given predicate
* and scope.
*
* @param {Function: boolean} predicate
* @param {Scope} scope
*
* @return {DebugElement}
*/
query(predicate: Predicate<DebugElement>, scope: Function = Scope.all): DebugElement {
var results = this.queryAll(predicate, scope);
return results.length > 0 ? results[0] : null;
}
/**
* Return descendant TestElememts matching the given predicate
* and scope.
*
* @param {Function: boolean} predicate
* @param {Scope} scope
*
* @return {DebugElement[]}
*/
queryAll(predicate: Predicate<DebugElement>, scope: Function = Scope.all): DebugElement[] {
var elementsInScope = scope(this);
return ListWrapper.filter(elementsInScope, predicate);
}
}
export class DebugElement_ extends DebugElement {
_elementInjector: ElementInjector;
constructor(private _parentView: AppView, private _boundElementIndex: number) {
super();
this._elementInjector = this._parentView.elementInjectors[this._boundElementIndex];
}
@ -38,21 +99,10 @@ export class DebugElement {
return this._elementInjector.getDirectiveAtIndex(directiveIndex);
}
/**
* Get child DebugElements from within the Light DOM.
*
* @return {DebugElement[]}
*/
get children(): DebugElement[] {
return this._getChildElements(this._parentView, this._boundElementIndex);
}
/**
* Get the root DebugElement children of a component. Returns an empty
* list if the current DebugElement is not a component root.
*
* @return {DebugElement[]}
*/
get componentViewChildren(): DebugElement[] {
var shadowView = this._parentView.getNestedView(this._boundElementIndex);
@ -84,35 +134,6 @@ export class DebugElement {
getLocal(name: string): any { return this._parentView.locals.get(name); }
/**
* Return the first descendant TestElement matching the given predicate
* and scope.
*
* @param {Function: boolean} predicate
* @param {Scope} scope
*
* @return {DebugElement}
*/
query(predicate: Predicate<DebugElement>, scope: Function = Scope.all): DebugElement {
var results = this.queryAll(predicate, scope);
return results.length > 0 ? results[0] : null;
}
/**
* Return descendant TestElememts matching the given predicate
* and scope.
*
* @param {Function: boolean} predicate
* @param {Scope} scope
*
* @return {DebugElement[]}
*/
queryAll(predicate: Predicate<DebugElement>, scope: Function = Scope.all): DebugElement[] {
var elementsInScope = scope(this);
return ListWrapper.filter(elementsInScope, predicate);
}
_getChildElements(view: AppView, parentBoundElementIndex: number): DebugElement[] {
var els = [];
var parentElementBinder = null;
@ -122,7 +143,7 @@ export class DebugElement {
for (var i = 0; i < view.proto.elementBinders.length; ++i) {
var binder = view.proto.elementBinders[i];
if (binder.parent == parentElementBinder) {
els.push(new DebugElement(view, view.elementOffset + i));
els.push(new DebugElement_(view, view.elementOffset + i));
var views = view.viewContainers[view.elementOffset + i];
if (isPresent(views)) {
@ -142,7 +163,8 @@ export class DebugElement {
* @return {DebugElement}
*/
export function inspectElement(elementRef: ElementRef): DebugElement {
return new DebugElement(internalView(elementRef.parentView), elementRef.boundElementIndex);
return new DebugElement_(internalView((<ElementRef_>elementRef).parentView),
(<ElementRef_>elementRef).boundElementIndex);
}
export function asNativeElements(arr: DebugElement[]): any[] {

View File

@ -5,7 +5,7 @@ import {AppViewListener} from 'angular2/src/core/linker/view_listener';
import {AppView} from 'angular2/src/core/linker/view';
import {DOM} from 'angular2/src/core/dom/dom_adapter';
import {Renderer} from 'angular2/src/core/render/api';
import {DebugElement} from './debug_element';
import {DebugElement, DebugElement_} from './debug_element';
const NG_ID_PROPERTY = 'ngid';
const INSPECT_GLOBAL_NAME = 'ng.probe';
@ -38,7 +38,7 @@ export function inspectNativeElement(element): DebugElement {
if (isPresent(elId)) {
var view = _allViewsById.get(elId[0]);
if (isPresent(view)) {
return new DebugElement(view, elId[1]);
return new DebugElement_(view, elId[1]);
}
}
return null;

View File

@ -255,29 +255,31 @@ export class Binding {
* expect(injector.get('message')).toEqual('Hello');
* ```
*/
export class ResolvedBinding {
export abstract class ResolvedBinding {
/**
* @internal
* A key, usually a `Type`.
*/
constructor(
/**
* A key, usually a `Type`.
*/
public key: Key,
public key: Key;
/**
* @internal
* Factory function which can return an instance of an object represented by a key.
*/
public resolvedFactories: ResolvedFactory[],
/**
* Factory function which can return an instance of an object represented by a key.
*/
public resolvedFactories: ResolvedFactory[];
/**
* @internal
* Indicates if the binding is a multi-binding or a regular binding.
*/
public multiBinding: boolean) {}
/**
* Indicates if the binding is a multi-binding or a regular binding.
*/
public multiBinding: boolean;
}
export class ResolvedBinding_ extends ResolvedBinding {
constructor(key: Key, resolvedFactories: ResolvedFactory[], multiBinding: boolean) {
super();
this.key = key;
this.resolvedFactories = resolvedFactories;
this.multiBinding = multiBinding;
}
/** @internal */
get resolvedFactory(): ResolvedFactory { return this.resolvedFactories[0]; }
}
@ -463,7 +465,7 @@ export function resolveFactory(binding: Binding): ResolvedFactory {
* convenience binding syntax.
*/
export function resolveBinding(binding: Binding): ResolvedBinding {
return new ResolvedBinding(Key.get(binding.token), [resolveFactory(binding)], false);
return new ResolvedBinding_(Key.get(binding.token), [resolveFactory(binding)], false);
}
/**
@ -474,11 +476,11 @@ export function resolveBindings(bindings: Array<Type | Binding | any[]>): Resolv
_normalizeBindings(bindings, new Map<number, _NormalizedBinding | _NormalizedBinding[]>()));
return normalized.map(b => {
if (b instanceof _NormalizedBinding) {
return new ResolvedBinding(b.key, [b.resolvedFactory], false);
return new ResolvedBinding_(b.key, [b.resolvedFactory], false);
} else {
var arr = <_NormalizedBinding[]>b;
return new ResolvedBinding(arr[0].key, arr.map(_ => _.resolvedFactory), true);
return new ResolvedBinding_(arr[0].key, arr.map(_ => _.resolvedFactory), true);
}
});
}

View File

@ -1,6 +1,6 @@
import {ListWrapper} from 'angular2/src/core/facade/collection';
import {stringify, isBlank} from 'angular2/src/core/facade/lang';
import {BaseException, WrappedException} from 'angular2/src/core/facade/exceptions';
import {BaseException, WrappedException, unimplemented} from 'angular2/src/core/facade/exceptions';
import {Key} from './key';
import {Injector} from './injector';
@ -134,14 +134,20 @@ export class CyclicDependencyError extends AbstractBindingError {
* }
* ```
*/
export class InstantiationError extends WrappedException {
export abstract class InstantiationError extends WrappedException {
abstract addKey(injector: Injector, key: Key): void;
get wrapperMessage(): string { return unimplemented(); };
get causeKey(): Key { return unimplemented(); };
get context() { return unimplemented(); };
}
export class InstantiationError_ extends InstantiationError {
/** @internal */
keys: Key[];
/** @internal */
injectors: Injector[];
/** @internal */
constructor(injector: Injector, originalException, originalStack, key: Key) {
super("DI Exception", originalException, originalStack, null);
this.keys = [key];

View File

@ -13,6 +13,7 @@ import {
NoBindingError,
CyclicDependencyError,
InstantiationError,
InstantiationError_,
InvalidBindingError,
OutOfBoundsError,
MixingMultiBindingsWithRegularBindings
@ -865,7 +866,7 @@ export class Injector {
break;
}
} catch (e) {
throw new InstantiationError(this, e, e.stack, binding.key);
throw new InstantiationError_(this, e, e.stack, binding.key);
}
return obj;
}

View File

@ -2,6 +2,7 @@ import {isPresent, isString, StringWrapper, isBlank} from 'angular2/src/core/fac
import {DoCheck, OnDestroy} from 'angular2/lifecycle_hooks';
import {Directive} from 'angular2/src/core/metadata';
import {ElementRef} from 'angular2/src/core/linker';
import {ElementRef_} from '../linker/element_ref';
import {
IterableDiffer,
IterableDiffers,
@ -39,7 +40,7 @@ export class NgClass implements DoCheck, OnDestroy {
private _rawClass;
constructor(private _iterableDiffers: IterableDiffers, private _keyValueDiffers: KeyValueDiffers,
private _ngEl: ElementRef, private _renderer: Renderer) {}
private _ngEl: ElementRef_, private _renderer: Renderer) {}
set initialClasses(v) {
this._applyInitialClasses(true);

View File

@ -7,6 +7,7 @@ import {ElementRef} from 'angular2/src/core/linker';
import {Directive} from 'angular2/src/core/metadata';
import {Renderer} from 'angular2/src/core/render';
import {isPresent, isBlank, print} from 'angular2/src/core/facade/lang';
import {ElementRef_} from "../linker/element_ref";
/**
* The `NgStyle` directive changes styles based on a result of expression evaluation.
@ -65,7 +66,7 @@ export class NgStyle implements DoCheck {
_rawStyle;
_differ: KeyValueDiffer;
constructor(private _differs: KeyValueDiffers, private _ngEl: ElementRef,
constructor(private _differs: KeyValueDiffers, private _ngEl: ElementRef_,
private _renderer: Renderer) {}
set rawStyle(v) {

View File

@ -43,3 +43,7 @@ export class WrappedException extends Error {
export function makeTypeError(message?: string): Error {
return new TypeError(message);
}
export function unimplemented(): any {
throw new BaseException('unimplemented');
}

View File

@ -28,7 +28,8 @@ export var Type = Function;
* An example of a `Type` is `MyCustomComponent` class, which in JavaScript is be represented by
* the `MyCustomComponent` constructor function.
*/
export interface Type extends Function { new (...args): any; }
export interface Type extends Function {}
export interface ConcreteType extends Type { new (...args): any; }
export function getTypeNameForDebugging(type: Type): string {
return type['name'];

View File

@ -4,6 +4,7 @@ import {NgZone} from 'angular2/src/core/zone/ng_zone';
import {isPresent} from 'angular2/src/core/facade/lang';
import {BaseException, WrappedException} from 'angular2/src/core/facade/exceptions';
import {wtfLeave, wtfCreateScope, WtfScopeFn} from '../profile/profile';
import {NgZone_} from "../zone/ng_zone";
/**
* Provides access to explicitly trigger change detection in an application.
@ -31,35 +32,7 @@ import {wtfLeave, wtfCreateScope, WtfScopeFn} from '../profile/profile';
* });
* ```
*/
@Injectable()
export class LifeCycle {
static _tickScope: WtfScopeFn = wtfCreateScope('LifeCycle#tick()');
_changeDetectors: ChangeDetector[];
_enforceNoNewChanges: boolean;
_runningTick: boolean = false;
/**
* @internal
*/
constructor(changeDetector: ChangeDetector = null, enforceNoNewChanges: boolean = false) {
this._changeDetectors = [];
if (isPresent(changeDetector)) {
this._changeDetectors.push(changeDetector);
}
this._enforceNoNewChanges = enforceNoNewChanges;
}
/**
* @internal
*/
registerWith(zone: NgZone, changeDetector: ChangeDetector = null) {
if (isPresent(changeDetector)) {
this._changeDetectors.push(changeDetector);
}
zone.overrideOnTurnDone(() => this.tick());
}
export abstract class LifeCycle {
/**
* Invoke this method to explicitly process change detection and its side-effects.
*
@ -75,12 +48,39 @@ export class LifeCycle {
* complete.
*
*/
abstract tick();
}
@Injectable()
export class LifeCycle_ extends LifeCycle {
static _tickScope: WtfScopeFn = wtfCreateScope('LifeCycle#tick()');
_changeDetectors: ChangeDetector[];
_enforceNoNewChanges: boolean;
_runningTick: boolean = false;
constructor(changeDetector: ChangeDetector = null, enforceNoNewChanges: boolean = false) {
super();
this._changeDetectors = [];
if (isPresent(changeDetector)) {
this._changeDetectors.push(changeDetector);
}
this._enforceNoNewChanges = enforceNoNewChanges;
}
registerWith(zone: NgZone, changeDetector: ChangeDetector = null) {
if (isPresent(changeDetector)) {
this._changeDetectors.push(changeDetector);
}
(<NgZone_>zone).overrideOnTurnDone(() => this.tick());
}
tick() {
if (this._runningTick) {
throw new BaseException("LifeCycle.tick is called recursively");
}
var s = LifeCycle._tickScope();
var s = LifeCycle_._tickScope();
try {
this._runningTick = true;
this._changeDetectors.forEach((detector) => detector.detectChanges());

View File

@ -15,12 +15,14 @@ import {CompiledHostTemplate} from 'angular2/src/core/linker/template_commands';
* Most applications should instead use higher-level {@link DynamicComponentLoader} service, which
* both compiles and instantiates a Component.
*/
export abstract class Compiler {
abstract compileInHost(componentType: Type): Promise<ProtoViewRef>;
abstract clearCache();
}
@Injectable()
export class Compiler {
/**
* @internal
*/
constructor(private _protoViewFactory: ProtoViewFactory) {}
export class Compiler_ extends Compiler {
constructor(private _protoViewFactory: ProtoViewFactory) { super(); }
compileInHost(componentType: Type): Promise<ProtoViewRef> {
var metadatas = reflector.annotations(componentType);

View File

@ -13,7 +13,7 @@ import {ViewRef, HostViewRef} from './view_ref';
* Component Instance and allows you to destroy the Component Instance via the {@link #dispose}
* method.
*/
export class ComponentRef {
export abstract class ComponentRef {
/**
* Location of the Host Element of this Component Instance.
*/
@ -31,43 +31,11 @@ export class ComponentRef {
*/
componentType: Type;
/**
* @internal
*
* The injector provided {@link DynamicComponentLoader#loadAsRoot}.
*
* TODO(i): this api is useless and should be replaced by an injector retrieved from
* the HostElementRef, which is currently not possible.
*/
injector: Injector;
/**
* @internal
*
* TODO(i): refactor into public/private fields
*/
constructor(location: ElementRef, instance: any, componentType: Type, injector: Injector,
private _dispose: () => void) {
this.location = location;
this.instance = instance;
this.componentType = componentType;
this.injector = injector;
}
/**
* The {@link ViewRef} of the Host View of this Component instance.
*/
get hostView(): HostViewRef { return this.location.parentView; }
/**
* @internal
*
* Returns the type of this Component instance.
*
* TODO(i): this api should be removed
*/
get hostComponentType(): Type { return this.componentType; }
/**
* @internal
*
@ -82,19 +50,46 @@ export class ComponentRef {
*
* TODO(i): rename to destroy to be consistent with AppViewManager and ViewContainerRef
*/
abstract dispose();
}
export class ComponentRef_ extends ComponentRef {
/**
* The injector provided {@link DynamicComponentLoader#loadAsRoot}.
*
* TODO(i): this api is useless and should be replaced by an injector retrieved from
* the HostElementRef, which is currently not possible.
*/
injector: Injector;
/**
* TODO(i): refactor into public/private fields
*/
constructor(location: ElementRef, instance: any, componentType: Type, injector: Injector,
private _dispose: () => void) {
super();
this.location = location;
this.instance = instance;
this.componentType = componentType;
this.injector = injector;
}
/**
* @internal
*
* Returns the type of this Component instance.
*
* TODO(i): this api should be removed
*/
get hostComponentType(): Type { return this.componentType; }
dispose() { this._dispose(); }
}
/**
* Service for instantiating a Component and attaching it to a View at a specified location.
*/
@Injectable()
export class DynamicComponentLoader {
/**
* @internal
*/
constructor(private _compiler: Compiler, private _viewManager: AppViewManager) {}
export abstract class DynamicComponentLoader {
/**
* Creates an instance of a Component `type` and attaches it to the first element in the
* platform-specific global view that matches the component's selector.
@ -155,23 +150,8 @@ export class DynamicComponentLoader {
* </my-app>
* ```
*/
loadAsRoot(type: Type, overrideSelector: string, injector: Injector,
onDispose?: () => void): Promise<ComponentRef> {
return this._compiler.compileInHost(type).then(hostProtoViewRef => {
var hostViewRef =
this._viewManager.createRootHostView(hostProtoViewRef, overrideSelector, injector);
var newLocation = this._viewManager.getHostElement(hostViewRef);
var component = this._viewManager.getComponent(newLocation);
var dispose = () => {
this._viewManager.destroyRootHostView(hostViewRef);
if (isPresent(onDispose)) {
onDispose();
}
};
return new ComponentRef(newLocation, component, type, injector, dispose);
});
}
abstract loadAsRoot(type: Type, overrideSelector: string, injector: Injector,
onDispose?: () => void): Promise<ComponentRef>;
/**
* Creates an instance of a Component and attaches it to a View Container located inside of the
@ -228,11 +208,8 @@ export class DynamicComponentLoader {
* </my-app>
* ```
*/
loadIntoLocation(type: Type, hostLocation: ElementRef, anchorName: string,
bindings: ResolvedBinding[] = null): Promise<ComponentRef> {
return this.loadNextToLocation(
type, this._viewManager.getNamedElementInComponentView(hostLocation, anchorName), bindings);
}
abstract loadIntoLocation(type: Type, hostLocation: ElementRef, anchorName: string,
bindings?: ResolvedBinding[]): Promise<ComponentRef>;
/**
* Creates an instance of a Component and attaches it to the View Container found at the
@ -279,6 +256,38 @@ export class DynamicComponentLoader {
* <child-component>Child</child-component>
* ```
*/
abstract loadNextToLocation(type: Type, location: ElementRef, bindings?: ResolvedBinding[]):
Promise<ComponentRef>;
}
@Injectable()
export class DynamicComponentLoader_ extends DynamicComponentLoader {
constructor(private _compiler: Compiler, private _viewManager: AppViewManager) { super(); }
loadAsRoot(type: Type, overrideSelector: string, injector: Injector,
onDispose?: () => void): Promise<ComponentRef> {
return this._compiler.compileInHost(type).then(hostProtoViewRef => {
var hostViewRef =
this._viewManager.createRootHostView(hostProtoViewRef, overrideSelector, injector);
var newLocation = this._viewManager.getHostElement(hostViewRef);
var component = this._viewManager.getComponent(newLocation);
var dispose = () => {
this._viewManager.destroyRootHostView(hostViewRef);
if (isPresent(onDispose)) {
onDispose();
}
};
return new ComponentRef_(newLocation, component, type, injector, dispose);
});
}
loadIntoLocation(type: Type, hostLocation: ElementRef, anchorName: string,
bindings: ResolvedBinding[] = null): Promise<ComponentRef> {
return this.loadNextToLocation(
type, this._viewManager.getNamedElementInComponentView(hostLocation, anchorName), bindings);
}
loadNextToLocation(type: Type, location: ElementRef,
bindings: ResolvedBinding[] = null): Promise<ComponentRef> {
return this._compiler.compileInHost(type).then(hostProtoViewRef => {
@ -294,7 +303,7 @@ export class DynamicComponentLoader {
viewContainer.remove(index);
}
};
return new ComponentRef(newLocation, component, type, null, dispose);
return new ComponentRef_(newLocation, component, type, null, dispose);
});
}
}

View File

@ -52,6 +52,8 @@ import {EventConfig} from 'angular2/src/core/linker/event_config';
import {PipeBinding} from '../pipes/pipe_binding';
import {LifecycleHooks} from './interfaces';
import {ViewContainerRef_} from "./view_container_ref";
import {ResolvedBinding_} from "../di/binding";
var _staticKeys;
@ -126,7 +128,7 @@ export class DirectiveDependency extends Dependency {
}
}
export class DirectiveBinding extends ResolvedBinding {
export class DirectiveBinding extends ResolvedBinding_ {
public callOnDestroy: boolean;
constructor(key: Key, factory: Function, deps: Dependency[], public metadata: DirectiveMetadata,
@ -435,7 +437,7 @@ export class ElementInjector extends TreeNode<ElementInjector> implements Depend
getElementRef(): ElementRef { return this._preBuiltObjects.elementRef; }
getViewContainerRef(): ViewContainerRef {
return new ViewContainerRef(this._preBuiltObjects.viewManager, this.getElementRef());
return new ViewContainerRef_(this._preBuiltObjects.viewManager, this.getElementRef());
}
getNestedView(): viewModule.AppView { return this._preBuiltObjects.nestedView; }

View File

@ -1,6 +1,7 @@
import {BaseException} from 'angular2/src/core/facade/exceptions';
import {ViewRef} from './view_ref';
import {BaseException, unimplemented} from 'angular2/src/core/facade/exceptions';
import {ViewRef, ViewRef_} from './view_ref';
import {RenderViewRef, RenderElementRef, Renderer} from 'angular2/src/core/render/api';
import {ChangeDetectorRef} from "../change_detection/change_detector_ref";
/**
* Represents a location in a View that has an injection, change-detection and render context
@ -12,7 +13,7 @@ import {RenderViewRef, RenderElementRef, Renderer} from 'angular2/src/core/rende
* An `ElementRef` is backed by a render-specific element. In the browser, this is usually a DOM
* element.
*/
export class ElementRef implements RenderElementRef {
export abstract class ElementRef implements RenderElementRef {
/**
* @internal
*
@ -20,7 +21,6 @@ export class ElementRef implements RenderElementRef {
*/
parentView: ViewRef;
/**
* @internal
*
@ -29,23 +29,6 @@ export class ElementRef implements RenderElementRef {
* This is used internally by the Angular framework to locate elements.
*/
boundElementIndex: number;
/**
* @internal
*/
constructor(parentView: ViewRef, boundElementIndex: number, private _renderer: Renderer) {
this.parentView = parentView;
this.boundElementIndex = boundElementIndex;
}
/**
* @internal
*/
get renderView(): RenderViewRef { return this.parentView.render; }
// TODO(tbosch): remove this once Typescript supports declaring interfaces
// that contain getters
// https://github.com/Microsoft/TypeScript/issues/3745
set renderView(viewRef: RenderViewRef) { throw new BaseException('Abstract setter'); }
/**
* The underlying native element or `null` if direct access to native elements is not supported
@ -66,5 +49,23 @@ export class ElementRef implements RenderElementRef {
* </p>
* </div>
*/
get nativeElement(): any { return unimplemented(); };
get renderView(): RenderViewRef { return unimplemented(); }
}
export class ElementRef_ extends ElementRef {
constructor(public parentView: ViewRef,
/**
* Index of the element inside the {@link ViewRef}.
*
* This is used internally by the Angular framework to locate elements.
*/
public boundElementIndex: number, private _renderer: Renderer) {
super();
}
get renderView(): RenderViewRef { return (<ViewRef_>this.parentView).render; }
get nativeElement(): any { return this._renderer.getNativeElementSync(this); }
}

View File

@ -1,5 +1,5 @@
import {internalView, ProtoViewRef} from './view_ref';
import {ElementRef} from './element_ref';
import {ElementRef, ElementRef_} from './element_ref';
import * as viewModule from './view';
/**
@ -14,7 +14,7 @@ import * as viewModule from './view';
* {@link ViewContainerRef#createEmbeddedView}, which will create the View and attach it to the
* View Container.
*/
export class TemplateRef {
export abstract class TemplateRef {
/**
* The location in the View where the Embedded View logically belongs to.
*
@ -30,28 +30,30 @@ export class TemplateRef {
elementRef: ElementRef;
/**
* @internal
* Allows you to check if this Embedded Template defines Local Variable with name matching `name`.
*/
constructor(elementRef: ElementRef) { this.elementRef = elementRef; }
abstract hasLocal(name: string): boolean;
}
export class TemplateRef_ extends TemplateRef {
constructor(elementRef: ElementRef) {
super();
this.elementRef = elementRef;
}
private _getProtoView(): viewModule.AppProtoView {
var parentView = internalView(this.elementRef.parentView);
return parentView.proto
.elementBinders[this.elementRef.boundElementIndex - parentView.elementOffset]
let elementRef = <ElementRef_>this.elementRef;
var parentView = internalView(elementRef.parentView);
return parentView.proto.elementBinders[elementRef.boundElementIndex - parentView.elementOffset]
.nestedProtoView;
}
/**
* @internal
*
* Reference to the ProtoView used for creating Embedded Views that are based on the compiled
* Embedded Template.
*/
get protoViewRef(): ProtoViewRef { return this._getProtoView().ref; }
/**
* Allows you to check if this Embedded Template defines Local Variable with name matching `name`.
*/
hasLocal(name: string): boolean {
return this._getProtoView().templateVariableBindings.has(name);
}

View File

@ -33,6 +33,8 @@ import {ElementRef} from './element_ref';
import {ProtoPipes} from 'angular2/src/core/pipes/pipes';
import {camelCaseToDashCase} from 'angular2/src/core/render/dom/util';
import {TemplateCmd} from './template_commands';
import {ViewRef_} from "./view_ref";
import {ProtoViewRef_} from "./view_ref";
export {DebugContext} from 'angular2/src/core/change_detection/interfaces';
@ -106,7 +108,7 @@ export class AppView implements ChangeDispatcher, RenderEventDispatcher {
protoLocals: Map<string, any>, public render: renderApi.RenderViewRef,
public renderFragment: renderApi.RenderFragmentRef,
public containerElementInjector: ElementInjector) {
this.ref = new ViewRef(this);
this.ref = new ViewRef_(this);
this.locals = new Locals(null, MapWrapper.clone(protoLocals)); // TODO optimize this
}
@ -322,7 +324,7 @@ export class AppProtoView {
constructor(public templateCmds: TemplateCmd[], public type: ViewType, public isMergable: boolean,
public changeDetectorFactory: Function,
public templateVariableBindings: Map<string, string>, public pipes: ProtoPipes) {
this.ref = new ProtoViewRef(this);
this.ref = new ProtoViewRef_(this);
}
init(render: renderApi.RenderProtoViewRef, elementBinders: ElementBinder[],

View File

@ -1,11 +1,12 @@
import {ListWrapper} from 'angular2/src/core/facade/collection';
import {unimplemented} from 'angular2/src/core/facade/exceptions';
import {ResolvedBinding} from 'angular2/src/core/di';
import {isPresent, isBlank} from 'angular2/src/core/facade/lang';
import * as avmModule from './view_manager';
import * as viewModule from './view';
import {ElementRef} from './element_ref';
import {ElementRef, ElementRef_} from './element_ref';
import {TemplateRef} from './template_ref';
import {ViewRef, HostViewRef, ProtoViewRef, internalView} from './view_ref';
@ -29,26 +30,12 @@ import {ViewRef, HostViewRef, ProtoViewRef, internalView} from './view_ref';
*
* <!-- TODO(i): we are also considering ElementRef#viewContainer api -->
*/
export class ViewContainerRef {
export abstract class ViewContainerRef {
/**
* @internal
* Anchor element that specifies the location of this container in the containing View.
* <!-- TODO: rename to anchorElement -->
*/
constructor(
/**
* @internal
*/
public viewManager: avmModule.AppViewManager,
/**
* Anchor element that specifies the location of this container in the containing View.
* <!-- TODO: rename to anchorElement -->
*/
public element: ElementRef) {}
private _getViews(): Array<viewModule.AppView> {
var vc = internalView(this.element.parentView).viewContainers[this.element.boundElementIndex];
return isPresent(vc) ? vc.views : [];
}
public element: ElementRef;
/**
* Destroys all Views in this container.
@ -62,12 +49,12 @@ export class ViewContainerRef {
/**
* Returns the {@link ViewRef} for the View located in this container at the specified index.
*/
get(index: number): ViewRef { return this._getViews()[index].ref; }
abstract get(index: number): ViewRef;
/**
* Returns the number of Views currently attached to this container.
*/
get length(): number { return this._getViews().length; }
get length(): number { return unimplemented(); };
/**
* Instantiates an Embedded View based on the {@link TemplateRef `templateRef`} and inserts it
@ -77,12 +64,7 @@ export class ViewContainerRef {
*
* Returns the {@link ViewRef} for the newly created View.
*/
// TODO(rado): profile and decide whether bounds checks should be added
// to the methods below.
createEmbeddedView(templateRef: TemplateRef, index: number = -1): ViewRef {
if (index == -1) index = this.length;
return this.viewManager.createEmbeddedViewInContainer(this.element, index, templateRef);
}
abstract createEmbeddedView(templateRef: TemplateRef, index?: number): ViewRef;
/**
* Instantiates a single {@link Component} and inserts its Host View into this container at the
@ -98,12 +80,8 @@ export class ViewContainerRef {
*
* Returns the {@link HostViewRef} of the Host View created for the newly instantiated Component.
*/
createHostView(protoViewRef: ProtoViewRef = null, index: number = -1,
dynamicallyCreatedBindings: ResolvedBinding[] = null): HostViewRef {
if (index == -1) index = this.length;
return this.viewManager.createHostViewInContainer(this.element, index, protoViewRef,
dynamicallyCreatedBindings);
}
abstract createHostView(protoViewRef?: ProtoViewRef, index?: number,
dynamicallyCreatedBindings?: ResolvedBinding[]): HostViewRef;
/**
* Inserts a View identified by a {@link ViewRef} into the container at the specified `index`.
@ -112,25 +90,68 @@ export class ViewContainerRef {
*
* Returns the inserted {@link ViewRef}.
*/
// TODO(i): refactor insert+remove into move
insert(viewRef: ViewRef, index: number = -1): ViewRef {
if (index == -1) index = this.length;
return this.viewManager.attachViewInContainer(this.element, index, viewRef);
}
abstract insert(viewRef: ViewRef, index?: number): ViewRef;
/**
* Returns the index of the View, specified via {@link ViewRef}, within the current container or
* `-1` if this container doesn't contain the View.
*/
indexOf(viewRef: ViewRef): number {
return ListWrapper.indexOf(this._getViews(), internalView(viewRef));
}
abstract indexOf(viewRef: ViewRef): number;
/**
* Destroys a View attached to this container at the specified `index`.
*
* If `index` is not specified, the last View in the container will be removed.
*/
abstract remove(index?: number): void;
/**
* Use along with {@link #insert} to move a View within the current container.
*
* If the `index` param is omitted, the last {@link ViewRef} is detached.
*/
abstract detach(index?: number): ViewRef;
}
export class ViewContainerRef_ extends ViewContainerRef {
constructor(public viewManager: avmModule.AppViewManager, element: ElementRef) {
super();
this.element = element;
}
private _getViews(): Array<viewModule.AppView> {
let element = <ElementRef_>this.element;
var vc = internalView(element.parentView).viewContainers[element.boundElementIndex];
return isPresent(vc) ? vc.views : [];
}
get(index: number): ViewRef { return this._getViews()[index].ref; }
get length(): number { return this._getViews().length; }
// TODO(rado): profile and decide whether bounds checks should be added
// to the methods below.
createEmbeddedView(templateRef: TemplateRef, index: number = -1): ViewRef {
if (index == -1) index = this.length;
return this.viewManager.createEmbeddedViewInContainer(this.element, index, templateRef);
}
createHostView(protoViewRef: ProtoViewRef = null, index: number = -1,
dynamicallyCreatedBindings: ResolvedBinding[] = null): HostViewRef {
if (index == -1) index = this.length;
return this.viewManager.createHostViewInContainer(this.element, index, protoViewRef,
dynamicallyCreatedBindings);
}
// TODO(i): refactor insert+remove into move
insert(viewRef: ViewRef, index: number = -1): ViewRef {
if (index == -1) index = this.length;
return this.viewManager.attachViewInContainer(this.element, index, viewRef);
}
indexOf(viewRef: ViewRef): number {
return ListWrapper.indexOf(this._getViews(), internalView(viewRef));
}
// TODO(i): rename to destroy
remove(index: number = -1): void {
if (index == -1) index = this.length - 1;
@ -138,11 +159,6 @@ export class ViewContainerRef {
// view is intentionally not returned to the client.
}
/**
* Use along with {@link #insert} to move a View within the current container.
*
* If the `index` param is omitted, the last {@link ViewRef} is detached.
*/
// TODO(i): refactor insert+remove into move
detach(index: number = -1): ViewRef {
if (index == -1) index = this.length - 1;

View File

@ -9,10 +9,10 @@ import {
import {isPresent, isBlank} from 'angular2/src/core/facade/lang';
import {BaseException} from 'angular2/src/core/facade/exceptions';
import * as viewModule from './view';
import {ElementRef} from './element_ref';
import {ElementRef, ElementRef_} from './element_ref';
import {ProtoViewRef, ViewRef, HostViewRef, internalView, internalProtoView} from './view_ref';
import {ViewContainerRef} from './view_container_ref';
import {TemplateRef} from './template_ref';
import {TemplateRef, TemplateRef_} from './template_ref';
import {
Renderer,
RenderViewRef,
@ -31,25 +31,11 @@ import {ProtoViewFactory} from './proto_view_factory';
* Most applications should use higher-level abstractions like {@link DynamicComponentLoader} and
* {@link ViewContainerRef} instead.
*/
@Injectable()
export class AppViewManager {
private _protoViewFactory: ProtoViewFactory;
/**
* @internal
*/
constructor(private _viewPool: AppViewPool, private _viewListener: AppViewListener,
private _utils: AppViewManagerUtils, private _renderer: Renderer,
@Inject(forwardRef(() => ProtoViewFactory)) _protoViewFactory) {
this._protoViewFactory = _protoViewFactory;
}
export abstract class AppViewManager {
/**
* Returns a {@link ViewContainerRef} of the View Container at the specified location.
*/
getViewContainer(location: ElementRef): ViewContainerRef {
var hostView = internalView(location.parentView);
return hostView.elementInjectors[location.boundElementIndex].getViewContainerRef();
}
abstract getViewContainer(location: ElementRef): ViewContainerRef;
/**
* Returns the {@link ElementRef} that makes up the specified Host View.
@ -69,30 +55,14 @@ export class AppViewManager {
* Throws an exception if the specified `hostLocation` is not a Host Element of a Component, or if
* variable `variableName` couldn't be found in the Component View of this Component.
*/
getNamedElementInComponentView(hostLocation: ElementRef, variableName: string): ElementRef {
var hostView = internalView(hostLocation.parentView);
var boundElementIndex = hostLocation.boundElementIndex;
var componentView = hostView.getNestedView(boundElementIndex);
if (isBlank(componentView)) {
throw new BaseException(`There is no component directive at element ${boundElementIndex}`);
}
var binderIdx = componentView.proto.variableLocations.get(variableName);
if (isBlank(binderIdx)) {
throw new BaseException(`Could not find variable ${variableName}`);
}
return componentView.elementRefs[componentView.elementOffset + binderIdx];
}
abstract getNamedElementInComponentView(hostLocation: ElementRef, variableName: string):
ElementRef;
/**
* Returns the component instance for the provided Host Element.
*/
getComponent(hostLocation: ElementRef): any {
var hostView = internalView(hostLocation.parentView);
var boundElementIndex = hostLocation.boundElementIndex;
return this._utils.getComponentInstance(hostView, boundElementIndex);
}
abstract getComponent(hostLocation: ElementRef): any;
_createRootHostViewScope: WtfScopeFn = wtfCreateScope('AppViewManager#createRootHostView()');
/**
* Creates an instance of a Component and attaches it to the first element in the global View
* (usually DOM Document) that matches the component's selector or `overrideSelector`.
@ -145,6 +115,112 @@ export class AppViewManager {
* ng.bootstrap(MyApp);
* ```
*/
abstract createRootHostView(hostProtoViewRef: ProtoViewRef, overrideSelector: string,
injector: Injector): HostViewRef;
/**
* Destroys the Host View created via {@link AppViewManager#createRootHostView}.
*
* Along with the Host View, the Component Instance as well as all nested View and Components are
* destroyed as well.
*/
abstract destroyRootHostView(hostViewRef: HostViewRef);
/**
* Instantiates an Embedded View based on the {@link TemplateRef `templateRef`} and inserts it
* into the View Container specified via `viewContainerLocation` at the specified `index`.
*
* Returns the {@link ViewRef} for the newly created View.
*
* This as a low-level way to create and attach an Embedded via to a View Container. Most
* applications should used {@link ViewContainerRef#createEmbeddedView} instead.
*
* Use {@link AppViewManager#destroyViewInContainer} to destroy the created Embedded View.
*/
// TODO(i): this low-level version of ViewContainerRef#createEmbeddedView doesn't add anything new
// we should make it private, otherwise we have two apis to do the same thing.
abstract createEmbeddedViewInContainer(viewContainerLocation: ElementRef, index: number,
templateRef: TemplateRef): ViewRef;
/**
* Instantiates a single {@link Component} and inserts its Host View into the View Container
* found at `viewContainerLocation`. Within the container, the view will be inserted at position
* specified via `index`.
*
* The component is instantiated using its {@link ProtoViewRef `protoViewRef`} which can be
* obtained via {@link Compiler#compileInHost}.
*
* You can optionally specify `imperativelyCreatedInjector`, which configure the {@link Injector}
* that will be created for the Host View.
*
* Returns the {@link HostViewRef} of the Host View created for the newly instantiated Component.
*
* Use {@link AppViewManager#destroyViewInContainer} to destroy the created Host View.
*/
abstract createHostViewInContainer(viewContainerLocation: ElementRef, index: number,
protoViewRef: ProtoViewRef,
imperativelyCreatedInjector: ResolvedBinding[]): HostViewRef;
/**
* Destroys an Embedded or Host View attached to a View Container at the specified `index`.
*
* The View Container is located via `viewContainerLocation`.
*/
abstract destroyViewInContainer(viewContainerLocation: ElementRef, index: number);
/**
*
* See {@link AppViewManager#detachViewInContainer}.
*/
// TODO(i): refactor detachViewInContainer+attachViewInContainer to moveViewInContainer
abstract attachViewInContainer(viewContainerLocation: ElementRef, index: number,
viewRef: ViewRef): ViewRef;
/**
* See {@link AppViewManager#attachViewInContainer}.
*/
abstract detachViewInContainer(viewContainerLocation: ElementRef, index: number): ViewRef;
}
@Injectable()
export class AppViewManager_ extends AppViewManager {
private _protoViewFactory: ProtoViewFactory;
constructor(private _viewPool: AppViewPool, private _viewListener: AppViewListener,
private _utils: AppViewManagerUtils, private _renderer: Renderer,
@Inject(forwardRef(() => ProtoViewFactory)) _protoViewFactory) {
super();
this._protoViewFactory = _protoViewFactory;
}
getViewContainer(location: ElementRef): ViewContainerRef {
var hostView = internalView((<ElementRef_>location).parentView);
return hostView.elementInjectors[(<ElementRef_>location).boundElementIndex]
.getViewContainerRef();
}
getNamedElementInComponentView(hostLocation: ElementRef, variableName: string): ElementRef {
var hostView = internalView((<ElementRef_>hostLocation).parentView);
var boundElementIndex = (<ElementRef_>hostLocation).boundElementIndex;
var componentView = hostView.getNestedView(boundElementIndex);
if (isBlank(componentView)) {
throw new BaseException(`There is no component directive at element ${boundElementIndex}`);
}
var binderIdx = componentView.proto.variableLocations.get(variableName);
if (isBlank(binderIdx)) {
throw new BaseException(`Could not find variable ${variableName}`);
}
return componentView.elementRefs[componentView.elementOffset + binderIdx];
}
getComponent(hostLocation: ElementRef): any {
var hostView = internalView((<ElementRef_>hostLocation).parentView);
var boundElementIndex = (<ElementRef_>hostLocation).boundElementIndex;
return this._utils.getComponentInstance(hostView, boundElementIndex);
}
_createRootHostViewScope: WtfScopeFn = wtfCreateScope('AppViewManager#createRootHostView()');
createRootHostView(hostProtoViewRef: ProtoViewRef, overrideSelector: string,
injector: Injector): HostViewRef {
var s = this._createRootHostViewScope();
@ -165,12 +241,6 @@ export class AppViewManager {
_destroyRootHostViewScope: WtfScopeFn = wtfCreateScope('AppViewManager#destroyRootHostView()');
/**
* Destroys the Host View created via {@link AppViewManager#createRootHostView}.
*
* Along with the Host View, the Component Instance as well as all nested View and Components are
* destroyed as well.
*/
destroyRootHostView(hostViewRef: HostViewRef) {
// Note: Don't put the hostView into the view pool
// as it is depending on the element for which it was created.
@ -187,23 +257,10 @@ export class AppViewManager {
_createEmbeddedViewInContainerScope: WtfScopeFn =
wtfCreateScope('AppViewManager#createEmbeddedViewInContainer()');
/**
* Instantiates an Embedded View based on the {@link TemplateRef `templateRef`} and inserts it
* into the View Container specified via `viewContainerLocation` at the specified `index`.
*
* Returns the {@link ViewRef} for the newly created View.
*
* This as a low-level way to create and attach an Embedded via to a View Container. Most
* applications should used {@link ViewContainerRef#createEmbeddedView} instead.
*
* Use {@link AppViewManager#destroyViewInContainer} to destroy the created Embedded View.
*/
// TODO(i): this low-level version of ViewContainerRef#createEmbeddedView doesn't add anything new
// we should make it private, otherwise we have two apis to do the same thing.
createEmbeddedViewInContainer(viewContainerLocation: ElementRef, index: number,
templateRef: TemplateRef): ViewRef {
var s = this._createEmbeddedViewInContainerScope();
var protoView = internalProtoView(templateRef.protoViewRef);
var protoView = internalProtoView((<TemplateRef_>templateRef).protoViewRef);
if (protoView.type !== viewModule.ViewType.EMBEDDED) {
throw new BaseException('This method can only be called with embedded ProtoViews!');
}
@ -215,21 +272,6 @@ export class AppViewManager {
_createHostViewInContainerScope: WtfScopeFn =
wtfCreateScope('AppViewManager#createHostViewInContainer()');
/**
* Instantiates a single {@link Component} and inserts its Host View into the View Container
* found at `viewContainerLocation`. Within the container, the view will be inserted at position
* specified via `index`.
*
* The component is instantiated using its {@link ProtoViewRef `protoViewRef`} which can be
* obtained via {@link Compiler#compileInHost}.
*
* You can optionally specify `imperativelyCreatedInjector`, which configure the {@link Injector}
* that will be created for the Host View.
*
* Returns the {@link HostViewRef} of the Host View created for the newly instantiated Component.
*
* Use {@link AppViewManager#destroyViewInContainer} to destroy the created Host View.
*/
createHostViewInContainer(viewContainerLocation: ElementRef, index: number,
protoViewRef: ProtoViewRef,
imperativelyCreatedInjector: ResolvedBinding[]): HostViewRef {
@ -251,10 +293,10 @@ export class AppViewManager {
_createViewInContainer(viewContainerLocation: ElementRef, index: number,
protoView: viewModule.AppProtoView, context: ElementRef,
imperativelyCreatedInjector: ResolvedBinding[]): ViewRef {
var parentView = internalView(viewContainerLocation.parentView);
var boundElementIndex = viewContainerLocation.boundElementIndex;
var contextView = internalView(context.parentView);
var contextBoundElementIndex = context.boundElementIndex;
var parentView = internalView((<ElementRef_>viewContainerLocation).parentView);
var boundElementIndex = (<ElementRef_>viewContainerLocation).boundElementIndex;
var contextView = internalView((<ElementRef_>context).parentView);
var contextBoundElementIndex = (<ElementRef_>context).boundElementIndex;
var embeddedFragmentView = contextView.getNestedView(contextBoundElementIndex);
var view;
if (protoView.type === viewModule.ViewType.EMBEDDED && isPresent(embeddedFragmentView) &&
@ -291,32 +333,23 @@ export class AppViewManager {
_destroyViewInContainerScope = wtfCreateScope('AppViewMananger#destroyViewInContainer()');
/**
* Destroys an Embedded or Host View attached to a View Container at the specified `index`.
*
* The View Container is located via `viewContainerLocation`.
*/
destroyViewInContainer(viewContainerLocation: ElementRef, index: number) {
var s = this._destroyViewInContainerScope();
var parentView = internalView(viewContainerLocation.parentView);
var boundElementIndex = viewContainerLocation.boundElementIndex;
var parentView = internalView((<ElementRef_>viewContainerLocation).parentView);
var boundElementIndex = (<ElementRef_>viewContainerLocation).boundElementIndex;
this._destroyViewInContainer(parentView, boundElementIndex, index);
wtfLeave(s);
}
_attachViewInContainerScope = wtfCreateScope('AppViewMananger#attachViewInContainer()');
/**
*
* See {@link AppViewManager#detachViewInContainer}.
*/
// TODO(i): refactor detachViewInContainer+attachViewInContainer to moveViewInContainer
attachViewInContainer(viewContainerLocation: ElementRef, index: number,
viewRef: ViewRef): ViewRef {
var s = this._attachViewInContainerScope();
var view = internalView(viewRef);
var parentView = internalView(viewContainerLocation.parentView);
var boundElementIndex = viewContainerLocation.boundElementIndex;
var parentView = internalView((<ElementRef_>viewContainerLocation).parentView);
var boundElementIndex = (<ElementRef_>viewContainerLocation).boundElementIndex;
// TODO(tbosch): the public methods attachViewInContainer/detachViewInContainer
// are used for moving elements without the same container.
// We will change this into an atomic `move` operation, which should preserve the
@ -330,14 +363,11 @@ export class AppViewManager {
_detachViewInContainerScope = wtfCreateScope('AppViewMananger#detachViewInContainer()');
/**
* See {@link AppViewManager#attachViewInContainer}.
*/
// TODO(i): refactor detachViewInContainer+attachViewInContainer to moveViewInContainer
detachViewInContainer(viewContainerLocation: ElementRef, index: number): ViewRef {
var s = this._detachViewInContainerScope();
var parentView = internalView(viewContainerLocation.parentView);
var boundElementIndex = viewContainerLocation.boundElementIndex;
var parentView = internalView((<ElementRef_>viewContainerLocation).parentView);
var boundElementIndex = (<ElementRef_>viewContainerLocation).boundElementIndex;
var viewContainer = parentView.viewContainers[boundElementIndex];
var view = viewContainer.views[index];
this._utils.detachViewInContainer(parentView, boundElementIndex, index);

View File

@ -9,6 +9,8 @@ import {TemplateRef} from './template_ref';
import {Renderer, RenderViewWithFragments} from 'angular2/src/core/render/api';
import {Locals} from 'angular2/src/core/change_detection/change_detection';
import {Pipes} from 'angular2/src/core/pipes/pipes';
import {TemplateRef_} from "./template_ref";
import {ElementRef_} from "./element_ref";
@Injectable()
export class AppViewManagerUtils {
@ -86,14 +88,14 @@ export class AppViewManagerUtils {
elementInjectors[boundElementIndex] = elementInjector;
// elementRefs
var el = new ElementRef(currentView.ref, boundElementIndex, renderer);
var el = new ElementRef_(currentView.ref, boundElementIndex, renderer);
elementRefs[el.boundElementIndex] = el;
// preBuiltObjects
if (isPresent(elementInjector)) {
var templateRef = isPresent(binder.nestedProtoView) &&
binder.nestedProtoView.type === viewModule.ViewType.EMBEDDED ?
new TemplateRef(el) :
new TemplateRef_(el) :
null;
preBuiltObjects[boundElementIndex] =
new eli.PreBuiltObjects(viewManager, currentView, el, templateRef);

View File

@ -1,16 +1,17 @@
import {isPresent} from 'angular2/src/core/facade/lang';
import {unimplemented} from 'angular2/src/core/facade/exceptions';
import * as viewModule from './view';
import {ChangeDetectorRef} from '../change_detection/change_detector_ref';
import {RenderViewRef, RenderFragmentRef} from 'angular2/src/core/render/api';
// This is a workaround for privacy in Dart as we don't have library parts
export function internalView(viewRef: ViewRef): viewModule.AppView {
return viewRef._view;
return (<ViewRef_>viewRef)._view;
}
// This is a workaround for privacy in Dart as we don't have library parts
export function internalProtoView(protoViewRef: ProtoViewRef): viewModule.AppProtoView {
return isPresent(protoViewRef) ? protoViewRef._protoView : null;
return isPresent(protoViewRef) ? (<ProtoViewRef_>protoViewRef)._protoView : null;
}
@ -83,31 +84,34 @@ export interface HostViewRef {
* <!-- /ViewRef: outer-0 -->
* ```
*/
export class ViewRef implements HostViewRef {
export abstract class ViewRef implements HostViewRef {
/**
* Sets `value` of local variable called `variableName` in this View.
*/
abstract setLocal(variableName: string, value: any): void;
get changeDetectorRef(): ChangeDetectorRef { return unimplemented(); }
set changeDetectorRef(value: ChangeDetectorRef) {
unimplemented(); // TODO: https://github.com/Microsoft/TypeScript/issues/12
}
}
export class ViewRef_ extends ViewRef {
private _changeDetectorRef: ChangeDetectorRef = null;
/**
* @internal
*/
constructor(public _view: viewModule.AppView) {}
constructor(public _view: viewModule.AppView) { super(); }
/**
* @internal
*
* Return `RenderViewRef`
*/
get render(): RenderViewRef { return this._view.render; }
/**
* @internal
*
* Return `RenderFragmentRef`
*/
get renderFragment(): RenderFragmentRef { return this._view.renderFragment; }
/**
* @internal
*
* Return `ChangeDetectorRef`
*/
get changeDetectorRef(): ChangeDetectorRef {
@ -116,13 +120,7 @@ export class ViewRef implements HostViewRef {
}
return this._changeDetectorRef;
}
set changeDetectorRef(value: ChangeDetectorRef) {
throw "readonly"; // TODO: https://github.com/Microsoft/TypeScript/issues/12
}
/**
* Sets `value` of local variable called `variableName` in this View.
*/
setLocal(variableName: string, value: any): void { this._view.setLocal(variableName, value); }
}
@ -165,9 +163,8 @@ export class ViewRef implements HostViewRef {
*
* Notice that the original template is broken down into two separate ProtoViews.
*/
export class ProtoViewRef {
/**
* @internal
*/
constructor(public _protoView: viewModule.AppProtoView) {}
export abstract class ProtoViewRef {}
export class ProtoViewRef_ extends ProtoViewRef {
constructor(public _protoView: viewModule.AppProtoView) { super(); }
}

View File

@ -115,7 +115,7 @@ export class ViewMetadata {
* }
* ```
*/
directives: Array<Type | any[]>;
directives: Array<Type | Function | any[]>;
pipes: Array<Type | any[]>;

View File

@ -2,8 +2,9 @@ import {Type} from 'angular2/src/core/facade/lang';
import {ResolvedFactory, resolveBinding} from 'angular2/src/core/di/binding';
import {Key, ResolvedBinding, Binding} from 'angular2/src/core/di';
import {PipeMetadata} from '../metadata/directives';
import {ResolvedBinding_} from "../di/binding";
export class PipeBinding extends ResolvedBinding {
export class PipeBinding extends ResolvedBinding_ {
constructor(public name: string, public pure: boolean, key: Key,
resolvedFactories: ResolvedFactory[], multiBinding: boolean) {
super(key, resolvedFactories, multiBinding);

View File

@ -3,6 +3,7 @@ import {BaseException, WrappedException} from 'angular2/src/core/facade/exceptio
import {ListWrapper} from 'angular2/src/core/facade/collection';
import {GetterFn, SetterFn, MethodFn} from './types';
import {PlatformReflectionCapabilities} from 'platform_reflection_capabilities';
import {ConcreteType} from "../facade/lang";
export class ReflectionCapabilities implements PlatformReflectionCapabilities {
private _reflect: any;
@ -11,7 +12,7 @@ export class ReflectionCapabilities implements PlatformReflectionCapabilities {
isReflectionEnabled(): boolean { return true; }
factory(t: Type): Function {
factory(t: ConcreteType): Function {
switch (t.length) {
case 0:
return () => new t();

View File

@ -13,12 +13,10 @@ import {Map} from 'angular2/src/core/facade/collection';
*
* <!-- TODO: this is created by Renderer#createProtoView in the new compiler -->
*/
// TODO(i): refactor this to an interface
export class RenderProtoViewRef {
/**
* @internal
*/
constructor() {}
export abstract class RenderProtoViewRef {}
export class RenderProtoViewRef_ extends RenderProtoViewRef {
constructor() { super(); }
}
@ -152,6 +150,7 @@ export interface RenderElementRef {
* Reference to the Render View that contains this Element.
*/
renderView: RenderViewRef;
/**
* Index of the Element (in the depth-first order) inside the Render View.
*
@ -173,17 +172,7 @@ export interface RenderElementRef {
*
* The default Renderer implementation is {@link DomRenderer}. Also see {@link WebWorkerRenderer}.
*/
export class Renderer {
/**
* @internal
*
* Private constructor is required so that this class gets converted into an interface in our
* public api.
*
* We implement this a class so that we have a DI token available for binding.
*/
constructor(){};
export abstract class Renderer {
/**
* Registers a component template represented as arrays of {@link RenderTemplateCmd}s and styles
* with the Renderer.
@ -191,13 +180,13 @@ export class Renderer {
* Once a template is registered it can be referenced via {@link RenderBeginComponentCmd} when
* {@link #createProtoView creating Render ProtoView}.
*/
registerComponentTemplate(templateId: number, commands: RenderTemplateCmd[], styles: string[],
nativeShadow: boolean) {}
abstract registerComponentTemplate(templateId: number, commands: RenderTemplateCmd[],
styles: string[], nativeShadow: boolean);
/**
* Creates a {@link RenderProtoViewRef} from an array of {@link RenderTemplateCmd}`s.
*/
createProtoView(cmds: RenderTemplateCmd[]): RenderProtoViewRef { return null; }
abstract createProtoView(cmds: RenderTemplateCmd[]): RenderProtoViewRef;
/**
* Creates a Root Host View based on the provided `hostProtoViewRef`.
@ -211,10 +200,8 @@ export class Renderer {
*
* Returns an instance of {@link RenderViewWithFragments}, representing the Render View.
*/
createRootHostView(hostProtoViewRef: RenderProtoViewRef, fragmentCount: number,
hostElementSelector: string): RenderViewWithFragments {
return null;
}
abstract createRootHostView(hostProtoViewRef: RenderProtoViewRef, fragmentCount: number,
hostElementSelector: string): RenderViewWithFragments;
/**
* Creates a Render View based on the provided `protoViewRef`.
@ -225,9 +212,8 @@ export class Renderer {
*
* Returns an instance of {@link RenderViewWithFragments}, representing the Render View.
*/
createView(protoViewRef: RenderProtoViewRef, fragmentCount: number): RenderViewWithFragments {
return null;
}
abstract createView(protoViewRef: RenderProtoViewRef, fragmentCount: number):
RenderViewWithFragments;
/**
* Destroys a Render View specified via `viewRef`.
@ -239,18 +225,18 @@ export class Renderer {
* future operations. If the Renderer created any renderer-specific objects for this View, these
* objects should now be destroyed to prevent memory leaks.
*/
destroyView(viewRef: RenderViewRef) {}
abstract destroyView(viewRef: RenderViewRef);
/**
* Attaches the Nodes of a Render Fragment after the last Node of `previousFragmentRef`.
*/
attachFragmentAfterFragment(previousFragmentRef: RenderFragmentRef,
fragmentRef: RenderFragmentRef) {}
abstract attachFragmentAfterFragment(previousFragmentRef: RenderFragmentRef,
fragmentRef: RenderFragmentRef);
/**
* Attaches the Nodes of the Render Fragment after an Element.
*/
attachFragmentAfterElement(elementRef: RenderElementRef, fragmentRef: RenderFragmentRef) {}
abstract attachFragmentAfterElement(elementRef: RenderElementRef, fragmentRef: RenderFragmentRef);
/**
* Detaches the Nodes of a Render Fragment from their parent.
@ -258,7 +244,7 @@ export class Renderer {
* This operations should be called only on a View that has been already
* {@link #dehydrateView dehydrated}.
*/
detachFragment(fragmentRef: RenderFragmentRef) {}
abstract detachFragment(fragmentRef: RenderFragmentRef);
/**
* Notifies a custom Renderer to initialize a Render View.
@ -266,7 +252,7 @@ export class Renderer {
* This method is called by Angular after a Render View has been created, or when a previously
* dehydrated Render View is about to be reused.
*/
hydrateView(viewRef: RenderViewRef) {}
abstract hydrateView(viewRef: RenderViewRef);
/**
* Notifies a custom Renderer that a Render View is no longer active.
@ -274,7 +260,7 @@ export class Renderer {
* This method is called by Angular before a Render View will be destroyed, or when a hydrated
* Render View is about to be put into a pool for future reuse.
*/
dehydrateView(viewRef: RenderViewRef) {}
abstract dehydrateView(viewRef: RenderViewRef);
/**
* Returns the underlying native element at the specified `location`, or `null` if direct access
@ -293,38 +279,39 @@ export class Renderer {
* </p>
* </div>
*/
getNativeElementSync(location: RenderElementRef): any { return null; }
abstract getNativeElementSync(location: RenderElementRef): any;
/**
* Sets a property on the Element specified via `location`.
*/
setElementProperty(location: RenderElementRef, propertyName: string, propertyValue: any) {}
abstract setElementProperty(location: RenderElementRef, propertyName: string, propertyValue: any);
/**
* Sets an attribute on the Element specified via `location`.
*
* If `attributeValue` is `null`, the attribute is removed.
*/
setElementAttribute(location: RenderElementRef, attributeName: string, attributeValue: string) {}
abstract setElementAttribute(location: RenderElementRef, attributeName: string,
attributeValue: string);
/**
* Sets a (CSS) class on the Element specified via `location`.
*
* `isAdd` specifies if the class should be added or removed.
*/
setElementClass(location: RenderElementRef, className: string, isAdd: boolean) {}
abstract setElementClass(location: RenderElementRef, className: string, isAdd: boolean);
/**
* Sets a (CSS) inline style on the Element specified via `location`.
*
* If `styleValue` is `null`, the style is removed.
*/
setElementStyle(location: RenderElementRef, styleName: string, styleValue: string) {}
abstract setElementStyle(location: RenderElementRef, styleName: string, styleValue: string);
/**
* Calls a method on the Element specified via `location`.
*/
invokeElementMethod(location: RenderElementRef, methodName: string, args: any[]) {}
abstract invokeElementMethod(location: RenderElementRef, methodName: string, args: any[]);
/**
* Sets the value of an interpolated TextNode at the specified index to the `text` value.
@ -332,7 +319,7 @@ export class Renderer {
* `textNodeIndex` is the depth-first index of the Node among interpolated Nodes in the Render
* View.
*/
setText(viewRef: RenderViewRef, textNodeIndex: number, text: string) {}
abstract setText(viewRef: RenderViewRef, textNodeIndex: number, text: string);
/**
* Sets a dispatcher to relay all events triggered in the given Render View.
@ -340,10 +327,9 @@ export class Renderer {
* Each Render View can have only one Event Dispatcher, if this method is called multiple times,
* the last provided dispatcher will be used.
*/
setEventDispatcher(viewRef: RenderViewRef, dispatcher: RenderEventDispatcher) {}
abstract setEventDispatcher(viewRef: RenderViewRef, dispatcher: RenderEventDispatcher);
}
/**
* A dispatcher that relays all events that occur in a Render View.
*

View File

@ -32,74 +32,23 @@ import {createRenderView, NodeFactory} from '../view_factory';
import {DefaultRenderView, DefaultRenderFragmentRef, DefaultProtoViewRef} from '../view';
import {camelCaseToDashCase} from './util';
@Injectable()
export class DomRenderer implements Renderer, NodeFactory<Node> {
private _componentCmds: Map<number, RenderTemplateCmd[]> = new Map<number, RenderTemplateCmd[]>();
private _nativeShadowStyles: Map<number, string[]> = new Map<number, string[]>();
private _document;
export abstract class DomRenderer extends Renderer implements NodeFactory<Node> {
abstract registerComponentTemplate(templateId: number, commands: RenderTemplateCmd[],
styles: string[], nativeShadow: boolean);
/**
* @internal
*/
constructor(private _eventManager: EventManager,
private _domSharedStylesHost: DomSharedStylesHost, private _animate: AnimationBuilder,
@Inject(DOCUMENT) document) {
this._document = document;
}
registerComponentTemplate(templateId: number, commands: RenderTemplateCmd[], styles: string[],
nativeShadow: boolean) {
this._componentCmds.set(templateId, commands);
if (nativeShadow) {
this._nativeShadowStyles.set(templateId, styles);
} else {
this._domSharedStylesHost.addStyles(styles);
}
}
resolveComponentTemplate(templateId: number): RenderTemplateCmd[] {
return this._componentCmds.get(templateId);
}
abstract resolveComponentTemplate(templateId: number): RenderTemplateCmd[];
createProtoView(cmds: RenderTemplateCmd[]): RenderProtoViewRef {
return new DefaultProtoViewRef(cmds);
}
_createRootHostViewScope: WtfScopeFn = wtfCreateScope('DomRenderer#createRootHostView()');
createRootHostView(hostProtoViewRef: RenderProtoViewRef, fragmentCount: number,
hostElementSelector: string): RenderViewWithFragments {
var s = this._createRootHostViewScope();
var element = DOM.querySelector(this._document, hostElementSelector);
if (isBlank(element)) {
wtfLeave(s);
throw new BaseException(`The selector "${hostElementSelector}" did not match any elements`);
}
return wtfLeave(s, this._createView(hostProtoViewRef, element));
}
abstract createRootHostView(hostProtoViewRef: RenderProtoViewRef, fragmentCount: number,
hostElementSelector: string): RenderViewWithFragments;
_createViewScope = wtfCreateScope('DomRenderer#createView()');
createView(protoViewRef: RenderProtoViewRef, fragmentCount: number): RenderViewWithFragments {
var s = this._createViewScope();
return wtfLeave(s, this._createView(protoViewRef, null));
}
abstract createView(protoViewRef: RenderProtoViewRef, fragmentCount: number):
RenderViewWithFragments;
private _createView(protoViewRef: RenderProtoViewRef,
inplaceElement: HTMLElement): RenderViewWithFragments {
var view = createRenderView((<DefaultProtoViewRef>protoViewRef).cmds, inplaceElement, this);
var sdRoots = view.nativeShadowRoots;
for (var i = 0; i < sdRoots.length; i++) {
this._domSharedStylesHost.addHost(sdRoots[i]);
}
return new RenderViewWithFragments(view, view.fragments);
}
destroyView(viewRef: RenderViewRef) {
var view = <DefaultRenderView<Node>>viewRef;
var sdRoots = view.nativeShadowRoots;
for (var i = 0; i < sdRoots.length; i++) {
this._domSharedStylesHost.removeHost(sdRoots[i]);
}
}
abstract destroyView(viewRef: RenderViewRef);
getNativeElementSync(location: RenderElementRef): any {
return resolveInternalDomView(location.renderView).boundElements[location.boundElementIndex];
@ -130,35 +79,14 @@ export class DomRenderer implements Renderer, NodeFactory<Node> {
* Performs animations if necessary
* @param node
*/
animateNodeEnter(node: Node) {
if (DOM.isElementNode(node) && DOM.hasClass(node, 'ng-animate')) {
DOM.addClass(node, 'ng-enter');
this._animate.css()
.addAnimationClass('ng-enter-active')
.start(<HTMLElement>node)
.onComplete(() => { DOM.removeClass(node, 'ng-enter'); });
}
}
abstract animateNodeEnter(node: Node);
/**
* If animations are necessary, performs animations then removes the element; otherwise, it just
* removes the element.
* @param node
*/
animateNodeLeave(node: Node) {
if (DOM.isElementNode(node) && DOM.hasClass(node, 'ng-animate')) {
DOM.addClass(node, 'ng-leave');
this._animate.css()
.addAnimationClass('ng-leave-active')
.start(<HTMLElement>node)
.onComplete(() => {
DOM.removeClass(node, 'ng-leave');
DOM.remove(node);
});
} else {
DOM.remove(node);
}
}
abstract animateNodeLeave(node: Node);
attachFragmentAfterElement(elementRef: RenderElementRef, fragmentRef: RenderFragmentRef) {
var parentView = resolveInternalDomView(elementRef.renderView);
@ -168,15 +96,7 @@ export class DomRenderer implements Renderer, NodeFactory<Node> {
this.animateNodesEnter(nodes);
}
_detachFragmentScope = wtfCreateScope('DomRenderer#detachFragment()');
detachFragment(fragmentRef: RenderFragmentRef) {
var s = this._detachFragmentScope();
var fragmentNodes = resolveInternalDomFragment(fragmentRef);
for (var i = 0; i < fragmentNodes.length; i++) {
this.animateNodeLeave(fragmentNodes[i]);
}
wtfLeave(s);
}
abstract detachFragment(fragmentRef: RenderFragmentRef);
hydrateView(viewRef: RenderViewRef) { resolveInternalDomView(viewRef).hydrate(); }
@ -185,38 +105,13 @@ export class DomRenderer implements Renderer, NodeFactory<Node> {
createTemplateAnchor(attrNameAndValues: string[]): Node {
return this.createElement('script', attrNameAndValues);
}
createElement(name: string, attrNameAndValues: string[]): Node {
var el = DOM.createElement(name);
this._setAttributes(el, attrNameAndValues);
return el;
}
mergeElement(existing: Node, attrNameAndValues: string[]) {
DOM.clearNodes(existing);
this._setAttributes(existing, attrNameAndValues);
}
private _setAttributes(node: Node, attrNameAndValues: string[]) {
for (var attrIdx = 0; attrIdx < attrNameAndValues.length; attrIdx += 2) {
DOM.setAttribute(node, attrNameAndValues[attrIdx], attrNameAndValues[attrIdx + 1]);
}
}
createShadowRoot(host: Node, templateId: number): Node {
var sr = DOM.createShadowRoot(host);
var styles = this._nativeShadowStyles.get(templateId);
for (var i = 0; i < styles.length; i++) {
DOM.appendChild(sr, DOM.createStyleElement(styles[i]));
}
return sr;
}
abstract createElement(name: string, attrNameAndValues: string[]): Node;
abstract mergeElement(existing: Node, attrNameAndValues: string[]);
abstract createShadowRoot(host: Node, templateId: number): Node;
createText(value: string): Node { return DOM.createTextNode(isPresent(value) ? value : ''); }
appendChild(parent: Node, child: Node) { DOM.appendChild(parent, child); }
on(element: Node, eventName: string, callback: Function) {
this._eventManager.addEventListener(<HTMLElement>element, eventName,
decoratePreventDefault(callback));
}
globalOn(target: string, eventName: string, callback: Function): Function {
return this._eventManager.addGlobalEventListener(target, eventName,
decoratePreventDefault(callback));
}
abstract on(element: Node, eventName: string, callback: Function);
abstract globalOn(target: string, eventName: string, callback: Function): Function;
setElementProperty(location: RenderElementRef, propertyName: string, propertyValue: any): void {
var view = resolveInternalDomView(location.renderView);
@ -273,6 +168,135 @@ export class DomRenderer implements Renderer, NodeFactory<Node> {
}
}
@Injectable()
export class DomRenderer_ extends DomRenderer {
private _componentCmds: Map<number, RenderTemplateCmd[]> = new Map<number, RenderTemplateCmd[]>();
private _nativeShadowStyles: Map<number, string[]> = new Map<number, string[]>();
private _document;
constructor(private _eventManager: EventManager,
private _domSharedStylesHost: DomSharedStylesHost, private _animate: AnimationBuilder,
@Inject(DOCUMENT) document) {
super();
this._document = document;
}
registerComponentTemplate(templateId: number, commands: RenderTemplateCmd[], styles: string[],
nativeShadow: boolean) {
this._componentCmds.set(templateId, commands);
if (nativeShadow) {
this._nativeShadowStyles.set(templateId, styles);
} else {
this._domSharedStylesHost.addStyles(styles);
}
}
resolveComponentTemplate(templateId: number): RenderTemplateCmd[] {
return this._componentCmds.get(templateId);
}
_createRootHostViewScope: WtfScopeFn = wtfCreateScope('DomRenderer#createRootHostView()');
createRootHostView(hostProtoViewRef: RenderProtoViewRef, fragmentCount: number,
hostElementSelector: string): RenderViewWithFragments {
var s = this._createRootHostViewScope();
var element = DOM.querySelector(this._document, hostElementSelector);
if (isBlank(element)) {
wtfLeave(s);
throw new BaseException(`The selector "${hostElementSelector}" did not match any elements`);
}
return wtfLeave(s, this._createView(hostProtoViewRef, element));
}
_createViewScope = wtfCreateScope('DomRenderer#createView()');
createView(protoViewRef: RenderProtoViewRef, fragmentCount: number): RenderViewWithFragments {
var s = this._createViewScope();
return wtfLeave(s, this._createView(protoViewRef, null));
}
private _createView(protoViewRef: RenderProtoViewRef,
inplaceElement: HTMLElement): RenderViewWithFragments {
var view = createRenderView((<DefaultProtoViewRef>protoViewRef).cmds, inplaceElement, this);
var sdRoots = view.nativeShadowRoots;
for (var i = 0; i < sdRoots.length; i++) {
this._domSharedStylesHost.addHost(sdRoots[i]);
}
return new RenderViewWithFragments(view, view.fragments);
}
destroyView(viewRef: RenderViewRef) {
var view = <DefaultRenderView<Node>>viewRef;
var sdRoots = view.nativeShadowRoots;
for (var i = 0; i < sdRoots.length; i++) {
this._domSharedStylesHost.removeHost(sdRoots[i]);
}
}
animateNodeEnter(node: Node) {
if (DOM.isElementNode(node) && DOM.hasClass(node, 'ng-animate')) {
DOM.addClass(node, 'ng-enter');
this._animate.css()
.addAnimationClass('ng-enter-active')
.start(<HTMLElement>node)
.onComplete(() => { DOM.removeClass(node, 'ng-enter'); });
}
}
animateNodeLeave(node: Node) {
if (DOM.isElementNode(node) && DOM.hasClass(node, 'ng-animate')) {
DOM.addClass(node, 'ng-leave');
this._animate.css()
.addAnimationClass('ng-leave-active')
.start(<HTMLElement>node)
.onComplete(() => {
DOM.removeClass(node, 'ng-leave');
DOM.remove(node);
});
} else {
DOM.remove(node);
}
}
_detachFragmentScope = wtfCreateScope('DomRenderer#detachFragment()');
detachFragment(fragmentRef: RenderFragmentRef) {
var s = this._detachFragmentScope();
var fragmentNodes = resolveInternalDomFragment(fragmentRef);
for (var i = 0; i < fragmentNodes.length; i++) {
this.animateNodeLeave(fragmentNodes[i]);
}
wtfLeave(s);
}
createElement(name: string, attrNameAndValues: string[]): Node {
var el = DOM.createElement(name);
this._setAttributes(el, attrNameAndValues);
return el;
}
mergeElement(existing: Node, attrNameAndValues: string[]) {
DOM.clearNodes(existing);
this._setAttributes(existing, attrNameAndValues);
}
private _setAttributes(node: Node, attrNameAndValues: string[]) {
for (var attrIdx = 0; attrIdx < attrNameAndValues.length; attrIdx += 2) {
DOM.setAttribute(node, attrNameAndValues[attrIdx], attrNameAndValues[attrIdx + 1]);
}
}
createShadowRoot(host: Node, templateId: number): Node {
var sr = DOM.createShadowRoot(host);
var styles = this._nativeShadowStyles.get(templateId);
for (var i = 0; i < styles.length; i++) {
DOM.appendChild(sr, DOM.createStyleElement(styles[i]));
}
return sr;
}
on(element: Node, eventName: string, callback: Function) {
this._eventManager.addEventListener(<HTMLElement>element, eventName,
decoratePreventDefault(callback));
}
globalOn(target: string, eventName: string, callback: Function): Function {
return this._eventManager.addGlobalEventListener(target, eventName,
decoratePreventDefault(callback));
}
}
function resolveInternalDomView(viewRef: RenderViewRef): DefaultRenderView<Node> {
return <DefaultRenderView<Node>>viewRef;
}

View File

@ -5,6 +5,7 @@ import {CONST, CONST_EXPR} from 'angular2/src/core/facade/lang';
import {BaseException, WrappedException} from 'angular2/src/core/facade/exceptions';
import {NgZone} from '../zone/ng_zone';
import {PromiseWrapper} from 'angular2/src/core/facade/async';
import {NgZone_} from "../zone/ng_zone";
/**
@ -21,11 +22,12 @@ export class Testability {
constructor(public _ngZone: NgZone) { this._watchAngularEvents(_ngZone); }
_watchAngularEvents(_ngZone: NgZone): void {
_ngZone.overrideOnTurnStart(() => { this._isAngularEventPending = true; });
_ngZone.overrideOnEventDone(() => {
this._isAngularEventPending = false;
this._runCallbacksIfReady();
}, true);
(<NgZone_>_ngZone).overrideOnTurnStart(() => { this._isAngularEventPending = true; });
(<NgZone_>_ngZone)
.overrideOnEventDone(() => {
this._isAngularEventPending = false;
this._runCallbacksIfReady();
}, true);
}
increasePendingRequestCount(): number {

View File

@ -1,4 +1,5 @@
import {global, Type, isFunction, stringify} from 'angular2/src/core/facade/lang';
import {ConcreteType} from "../facade/lang";
/**
* Declares the interface to be used with {@link Class}.
@ -71,7 +72,7 @@ export interface TypeDecorator {
/**
* Generate a class from the definition and annotate it with {@link TypeDecorator#annotations}.
*/
Class(obj: ClassDefinition): Type;
Class(obj: ClassDefinition): ConcreteType;
}
function extractAnnotation(annotation: any): any {
@ -205,7 +206,7 @@ function applyParams(fnOrArray: (Function | any[]), key: string): Function {
* });
* ```
*/
export function Class(clsDef: ClassDefinition): Type {
export function Class(clsDef: ClassDefinition): ConcreteType {
var constructor = applyParams(
clsDef.hasOwnProperty('constructor') ? clsDef.constructor : undefined, 'constructor');
var proto = constructor.prototype;
@ -228,7 +229,7 @@ export function Class(clsDef: ClassDefinition): Type {
Reflect.defineMetadata('annotations', this.annotations, constructor);
}
return <Type>constructor;
return <ConcreteType>constructor;
}
var Reflect = global.Reflect;

View File

@ -77,7 +77,35 @@ export interface NgZoneZone extends Zone { _innerZone: boolean; }
* }
* ```
*/
export class NgZone {
export abstract class NgZone {
/**
* Executes the `fn` function synchronously within the Angular zone and returns value returned by
* the function.
*
* Running functions via `run` allows you to reenter Angular zone from a task that was executed
* outside of the Angular zone (typically started via {@link #runOutsideAngular}).
*
* Any future tasks or microtasks scheduled from within this function will continue executing from
* within the Angular zone.
*/
abstract run(fn: () => any): any;
/**
* Executes the `fn` function synchronously in Angular's parent zone and returns value returned by
* the function.
*
* Running functions via `runOutsideAngular` allows you to escape Angular's zone and do work that
* doesn't trigger Angular change-detection or is subject to Angular's error handling.
*
* Any future tasks or microtasks scheduled from within this function will continue executing from
* outside of the Angular zone.
*
* Use {@link #run} to reenter the Angular zone and do work that updates the application model.
*/
abstract runOutsideAngular(fn: () => any): any;
}
export class NgZone_ extends NgZone {
_runScope: WtfScopeFn = wtfCreateScope(`NgZone#run()`);
_microtaskScope: WtfScopeFn = wtfCreateScope(`NgZone#microtask()`);
@ -111,11 +139,11 @@ export class NgZone {
_pendingTimeouts: number[] = [];
/**
* @internal
* @param {bool} enableLongStackTrace whether to enable long stack trace. They should only be
* enabled in development mode as they significantly impact perf.
*/
constructor({enableLongStackTrace}) {
super();
this._onTurnStart = null;
this._onTurnDone = null;
this._onEventDone = null;
@ -136,8 +164,6 @@ export class NgZone {
}
/**
* @internal <!-- TODO: refactor to make TS private -->
*
* Sets the zone hook that is called just before a browser task that is handled by Angular
* executes.
*
@ -150,8 +176,6 @@ export class NgZone {
}
/**
* @internal <!-- TODO: refactor to make TS private -->
*
* Sets the zone hook that is called immediately after Angular zone is done processing the current
* task and any microtasks scheduled from that task.
*
@ -166,8 +190,6 @@ export class NgZone {
}
/**
* @internal <!-- TODO: refactor to make TS private -->
*
* Sets the zone hook that is called immediately after the `onTurnDone` callback is called and any
* microstasks scheduled from within that callback are drained.
*
@ -192,8 +214,6 @@ export class NgZone {
}
/**
* @internal <!-- TODO: refactor to make TS private -->
*
* Sets the zone hook that is called when an error is thrown in the Angular zone.
*
* Setting the hook overrides any previously set hook.
@ -202,16 +222,6 @@ export class NgZone {
this._onErrorHandler = normalizeBlank(errorHandler);
}
/**
* Executes the `fn` function synchronously within the Angular zone and returns value returned by
* the function.
*
* Running functions via `run` allows you to reenter Angular zone from a task that was executed
* outside of the Angular zone (typically started via {@link #runOutsideAngular}).
*
* Any future tasks or microtasks scheduled from within this function will continue executing from
* within the Angular zone.
*/
run(fn: () => any): any {
if (this._disabled) {
return fn();
@ -225,18 +235,6 @@ export class NgZone {
}
}
/**
* Executes the `fn` function synchronously in Angular's parent zone and returns value returned by
* the function.
*
* Running functions via `runOutsideAngular` allows you to escape Angular's zone and do work that
* doesn't trigger Angular change-detection or is subject to Angular's error handling.
*
* Any future tasks or microtasks scheduled from within this function will continue executing from
* outside of the Angular zone.
*
* Use {@link #run} to reenter the Angular zone and do work that updates the application model.
*/
runOutsideAngular(fn: () => any): any {
if (this._disabled) {
return fn();

View File

@ -11,20 +11,22 @@ import {StringWrapper, isPresent} from 'angular2/src/core/facade/lang';
// todo(robwormald): temporary until https://github.com/angular/angular/issues/4390 decided
var Rx = require('@reactivex/rxjs/dist/cjs/Rx');
var {Observable} = Rx;
export class JSONPConnection implements Connection {
export abstract class JSONPConnection implements Connection {
readyState: ReadyStates;
request: Request;
response: any;
abstract finished(data?: any): void;
}
export class JSONPConnection_ extends JSONPConnection {
private _id: string;
private _script: Element;
private _responseData: any;
private _finished: boolean = false;
/**
* @internal
*/
constructor(req: Request, private _dom: BrowserJsonp,
private baseResponseOptions?: ResponseOptions) {
super();
if (req.method !== RequestMethods.Get) {
throw makeTypeError("JSONP requests must use GET request method.");
}
@ -100,13 +102,15 @@ export class JSONPConnection implements Connection {
}
}
export abstract class JSONPBackend extends ConnectionBackend {}
@Injectable()
export class JSONPBackend implements ConnectionBackend {
/**
* @internal
*/
constructor(private _browserJSONP: BrowserJsonp, private _baseResponseOptions: ResponseOptions) {}
export class JSONPBackend_ extends JSONPBackend {
constructor(private _browserJSONP: BrowserJsonp, private _baseResponseOptions: ResponseOptions) {
super();
}
createConnection(request: Request): JSONPConnection {
return new JSONPConnection(request, this._browserJSONP, this._baseResponseOptions);
return new JSONPConnection_(request, this._browserJSONP, this._baseResponseOptions);
}
}

View File

@ -11,10 +11,7 @@ import {URLSearchParams} from './url_search_params';
* The primary purpose of a `ConnectionBackend` is to create new connections to fulfill a given
* {@link Request}.
*/
export abstract class ConnectionBackend {
constructor() {}
abstract createConnection(request: any): Connection;
}
export abstract class ConnectionBackend { abstract createConnection(request: any): Connection; }
/**
* Abstract class from which real connections are derived.

View File

@ -1,6 +1,6 @@
import {NgZone} from 'angular2/src/core/zone/ng_zone';
import {NgZone_} from 'angular2/src/core/zone/ng_zone';
export class MockNgZone extends NgZone {
export class MockNgZone extends NgZone_ {
_onEventDone: () => void;
constructor() { super({enableLongStackTrace: false}); }

View File

@ -1,4 +1,5 @@
import {Map, MapWrapper, StringMapWrapper, ListWrapper} from 'angular2/src/core/facade/collection';
import {unimplemented} from 'angular2/src/core/facade/exceptions';
import {isPresent, isBlank, normalizeBlank, Type} from 'angular2/src/core/facade/lang';
import {Promise} from 'angular2/src/core/facade/async';
@ -140,42 +141,55 @@ function stringifyAux(instruction: Instruction): string {
*
* You should not modify this object. It should be treated as immutable.
*/
export class ComponentInstruction {
export abstract class ComponentInstruction {
reuse: boolean = false;
/**
* @internal
*/
constructor(public urlPath: string, public urlParams: string[],
private _recognizer: PathRecognizer, public params: {[key: string]: any} = null) {}
public urlPath: string;
public urlParams: string[];
public params: {[key: string]: any};
/**
* Returns the component type of the represented route, or `null` if this instruction
* hasn't been resolved.
*/
get componentType() { return this._recognizer.handler.componentType; }
get componentType() { return unimplemented(); };
/**
* Returns a promise that will resolve to component type of the represented route.
* If this instruction references an {@link AsyncRoute}, the `loader` function of that route
* will run.
*/
resolveComponentType(): Promise<Type> { return this._recognizer.handler.resolveComponentType(); }
abstract resolveComponentType(): Promise<Type>;
/**
* Returns the specificity of the route associated with this `Instruction`.
*/
get specificity() { return this._recognizer.specificity; }
get specificity() { return unimplemented(); };
/**
* Returns `true` if the component type of this instruction has no child {@link RouteConfig},
* or `false` if it does.
*/
get terminal() { return this._recognizer.terminal; }
get terminal() { return unimplemented(); };
/**
* Returns the route data of the given route that was specified in the {@link RouteDefinition},
* or `null` if no route data was specified.
*/
abstract routeData(): Object;
}
export class ComponentInstruction_ extends ComponentInstruction {
constructor(urlPath: string, urlParams: string[], private _recognizer: PathRecognizer,
params: {[key: string]: any} = null) {
super();
this.urlPath = urlPath;
this.urlParams = urlParams;
this.params = params;
}
get componentType() { return this._recognizer.handler.componentType; }
resolveComponentType(): Promise<Type> { return this._recognizer.handler.resolveComponentType(); }
get specificity() { return this._recognizer.specificity; }
get terminal() { return this._recognizer.terminal; }
routeData(): Object { return this._recognizer.handler.data; }
}

View File

@ -13,6 +13,7 @@ import {Map, MapWrapper, StringMapWrapper} from 'angular2/src/core/facade/collec
import {RouteHandler} from './route_handler';
import {Url, RootUrl, serializeParams} from './url_parser';
import {ComponentInstruction} from './instruction';
import {ComponentInstruction_} from "./instruction";
class TouchMap {
map: {[key: string]: string} = {};
@ -297,7 +298,7 @@ export class PathRecognizer {
if (this._cache.has(hashKey)) {
return this._cache.get(hashKey);
}
var instruction = new ComponentInstruction(urlPath, urlParams, _recognizer, params);
var instruction = new ComponentInstruction_(urlPath, urlParams, _recognizer, params);
this._cache.set(hashKey, instruction);
return instruction;

View File

@ -12,6 +12,7 @@ import {ComponentInstruction, RouteParams} from './instruction';
import {ROUTE_DATA} from './route_data';
import * as hookMod from './lifecycle_annotations';
import {hasLifecycleHook} from './route_lifecycle_reflector';
import {Type} from "../core/facade/lang";
let _resolveToTrue = PromiseWrapper.resolve(true);
@ -24,18 +25,59 @@ let _resolveToTrue = PromiseWrapper.resolve(true);
* <router-outlet></router-outlet>
* ```
*/
@Directive({selector: 'router-outlet'})
export class RouterOutlet {
export abstract class RouterOutlet {
name: string = null;
/**
* Called by the Router to instantiate a new component during the commit phase of a navigation.
* This method in turn is responsible for calling the `onActivate` hook of its child.
*/
abstract activate(nextInstruction: ComponentInstruction): Promise<any>;
/**
* Called by the {@link Router} during the commit phase of a navigation when an outlet
* reuses a component between different routes.
* This method in turn is responsible for calling the `onReuse` hook of its child.
*/
abstract reuse(nextInstruction: ComponentInstruction): Promise<any>;
/**
* Called by the {@link Router} when an outlet reuses a component across navigations.
* This method in turn is responsible for calling the `onReuse` hook of its child.
*/
abstract deactivate(nextInstruction: ComponentInstruction): Promise<any>;
/**
* Called by the {@link Router} during recognition phase of a navigation.
*
* If this resolves to `false`, the given navigation is cancelled.
*
* This method delegates to the child component's `canDeactivate` hook if it exists,
* and otherwise resolves to true.
*/
abstract canDeactivate(nextInstruction: ComponentInstruction): Promise<boolean>;
/**
* Called by the {@link Router} during recognition phase of a navigation.
*
* If the new child component has a different Type than the existing child component,
* this will resolve to `false`. You can't reuse an old component when the new component
* is of a different Type.
*
* Otherwise, this method delegates to the child component's `canReuse` hook if it exists,
* or resolves to true if the hook is not present.
*/
abstract canReuse(nextInstruction: ComponentInstruction): Promise<boolean>;
}
@Directive({selector: 'router-outlet'})
export class RouterOutlet_ extends RouterOutlet {
private _componentRef: ComponentRef = null;
private _currentInstruction: ComponentInstruction = null;
/**
* @internal
*/
constructor(private _elementRef: ElementRef, private _loader: DynamicComponentLoader,
private _parentRouter: routerMod.Router, @Attribute('name') nameAttr: string) {
super();
if (isPresent(nameAttr)) {
this.name = nameAttr;
this._parentRouter.registerAuxOutlet(this);
@ -44,10 +86,6 @@ export class RouterOutlet {
}
}
/**
* Called by the Router to instantiate a new component during the commit phase of a navigation.
* This method in turn is responsible for calling the `onActivate` hook of its child.
*/
activate(nextInstruction: ComponentInstruction): Promise<any> {
var previousInstruction = this._currentInstruction;
this._currentInstruction = nextInstruction;
@ -69,11 +107,6 @@ export class RouterOutlet {
});
}
/**
* Called by the {@link Router} during the commit phase of a navigation when an outlet
* reuses a component between different routes.
* This method in turn is responsible for calling the `onReuse` hook of its child.
*/
reuse(nextInstruction: ComponentInstruction): Promise<any> {
var previousInstruction = this._currentInstruction;
this._currentInstruction = nextInstruction;
@ -87,10 +120,6 @@ export class RouterOutlet {
true);
}
/**
* Called by the {@link Router} when an outlet reuses a component across navigations.
* This method in turn is responsible for calling the `onReuse` hook of its child.
*/
deactivate(nextInstruction: ComponentInstruction): Promise<any> {
var next = _resolveToTrue;
if (isPresent(this._componentRef) && isPresent(this._currentInstruction) &&
@ -106,14 +135,6 @@ export class RouterOutlet {
});
}
/**
* Called by the {@link Router} during recognition phase of a navigation.
*
* If this resolves to `false`, the given navigation is cancelled.
*
* This method delegates to the child component's `canDeactivate` hook if it exists,
* and otherwise resolves to true.
*/
canDeactivate(nextInstruction: ComponentInstruction): Promise<boolean> {
if (isBlank(this._currentInstruction)) {
return _resolveToTrue;
@ -125,16 +146,6 @@ export class RouterOutlet {
return _resolveToTrue;
}
/**
* Called by the {@link Router} during recognition phase of a navigation.
*
* If the new child component has a different Type than the existing child component,
* this will resolve to `false`. You can't reuse an old component when the new component
* is of a different Type.
*
* Otherwise, this method delegates to the child component's `canReuse` hook if it exists,
* or resolves to true if the hook is not present.
*/
canReuse(nextInstruction: ComponentInstruction): Promise<boolean> {
var result;

View File

@ -20,19 +20,22 @@ import {el} from './utils';
import {DOCUMENT} from 'angular2/src/core/render/render';
import {DOM} from 'angular2/src/core/dom/dom_adapter';
import {DebugElement} from 'angular2/src/core/debug/debug_element';
import {DebugElement, DebugElement_} from 'angular2/src/core/debug/debug_element';
export class RootTestComponent {
_componentRef: ComponentRef;
_componentParentView: AppView;
export abstract class RootTestComponent {
debugElement: DebugElement;
/**
* @internal
*/
constructor(componentRef: ComponentRef) {
this.debugElement = new DebugElement(internalView(<ViewRef>componentRef.hostView), 0);
abstract detectChanges(): void;
abstract destroy(): void;
}
export class RootTestComponent_ extends RootTestComponent {
_componentRef: ComponentRef;
_componentParentView: AppView;
constructor(componentRef: ComponentRef) {
super();
this.debugElement = new DebugElement_(internalView(<ViewRef>componentRef.hostView), 0);
this._componentParentView = internalView(<ViewRef>componentRef.hostView);
this._componentRef = componentRef;
}
@ -195,6 +198,6 @@ export class TestComponentBuilder {
return this._injector.get(DynamicComponentLoader)
.loadAsRoot(rootComponentType, `#${rootElId}`, this._injector)
.then((componentRef) => { return new RootTestComponent(componentRef); });
.then((componentRef) => { return new RootTestComponent_(componentRef); });
}
}

View File

@ -3,6 +3,7 @@ import {ComponentRef} from 'angular2/src/core/linker/dynamic_component_loader';
import {isPresent, NumberWrapper} from 'angular2/src/core/facade/lang';
import {performance, window} from 'angular2/src/core/facade/browser';
import {DOM} from 'angular2/src/core/dom/dom_adapter';
import {ComponentRef_} from "../core/linker/dynamic_component_loader";
/**
* Entry point for all Angular debug tools. This object corresponds to the `ng`
@ -21,7 +22,7 @@ export class AngularTools {
export class AngularProfiler {
lifeCycle: LifeCycle;
constructor(ref: ComponentRef) { this.lifeCycle = ref.injector.get(LifeCycle); }
constructor(ref: ComponentRef) { this.lifeCycle = (<ComponentRef_>ref).injector.get(LifeCycle); }
/**
* Exercises change detection in a loop and then prints the average amount of

View File

@ -14,30 +14,36 @@ import {Injectable} from "angular2/src/core/di";
import {Type, StringWrapper} from "angular2/src/core/facade/lang";
export {Type} from "angular2/src/core/facade/lang";
@Injectable()
export class ClientMessageBrokerFactory {
export abstract class ClientMessageBrokerFactory {
/**
* @internal
* Initializes the given channel and attaches a new {@link ClientMessageBroker} to it.
*/
constructor(private _messageBus: MessageBus, public _serializer: Serializer) {}
abstract createMessageBroker(channel: string, runInZone?: boolean): ClientMessageBroker;
}
@Injectable()
export class ClientMessageBrokerFactory_ extends ClientMessageBrokerFactory {
constructor(private _messageBus: MessageBus, public _serializer: Serializer) { super(); }
/**
* Initializes the given channel and attaches a new {@link ClientMessageBroker} to it.
*/
createMessageBroker(channel: string, runInZone: boolean = true): ClientMessageBroker {
this._messageBus.initChannel(channel, runInZone);
return new ClientMessageBroker(this._messageBus, this._serializer, channel);
return new ClientMessageBroker_(this._messageBus, this._serializer, channel);
}
}
export class ClientMessageBroker {
export abstract class ClientMessageBroker {
abstract runOnService(args: UiArguments, returnType: Type): Promise<any>;
}
export class ClientMessageBroker_ extends ClientMessageBroker {
private _pending: Map<string, PromiseCompleter<any>> = new Map<string, PromiseCompleter<any>>();
private _sink: EventEmitter;
/**
* @internal
*/
constructor(messageBus: MessageBus, public _serializer: Serializer, public channel) {
super();
this._sink = messageBus.to(channel);
var source = messageBus.from(channel);
ObservableWrapper.subscribe(source,

View File

@ -8,6 +8,7 @@ import {EventEmitter} from 'angular2/src/core/facade/async';
import {StringMapWrapper} from 'angular2/src/core/facade/collection';
import {Injectable} from "angular2/src/core/di";
import {NgZone} from 'angular2/src/core/zone/ng_zone';
import {NgZone_} from "../../core/zone/ng_zone";
/**
* A TypeScript implementation of {@link MessageBus} for communicating via JavaScript's
@ -41,7 +42,7 @@ export class PostMessageBusSink implements MessageBusSink {
attachToZone(zone: NgZone): void {
this._zone = zone;
this._zone.overrideOnEventDone(() => this._handleOnEventDone(), false);
(<NgZone_>this._zone).overrideOnEventDone(() => this._handleOnEventDone(), false);
}
initChannel(channel: string, runInZone: boolean = true): void {

View File

@ -10,36 +10,40 @@ import {
ObservableWrapper
} from 'angular2/src/core/facade/async';
@Injectable()
export class ServiceMessageBrokerFactory {
/**
* @internal
*/
constructor(private _messageBus: MessageBus, public _serializer: Serializer) {}
export abstract class ServiceMessageBrokerFactory {
/**
* Initializes the given channel and attaches a new {@link ServiceMessageBroker} to it.
*/
abstract createMessageBroker(channel: string, runInZone?: boolean): ServiceMessageBroker;
}
@Injectable()
export class ServiceMessageBrokerFactory_ extends ServiceMessageBrokerFactory {
constructor(private _messageBus: MessageBus, public _serializer: Serializer) { super(); }
createMessageBroker(channel: string, runInZone: boolean = true): ServiceMessageBroker {
this._messageBus.initChannel(channel, runInZone);
return new ServiceMessageBroker(this._messageBus, this._serializer, channel);
return new ServiceMessageBroker_(this._messageBus, this._serializer, channel);
}
}
export abstract class ServiceMessageBroker {
abstract registerMethod(methodName: string, signature: Type[], method: Function,
returnType?: Type): void;
}
/**
* Helper class for UIComponents that allows components to register methods.
* If a registered method message is received from the broker on the worker,
* the UIMessageBroker deserializes its arguments and calls the registered method.
* If that method returns a promise, the UIMessageBroker returns the result to the worker.
*/
export class ServiceMessageBroker {
export class ServiceMessageBroker_ extends ServiceMessageBroker {
private _sink: EventEmitter;
private _methods: Map<string, Function> = new Map<string, Function>();
/**
* @internal
*/
constructor(messageBus: MessageBus, private _serializer: Serializer, public channel) {
super();
this._sink = messageBus.to(channel);
var source = messageBus.from(channel);
ObservableWrapper.subscribe(source, (message) => this._handleMessage(message));

View File

@ -21,6 +21,7 @@ import {bind, Inject, Injector, LifeCycle} from 'angular2/core';
import {ExceptionHandler} from 'angular2/src/core/facade/exceptions';
import {Testability, TestabilityRegistry} from 'angular2/src/core/testability/testability';
import {IS_DART} from '../platform';
import {ComponentRef_} from "../../src/core/linker/dynamic_component_loader";
@Component({selector: 'hello-app'})
@View({template: '{{greeting}} world!'})
@ -178,7 +179,7 @@ export function main() {
var refPromise = bootstrap(HelloRootCmp4, testBindings);
refPromise.then((ref) => {
expect(ref.hostComponent.lc).toBe(ref.injector.get(LifeCycle));
expect(ref.hostComponent.lc).toBe((<ComponentRef_>ref).injector.get(LifeCycle));
async.done();
});
}));

View File

@ -13,6 +13,7 @@ import {
import {ChangeDetectorRef} from 'angular2/src/core/change_detection/change_detector_ref';
import {SpyChangeDetector} from '../spies';
import {ChangeDetectorRef_} from "../../../src/core/change_detection/change_detector_ref";
export function main() {
@ -20,7 +21,7 @@ export function main() {
it('should delegate detectChanges()', () => {
var changeDetector = new SpyChangeDetector();
changeDetector.spy('detectChanges');
var changeDetectorRef = new ChangeDetectorRef(<any>changeDetector);
var changeDetectorRef = new ChangeDetectorRef_(<any>changeDetector);
changeDetectorRef.detectChanges();
expect(changeDetector.spy('detectChanges')).toHaveBeenCalled();
});

View File

@ -13,14 +13,14 @@ import {
tick,
inject
} from 'angular2/test_lib';
import {LifeCycle} from 'angular2/core';
import {SpyChangeDetector} from '../spies';
import {LifeCycle_} from "../../../src/core/life_cycle/life_cycle";
export function main() {
describe("LifeCycle", () => {
it("should throw when reentering tick", () => {
var cd = <any>new SpyChangeDetector();
var lc = new LifeCycle(cd, false);
var lc = new LifeCycle_(cd, false);
cd.spy("detectChanges").andCallFake(() => lc.tick());
expect(() => lc.tick()).toThrowError("LifeCycle.tick is called recursively");

View File

@ -24,6 +24,7 @@ import {DynamicComponentLoader} from 'angular2/src/core/linker/dynamic_component
import {ElementRef} from 'angular2/src/core/linker/element_ref';
import {DOCUMENT} from 'angular2/src/core/render/render';
import {DOM} from 'angular2/src/core/dom/dom_adapter';
import {RootTestComponent_} from "../../../src/test_lib/test_component_builder";
export function main() {
describe('DynamicComponentLoader', function() {
@ -231,7 +232,7 @@ export function main() {
DOM.appendChild(doc.body, rootEl);
loader.loadAsRoot(ChildComp, null, injector)
.then((componentRef) => {
var el = new RootTestComponent(componentRef);
var el = new RootTestComponent_(componentRef);
expect(rootEl.parentNode).toBe(doc.body);
el.detectChanges();

View File

@ -45,6 +45,7 @@ import {ElementRef} from 'angular2/src/core/linker/element_ref';
import {DynamicChangeDetector, ChangeDetectorRef, Parser, Lexer} from 'angular2/src/core/change_detection/change_detection';
import {QueryList} from 'angular2/src/core/linker/query_list';
import {AppView, AppViewContainer} from "angular2/src/core/linker/view";
import {TemplateRef_} from "../../../src/core/linker/template_ref";
function createDummyView(detector = null): AppView {
var res = new SpyView();
@ -701,7 +702,7 @@ export function main() {
});
it("should instantiate directives that depend on pre built objects", () => {
var templateRef = new TemplateRef(<any>new SpyElementRef());
var templateRef = new TemplateRef_(<any>new SpyElementRef());
var bindings = ListWrapper.concat([NeedsTemplateRef], extraBindings);
var inj = injector(bindings, null, false, new PreBuiltObjects(null, null, null, templateRef));
@ -909,7 +910,7 @@ export function main() {
});
it("should inject TemplateRef", () => {
var templateRef = new TemplateRef(<any>new SpyElementRef());
var templateRef = new TemplateRef_(<any>new SpyElementRef());
var inj = injector(ListWrapper.concat([NeedsTemplateRef], extraBindings), null, false,
new PreBuiltObjects(null, null, null, templateRef));
@ -968,7 +969,7 @@ export function main() {
});
it('should contain PreBuiltObjects on the same injector', () => {
var preBuiltObjects = new PreBuiltObjects(null, dummyView, null, new TemplateRef(<any>new SpyElementRef()));
var preBuiltObjects = new PreBuiltObjects(null, dummyView, null, new TemplateRef_(<any>new SpyElementRef()));
var inj = injector(ListWrapper.concat([
NeedsTemplateRefQuery
], extraBindings), null,

View File

@ -90,6 +90,7 @@ import {TemplateRef} from 'angular2/src/core/linker/template_ref';
import {DomRenderer} from 'angular2/src/core/render/dom/dom_renderer';
import {IS_DART} from '../../platform';
import {ViewRef_} from "../../../src/core/linker/view_ref";
const ANCHOR_ELEMENT = CONST_EXPR(new OpaqueToken('AnchorElement'));
@ -2231,7 +2232,7 @@ class SomeImperativeViewport {
}
if (value) {
this.view = this.vc.createEmbeddedView(this.templateRef);
var nodes = this.renderer.getRootNodes(this.view.renderFragment);
var nodes = this.renderer.getRootNodes((<ViewRef_>this.view).renderFragment);
for (var i = 0; i < nodes.length; i++) {
DOM.appendChild(this.anchor, nodes[i]);
}

View File

@ -19,6 +19,9 @@ import {AppView, AppViewContainer} from 'angular2/src/core/linker/view';
import {ViewContainerRef} from 'angular2/src/core/linker/view_container_ref';
import {ElementRef} from 'angular2/src/core/linker/element_ref';
import {ViewRef} from 'angular2/src/core/linker/view_ref';
import {ViewContainerRef_} from "../../../src/core/linker/view_container_ref";
import {ViewRef_} from "../../../src/core/linker/view_ref";
import {ElementRef_} from "../../../src/core/linker/element_ref";
export function main() {
// TODO(tbosch): add missing tests
@ -28,13 +31,13 @@ export function main() {
var view;
var viewManager;
function createViewContainer() { return new ViewContainerRef(viewManager, location); }
function createViewContainer() { return new ViewContainerRef_(viewManager, location); }
beforeEach(() => {
viewManager = new SpyAppViewManager();
view = new SpyView();
view.prop("viewContainers", [null]);
location = new ElementRef(new ViewRef(view), 0, null);
location = new ElementRef_(new ViewRef_(view), 0, null);
});
describe('length', () => {

View File

@ -38,6 +38,10 @@ import {
createNestedElBinder,
createProtoElInjector
} from './view_manager_utils_spec';
import {ProtoViewRef_} from "../../../src/core/linker/view_ref";
import {ViewRef_} from "../../../src/core/linker/view_ref";
import {AppViewManager_} from "../../../src/core/linker/view_manager";
import {TemplateRef_} from "../../../src/core/linker/template_ref";
export function main() {
// TODO(tbosch): add missing tests
@ -51,9 +55,9 @@ export function main() {
var manager: AppViewManager;
var createdRenderViews: RenderViewWithFragments[];
function wrapPv(protoView: AppProtoView): ProtoViewRef { return new ProtoViewRef(protoView); }
function wrapPv(protoView: AppProtoView): ProtoViewRef { return new ProtoViewRef_(protoView); }
function wrapView(view: AppView): ViewRef { return new ViewRef(view); }
function wrapView(view: AppView): ViewRef { return new ViewRef_(view); }
function resetSpies() {
viewListener.spy('viewCreated').reset();
@ -73,7 +77,7 @@ export function main() {
viewListener = new SpyAppViewListener();
viewPool = new SpyAppViewPool();
linker = new SpyProtoViewFactory();
manager = new AppViewManager(viewPool, viewListener, utils, renderer, linker);
manager = new AppViewManager_(viewPool, viewListener, utils, renderer, linker);
createdRenderViews = [];
renderer.spy('createRootHostView')
@ -196,7 +200,7 @@ export function main() {
hostView =
internalView(<ViewRef>manager.createRootHostView(wrapPv(hostProtoView), null, null));
vcRef = hostView.elementRefs[1];
templateRef = new TemplateRef(hostView.elementRefs[1]);
templateRef = new TemplateRef_(hostView.elementRefs[1]);
resetSpies();
});
@ -348,7 +352,7 @@ export function main() {
hostView =
internalView(<ViewRef>manager.createRootHostView(wrapPv(hostProtoView), null, null));
vcRef = hostView.elementRefs[1];
templateRef = new TemplateRef(hostView.elementRefs[1]);
templateRef = new TemplateRef_(hostView.elementRefs[1]);
firstChildView =
internalView(manager.createEmbeddedViewInContainer(vcRef, 0, templateRef));
resetSpies();
@ -420,7 +424,7 @@ export function main() {
hostView = internalView(
<ViewRef>manager.createRootHostView(wrapPv(hostProtoView), null, null));
vcRef = hostView.elementRefs[1];
templateRef = new TemplateRef(hostView.elementRefs[1]);
templateRef = new TemplateRef_(hostView.elementRefs[1]);
firstChildView =
internalView(manager.createEmbeddedViewInContainer(vcRef, 0, templateRef));
secondChildView =
@ -473,7 +477,7 @@ export function main() {
hostView = internalView(
<ViewRef>manager.createRootHostView(wrapPv(hostProtoView), null, null));
vcRef = hostView.elementRefs[1];
templateRef = new TemplateRef(hostView.elementRefs[1]);
templateRef = new TemplateRef_(hostView.elementRefs[1]);
nestedChildViews = [];
childViews = [];
nestedVcRefs = [];

View File

@ -17,6 +17,7 @@ import {
import {NgZone} from 'angular2/src/core/zone/ng_zone';
import {ListWrapper, Map, MapWrapper} from 'angular2/src/core/facade/collection';
import {DOM} from 'angular2/src/core/dom/dom_adapter';
import {NgZone_} from "../../../../../src/core/zone/ng_zone";
export function main() {
var domEventPlugin;
@ -106,7 +107,7 @@ class FakeEventManagerPlugin extends EventManagerPlugin {
}
}
class FakeNgZone extends NgZone {
class FakeNgZone extends NgZone_ {
constructor() { super({enableLongStackTrace: false}); }
run(fn) { fn(); }

View File

@ -15,13 +15,14 @@ import {Testability} from 'angular2/src/core/testability/testability';
import {NgZone} from 'angular2/src/core/zone/ng_zone';
import {normalizeBlank} from 'angular2/src/core/facade/lang';
import {PromiseWrapper} from 'angular2/src/core/facade/async';
import {NgZone_} from "../../../src/core/zone/ng_zone";
// Schedules a microtasks (using a resolved promise .then())
function microTask(fn: Function): void {
PromiseWrapper.resolve(null).then((_) => { fn(); });
}
class MockNgZone extends NgZone {
class MockNgZone extends NgZone_ {
_onTurnStart: () => void;
_onEventDone: () => void;

View File

@ -18,6 +18,7 @@ import {PromiseCompleter, PromiseWrapper, TimerWrapper} from 'angular2/src/core/
import {BaseException} from 'angular2/src/core/facade/exceptions';
import {NgZone} from 'angular2/src/core/zone/ng_zone';
import {NgZone_} from "../../../src/core/zone/ng_zone";
var needsLongerTimers = browserDetection.isSlow || browserDetection.isEdge;
var resultTimer = 1000;
@ -47,7 +48,7 @@ export function main() {
describe("NgZone", () => {
function createZone(enableLongStackTrace) {
var zone = new NgZone({enableLongStackTrace: enableLongStackTrace});
var zone = new NgZone_({enableLongStackTrace: enableLongStackTrace});
zone.overrideOnTurnStart(_log.fn('onTurnStart'));
zone.overrideOnTurnDone(_log.fn('onTurnDone'));
return zone;

View File

@ -23,6 +23,7 @@ import {Map} from 'angular2/src/core/facade/collection';
import {RequestOptions, BaseRequestOptions} from 'angular2/src/http/base_request_options';
import {BaseResponseOptions, ResponseOptions} from 'angular2/src/http/base_response_options';
import {ResponseTypes, ReadyStates, RequestMethods} from 'angular2/src/http/enums';
import {JSONPConnection_} from "../../../src/http/backends/jsonp_backend";
var addEventListenerSpy;
var existingScripts = [];
@ -89,8 +90,8 @@ export function main() {
describe('JSONPConnection', () => {
it('should use the injected BaseResponseOptions to create the response',
inject([AsyncTestCompleter], async => {
let connection = new JSONPConnection(sampleRequest, new MockBrowserJsonp(),
new ResponseOptions({type: ResponseTypes.Error}));
let connection = new JSONPConnection_(sampleRequest, new MockBrowserJsonp(),
new ResponseOptions({type: ResponseTypes.Error}));
connection.response.subscribe(res => {
expect(res.type).toBe(ResponseTypes.Error);
async.done();
@ -100,7 +101,7 @@ export function main() {
}));
it('should ignore load/callback when disposed', inject([AsyncTestCompleter], async => {
var connection = new JSONPConnection(sampleRequest, new MockBrowserJsonp());
var connection = new JSONPConnection_(sampleRequest, new MockBrowserJsonp());
let spy = new SpyObject();
let loadSpy = spy.spy('load');
let errorSpy = spy.spy('error');
@ -123,7 +124,7 @@ export function main() {
it('should report error if loaded without invoking callback',
inject([AsyncTestCompleter], async => {
let connection = new JSONPConnection(sampleRequest, new MockBrowserJsonp());
let connection = new JSONPConnection_(sampleRequest, new MockBrowserJsonp());
connection.response.subscribe(
res => {
expect("response listener called").toBe(false);
@ -138,7 +139,7 @@ export function main() {
}));
it('should report error if script contains error', inject([AsyncTestCompleter], async => {
let connection = new JSONPConnection(sampleRequest, new MockBrowserJsonp());
let connection = new JSONPConnection_(sampleRequest, new MockBrowserJsonp());
connection.response.subscribe(
res => {
@ -160,13 +161,13 @@ export function main() {
let base = new BaseRequestOptions();
let req = new Request(
base.merge(new RequestOptions({url: 'https://google.com', method: method})));
expect(() => new JSONPConnection(req, new MockBrowserJsonp()).response.subscribe())
expect(() => new JSONPConnection_(req, new MockBrowserJsonp()).response.subscribe())
.toThrowError();
});
});
it('should respond with data passed to callback', inject([AsyncTestCompleter], async => {
let connection = new JSONPConnection(sampleRequest, new MockBrowserJsonp());
let connection = new JSONPConnection_(sampleRequest, new MockBrowserJsonp());
connection.response.subscribe(res => {
expect(res.json()).toEqual(({fake_payload: true, blob_id: 12345}));

View File

@ -32,8 +32,9 @@ import {
} from 'angular2/router';
import {DOM} from 'angular2/src/core/dom/dom_adapter';
import {ComponentInstruction_} from "../../src/router/instruction";
var dummyInstruction = new Instruction(new ComponentInstruction('detail', [], null), null, {});
var dummyInstruction = new Instruction(new ComponentInstruction_('detail', [], null), null, {});
export function main() {
describe('router-link directive', function() {

View File

@ -12,6 +12,7 @@ import {RenderProtoViewRefStore} from "angular2/src/web_workers/shared/render_pr
import {
WebWorkerRenderProtoViewRef
} from "angular2/src/web_workers/shared/render_proto_view_ref_store";
import {RenderProtoViewRef_} from "../../../src/core/render/api";
export function main() {
describe("RenderProtoViewRefStore", () => {
@ -36,14 +37,14 @@ export function main() {
beforeEach(() => { store = new RenderProtoViewRefStore(false); });
it("should associate views with the correct references", () => {
var renderProtoViewRef = new RenderProtoViewRef();
var renderProtoViewRef = new RenderProtoViewRef_();
store.store(renderProtoViewRef, 100);
expect(store.deserialize(100)).toBe(renderProtoViewRef);
});
it("should be serializable", () => {
var renderProtoViewRef = new RenderProtoViewRef();
var renderProtoViewRef = new RenderProtoViewRef_();
store.store(renderProtoViewRef, 0);
var deserialized = store.deserialize(store.serialize(renderProtoViewRef));

View File

@ -20,6 +20,7 @@ import {RenderProtoViewRefStore} from 'angular2/src/web_workers/shared/render_pr
import {
RenderViewWithFragmentsStore
} from 'angular2/src/web_workers/shared/render_view_with_fragments_store';
import {ServiceMessageBroker_} from "../../../src/web_workers/shared/service_message_broker";
export function main() {
const CHANNEL = "UIMessageBroker Test Channel";
@ -46,7 +47,7 @@ export function main() {
});
it("should call registered method with correct arguments",
inject([Serializer], (serializer) => {
var broker = new ServiceMessageBroker(messageBuses.ui, serializer, CHANNEL);
var broker = new ServiceMessageBroker_(messageBuses.ui, serializer, CHANNEL);
broker.registerMethod(TEST_METHOD, [PRIMITIVE, PRIMITIVE], (arg1, arg2) => {
expect(arg1).toEqual(PASSED_ARG_1);
expect(arg2).toEqual(PASSED_ARG_2);
@ -56,7 +57,7 @@ export function main() {
}));
it("should return promises to the worker", inject([Serializer], (serializer) => {
var broker = new ServiceMessageBroker(messageBuses.ui, serializer, CHANNEL);
var broker = new ServiceMessageBroker_(messageBuses.ui, serializer, CHANNEL);
broker.registerMethod(TEST_METHOD, [PRIMITIVE], (arg1) => {
expect(arg1).toEqual(PASSED_ARG_1);
return PromiseWrapper.wrap(() => { return RESULT; });

View File

@ -52,6 +52,8 @@ import {MessageBasedRenderer} from 'angular2/src/web_workers/ui/renderer';
import {createPairedMessageBuses, PairedMessageBuses} from '../shared/web_worker_test_util';
import {ServiceMessageBrokerFactory} from 'angular2/src/web_workers/shared/service_message_broker';
import {WebWorkerEventDispatcher} from 'angular2/src/web_workers/worker/event_dispatcher';
import {ServiceMessageBrokerFactory_} from "../../../src/web_workers/shared/service_message_broker";
import {ClientMessageBrokerFactory_} from "../../../src/web_workers/shared/client_message_broker";
export function main() {
@ -63,10 +65,11 @@ export function main() {
var workerMessageBus = messageBuses.worker;
// set up the worker side
var webWorkerBrokerFactory = new ClientMessageBrokerFactory(workerMessageBus, workerSerializer);
var webWorkerBrokerFactory =
new ClientMessageBrokerFactory_(workerMessageBus, workerSerializer);
// set up the ui side
var uiMessageBrokerFactory = new ServiceMessageBrokerFactory(uiMessageBus, uiSerializer);
var uiMessageBrokerFactory = new ServiceMessageBrokerFactory_(uiMessageBus, uiSerializer);
var renderer = new MessageBasedRenderer(uiMessageBrokerFactory, uiMessageBus, uiSerializer,
uiRenderProtoViewStore, uiRenderViewStore, domRenderer);
renderer.start();

View File

@ -17,6 +17,7 @@ import {
} from 'angular2/src/web_workers/shared/client_message_broker';
import {WebWorkerXHRImpl} from "angular2/src/web_workers/worker/xhr_impl";
import {PromiseWrapper} from "angular2/src/core/facade/async";
import {ClientMessageBrokerFactory_} from "../../../src/web_workers/shared/client_message_broker";
export function main() {
describe("WebWorkerXHRImpl", () => {
@ -43,7 +44,7 @@ export function main() {
});
}
class MockMessageBrokerFactory extends ClientMessageBrokerFactory {
class MockMessageBrokerFactory extends ClientMessageBrokerFactory_ {
constructor(private _messageBroker: ClientMessageBroker) { super(null, null); }
createMessageBroker(channel: string, runInZone = true) { return this._messageBroker; }
}

View File

@ -11,6 +11,7 @@ import {
import {LifeCycle} from 'angular2/src/core/life_cycle/life_cycle';
import {ListWrapper} from 'angular2/src/core/facade/collection';
import {getIntParameter, bindAction} from 'angular2/src/test_lib/benchmark_util';
import {ComponentRef_} from "../../../angular2/src/core/linker/dynamic_component_loader";
var testList = null;
@ -20,7 +21,7 @@ export function main() {
bootstrap(AppComponent)
.then((ref) => {
var injector = ref.injector;
var injector = (<ComponentRef_>ref).injector;
var app: AppComponent = ref.hostComponent;
var lifeCycle = injector.get(LifeCycle);

View File

@ -26,6 +26,7 @@ import {ListWrapper} from 'angular2/src/core/facade/collection';
import {Inject} from 'angular2/src/core/di/decorators';
import {reflector} from 'angular2/src/core/reflection/reflection';
import {ComponentRef_} from "../../../angular2/src/core/linker/dynamic_component_loader";
export const BENCHMARK_TYPE = 'LargetableComponent.benchmarkType';
export const LARGETABLE_ROWS = 'LargetableComponent.rows';
@ -124,7 +125,7 @@ export function main() {
function initNg2() {
bootstrap(AppComponent, _createBindings())
.then((ref) => {
var injector = ref.injector;
var injector = (<ComponentRef_>ref).injector;
app = ref.hostComponent;
lifecycle = injector.get(LifeCycle);
bindAction('#ng2DestroyDom', ng2DestroyDom);

View File

@ -9,7 +9,7 @@ import {
Binding,
NgIf
} from 'angular2/core';
import {ComponentRef_} from 'angular2/src/core/linker/dynamic_component_loader';
import {LifeCycle} from 'angular2/src/core/life_cycle/life_cycle';
import {reflector} from 'angular2/src/core/reflection/reflection';
import {ReflectionCapabilities} from 'angular2/src/core/reflection/reflection_capabilities';
@ -96,10 +96,10 @@ export function main() {
function initNg2() {
bootstrap(AppComponentWithStaticTree, createBindings())
.then((ref) => {
var injector = ref.injector;
var injector = (<ComponentRef_>ref).injector;
lifeCycle = injector.get(LifeCycle);
app = ref.hostComponent;
app = (<ComponentRef_>ref).hostComponent;
bindAction('#ng2DestroyDom', ng2DestroyDom);
bindAction('#ng2CreateDom', ng2CreateDom);
bindAction('#ng2UpdateDomProfile', profile(ng2CreateDom, noop, 'ng2-update'));

View File

@ -23,6 +23,7 @@ import {
} from 'angular2/src/test_lib/benchmark_util';
import {BrowserDomAdapter} from 'angular2/src/core/dom/browser_adapter';
import {APP_VIEW_POOL_CAPACITY} from 'angular2/src/core/linker/view_pool';
import {ComponentRef_} from "../../../angular2/src/core/linker/dynamic_component_loader";
function createBindings(): Binding[] {
var viewCacheCapacity = getStringParameter('viewcache') == 'true' ? 10000 : 1;
@ -93,7 +94,7 @@ export function main() {
function initNg2() {
bootstrap(AppComponent, createBindings())
.then((ref) => {
var injector = ref.injector;
var injector = (<ComponentRef_>ref).injector;
lifeCycle = injector.get(LifeCycle);
app = ref.hostComponent;

View File

@ -34,6 +34,7 @@ import {
} from './constants';
import {Ng2ComponentFacade} from './ng2_facade';
import {ExportedNg1Component} from './ng1_facade';
import {NgZone_} from "../../angular2/src/core/zone/ng_zone";
var moduleCount: number = 0;
@ -115,7 +116,7 @@ export class UpgradeModule {
'$rootScope',
(injector: angular.auto.IInjectorService, rootScope: angular.IRootScopeService) => {
ng1Injector = injector;
ngZone.overrideOnTurnDone(() => rootScope.$apply());
(<NgZone_>ngZone).overrideOnTurnDone(() => rootScope.$apply());
ExportedNg1Component.resolve(this.exportedNg1Components, injector);
}
]);