fix(build): add missing return types now enforced by linter

This commit is contained in:
Alex Eagle 2015-06-26 11:10:52 -07:00
parent bc585f2724
commit 44891996b5
61 changed files with 467 additions and 400 deletions

View File

@ -138,9 +138,9 @@ export class ChangeDetectorJITGenerator {
.map((d) => this._genGetDetector(d.directiveIndex)); .map((d) => this._genGetDetector(d.directiveIndex));
} }
_genGetDirective(d: DirectiveIndex) { return `this.directive_${d.name}`; } _genGetDirective(d: DirectiveIndex): string { return `this.directive_${d.name}`; }
_genGetDetector(d: DirectiveIndex) { return `this.detector_${d.name}`; } _genGetDetector(d: DirectiveIndex): string { return `this.detector_${d.name}`; }
_getNonNullPipeNames(): List<string> { _getNonNullPipeNames(): List<string> {
var pipes = []; var pipes = [];
@ -152,7 +152,7 @@ export class ChangeDetectorJITGenerator {
return pipes; return pipes;
} }
_genFieldDefinitions() { _genFieldDefinitions(): string {
var fields = []; var fields = [];
fields = fields.concat(this._fieldNames); fields = fields.concat(this._fieldNames);
fields = fields.concat(this._getNonNullPipeNames()); fields = fields.concat(this._getNonNullPipeNames());
@ -226,7 +226,7 @@ export class ChangeDetectorJITGenerator {
return `${rec}${this._maybeGenLastInDirective(r)}`; return `${rec}${this._maybeGenLastInDirective(r)}`;
} }
_genDirectiveLifecycle(r: ProtoRecord) { _genDirectiveLifecycle(r: ProtoRecord): string {
if (r.name === "onCheck") { if (r.name === "onCheck") {
return this._genOnCheck(r); return this._genOnCheck(r);
} else if (r.name === "onInit") { } else if (r.name === "onInit") {

View File

@ -35,7 +35,7 @@ var _simpleChanges = [
new SimpleChange(null, null) new SimpleChange(null, null)
]; ];
function _simpleChange(previousValue, currentValue) { function _simpleChange(previousValue, currentValue): SimpleChange {
var index = _simpleChangesIndex++ % 20; var index = _simpleChangesIndex++ % 20;
var s = _simpleChanges[index]; var s = _simpleChanges[index];
s.previousValue = previousValue; s.previousValue = previousValue;
@ -44,41 +44,43 @@ function _simpleChange(previousValue, currentValue) {
} }
export class ChangeDetectionUtil { export class ChangeDetectionUtil {
static uninitialized() { return uninitialized; } static uninitialized(): Object { return uninitialized; }
static arrayFn0() { return []; } static arrayFn0(): any[] { return []; }
static arrayFn1(a1) { return [a1]; } static arrayFn1(a1): any[] { return [a1]; }
static arrayFn2(a1, a2) { return [a1, a2]; } static arrayFn2(a1, a2): any[] { return [a1, a2]; }
static arrayFn3(a1, a2, a3) { return [a1, a2, a3]; } static arrayFn3(a1, a2, a3): any[] { return [a1, a2, a3]; }
static arrayFn4(a1, a2, a3, a4) { return [a1, a2, a3, a4]; } static arrayFn4(a1, a2, a3, a4): any[] { return [a1, a2, a3, a4]; }
static arrayFn5(a1, a2, a3, a4, a5) { return [a1, a2, a3, a4, a5]; } static arrayFn5(a1, a2, a3, a4, a5): any[] { return [a1, a2, a3, a4, a5]; }
static arrayFn6(a1, a2, a3, a4, a5, a6) { return [a1, a2, a3, a4, a5, a6]; } static arrayFn6(a1, a2, a3, a4, a5, a6): any[] { return [a1, a2, a3, a4, a5, a6]; }
static arrayFn7(a1, a2, a3, a4, a5, a6, a7) { return [a1, a2, a3, a4, a5, a6, a7]; } static arrayFn7(a1, a2, a3, a4, a5, a6, a7): any[] { return [a1, a2, a3, a4, a5, a6, a7]; }
static arrayFn8(a1, a2, a3, a4, a5, a6, a7, a8) { return [a1, a2, a3, a4, a5, a6, a7, a8]; } static arrayFn8(a1, a2, a3, a4, a5, a6, a7, a8): any[] {
static arrayFn9(a1, a2, a3, a4, a5, a6, a7, a8, a9) { return [a1, a2, a3, a4, a5, a6, a7, a8];
}
static arrayFn9(a1, a2, a3, a4, a5, a6, a7, a8, a9): any[] {
return [a1, a2, a3, a4, a5, a6, a7, a8, a9]; return [a1, a2, a3, a4, a5, a6, a7, a8, a9];
} }
static operation_negate(value) { return !value; } static operation_negate(value): any { return !value; }
static operation_add(left, right) { return left + right; } static operation_add(left, right): any { return left + right; }
static operation_subtract(left, right) { return left - right; } static operation_subtract(left, right): any { return left - right; }
static operation_multiply(left, right) { return left * right; } static operation_multiply(left, right): any { return left * right; }
static operation_divide(left, right) { return left / right; } static operation_divide(left, right): any { return left / right; }
static operation_remainder(left, right) { return left % right; } static operation_remainder(left, right): any { return left % right; }
static operation_equals(left, right) { return left == right; } static operation_equals(left, right): any { return left == right; }
static operation_not_equals(left, right) { return left != right; } static operation_not_equals(left, right): any { return left != right; }
static operation_identical(left, right) { return left === right; } static operation_identical(left, right): any { return left === right; }
static operation_not_identical(left, right) { return left !== right; } static operation_not_identical(left, right): any { return left !== right; }
static operation_less_then(left, right) { return left < right; } static operation_less_then(left, right): any { return left < right; }
static operation_greater_then(left, right) { return left > right; } static operation_greater_then(left, right): any { return left > right; }
static operation_less_or_equals_then(left, right) { return left <= right; } static operation_less_or_equals_then(left, right): any { return left <= right; }
static operation_greater_or_equals_then(left, right) { return left >= right; } static operation_greater_or_equals_then(left, right): any { return left >= right; }
static operation_logical_and(left, right) { return left && right; } static operation_logical_and(left, right): any { return left && right; }
static operation_logical_or(left, right) { return left || right; } static operation_logical_or(left, right): any { return left || right; }
static cond(cond, trueVal, falseVal) { return cond ? trueVal : falseVal; } static cond(cond, trueVal, falseVal): any { return cond ? trueVal : falseVal; }
static mapFn(keys: List<any>) { static mapFn(keys: List<any>): any {
function buildMap(values) { function buildMap(values): StringMap<any, any> {
var res = StringMapWrapper.create(); var res = StringMapWrapper.create();
for (var i = 0; i < keys.length; ++i) { for (var i = 0; i < keys.length; ++i) {
StringMapWrapper.set(res, keys[i], values[i]); StringMapWrapper.set(res, keys[i], values[i]);
@ -113,7 +115,7 @@ export class ChangeDetectionUtil {
} }
} }
static keyedAccess(obj, args) { return obj[args[0]]; } static keyedAccess(obj, args): any { return obj[args[0]]; }
static unwrapValue(value: any): any { static unwrapValue(value: any): any {
if (value instanceof WrappedValue) { if (value instanceof WrappedValue) {
@ -129,7 +131,7 @@ export class ChangeDetectionUtil {
static throwDehydrated() { throw new DehydratedException(); } static throwDehydrated() { throw new DehydratedException(); }
static changeDetectionMode(strategy: string) { static changeDetectionMode(strategy: string): string {
return strategy == ON_PUSH ? CHECK_ONCE : CHECK_ALWAYS; return strategy == ON_PUSH ? CHECK_ONCE : CHECK_ALWAYS;
} }
@ -137,7 +139,7 @@ export class ChangeDetectionUtil {
return _simpleChange(previousValue, currentValue); return _simpleChange(previousValue, currentValue);
} }
static addChange(changes, propertyName: string, change) { static addChange(changes, propertyName: string, change): Map<any, any> {
if (isBlank(changes)) { if (isBlank(changes)) {
changes = {}; changes = {};
} }

View File

@ -318,7 +318,7 @@ export class DynamicChangeDetector extends AbstractChangeDetector {
} }
} }
function isSame(a, b) { function isSame(a, b): boolean {
if (a === b) return true; if (a === b) return true;
if (a instanceof String && b instanceof String && a == b) return true; if (a instanceof String && b instanceof String && a == b) return true;
if ((a !== a) && (b !== b)) return true; if ((a !== a) && (b !== b)) return true;

View File

@ -15,7 +15,7 @@ export class AST {
} }
export class EmptyExpr extends AST { export class EmptyExpr extends AST {
eval(context, locals: Locals) { return null; } eval(context, locals: Locals): any { return null; }
visit(visitor: AstVisitor) { visit(visitor: AstVisitor) {
// do nothing // do nothing
@ -23,9 +23,9 @@ export class EmptyExpr extends AST {
} }
export class ImplicitReceiver extends AST { export class ImplicitReceiver extends AST {
eval(context, locals: Locals) { return context; } eval(context, locals: Locals): any { return context; }
visit(visitor: AstVisitor) { return visitor.visitImplicitReceiver(this); } visit(visitor: AstVisitor): any { return visitor.visitImplicitReceiver(this); }
} }
/** /**
@ -34,7 +34,7 @@ export class ImplicitReceiver extends AST {
export class Chain extends AST { export class Chain extends AST {
constructor(public expressions: List<any>) { super(); } constructor(public expressions: List<any>) { super(); }
eval(context, locals: Locals) { eval(context, locals: Locals): any {
var result; var result;
for (var i = 0; i < this.expressions.length; i++) { for (var i = 0; i < this.expressions.length; i++) {
var last = this.expressions[i].eval(context, locals); var last = this.expressions[i].eval(context, locals);
@ -43,13 +43,13 @@ export class Chain extends AST {
return result; return result;
} }
visit(visitor: AstVisitor) { return visitor.visitChain(this); } visit(visitor: AstVisitor): any { return visitor.visitChain(this); }
} }
export class Conditional extends AST { export class Conditional extends AST {
constructor(public condition: AST, public trueExp: AST, public falseExp: AST) { super(); } constructor(public condition: AST, public trueExp: AST, public falseExp: AST) { super(); }
eval(context, locals: Locals) { eval(context, locals: Locals): any {
if (this.condition.eval(context, locals)) { if (this.condition.eval(context, locals)) {
return this.trueExp.eval(context, locals); return this.trueExp.eval(context, locals);
} else { } else {
@ -57,7 +57,7 @@ export class Conditional extends AST {
} }
} }
visit(visitor: AstVisitor) { return visitor.visitConditional(this); } visit(visitor: AstVisitor): any { return visitor.visitConditional(this); }
} }
export class If extends AST { export class If extends AST {
@ -71,7 +71,7 @@ export class If extends AST {
} }
} }
visit(visitor: AstVisitor) { return visitor.visitIf(this); } visit(visitor: AstVisitor): any { return visitor.visitIf(this); }
} }
export class AccessMember extends AST { export class AccessMember extends AST {
@ -80,7 +80,7 @@ export class AccessMember extends AST {
super(); super();
} }
eval(context, locals: Locals) { eval(context, locals: Locals): any {
if (this.receiver instanceof ImplicitReceiver && isPresent(locals) && if (this.receiver instanceof ImplicitReceiver && isPresent(locals) &&
locals.contains(this.name)) { locals.contains(this.name)) {
return locals.get(this.name); return locals.get(this.name);
@ -92,7 +92,7 @@ export class AccessMember extends AST {
get isAssignable(): boolean { return true; } get isAssignable(): boolean { return true; }
assign(context, locals: Locals, value) { assign(context, locals: Locals, value): any {
var evaluatedContext = this.receiver.eval(context, locals); var evaluatedContext = this.receiver.eval(context, locals);
if (this.receiver instanceof ImplicitReceiver && isPresent(locals) && if (this.receiver instanceof ImplicitReceiver && isPresent(locals) &&
@ -103,7 +103,7 @@ export class AccessMember extends AST {
} }
} }
visit(visitor: AstVisitor) { return visitor.visitAccessMember(this); } visit(visitor: AstVisitor): any { return visitor.visitAccessMember(this); }
} }
export class SafeAccessMember extends AST { export class SafeAccessMember extends AST {
@ -112,18 +112,18 @@ export class SafeAccessMember extends AST {
super(); super();
} }
eval(context, locals: Locals) { eval(context, locals: Locals): any {
var evaluatedReceiver = this.receiver.eval(context, locals); var evaluatedReceiver = this.receiver.eval(context, locals);
return isBlank(evaluatedReceiver) ? null : this.getter(evaluatedReceiver); return isBlank(evaluatedReceiver) ? null : this.getter(evaluatedReceiver);
} }
visit(visitor: AstVisitor) { return visitor.visitSafeAccessMember(this); } visit(visitor: AstVisitor): any { return visitor.visitSafeAccessMember(this); }
} }
export class KeyedAccess extends AST { export class KeyedAccess extends AST {
constructor(public obj: AST, public key: AST) { super(); } constructor(public obj: AST, public key: AST) { super(); }
eval(context, locals: Locals) { eval(context, locals: Locals): any {
var obj: any = this.obj.eval(context, locals); var obj: any = this.obj.eval(context, locals);
var key: any = this.key.eval(context, locals); var key: any = this.key.eval(context, locals);
return obj[key]; return obj[key];
@ -131,44 +131,44 @@ export class KeyedAccess extends AST {
get isAssignable(): boolean { return true; } get isAssignable(): boolean { return true; }
assign(context, locals: Locals, value) { assign(context, locals: Locals, value): any {
var obj: any = this.obj.eval(context, locals); var obj: any = this.obj.eval(context, locals);
var key: any = this.key.eval(context, locals); var key: any = this.key.eval(context, locals);
obj[key] = value; obj[key] = value;
return value; return value;
} }
visit(visitor: AstVisitor) { return visitor.visitKeyedAccess(this); } visit(visitor: AstVisitor): any { return visitor.visitKeyedAccess(this); }
} }
export class BindingPipe extends AST { export class BindingPipe extends AST {
constructor(public exp: AST, public name: string, public args: List<any>) { super(); } constructor(public exp: AST, public name: string, public args: List<any>) { super(); }
visit(visitor: AstVisitor) { return visitor.visitPipe(this); } visit(visitor: AstVisitor): any { return visitor.visitPipe(this); }
} }
export class LiteralPrimitive extends AST { export class LiteralPrimitive extends AST {
constructor(public value) { super(); } constructor(public value) { super(); }
eval(context, locals: Locals) { return this.value; } eval(context, locals: Locals): any { return this.value; }
visit(visitor: AstVisitor) { return visitor.visitLiteralPrimitive(this); } visit(visitor: AstVisitor): any { return visitor.visitLiteralPrimitive(this); }
} }
export class LiteralArray extends AST { export class LiteralArray extends AST {
constructor(public expressions: List<any>) { super(); } constructor(public expressions: List<any>) { super(); }
eval(context, locals: Locals) { eval(context, locals: Locals): any {
return ListWrapper.map(this.expressions, (e) => e.eval(context, locals)); return ListWrapper.map(this.expressions, (e) => e.eval(context, locals));
} }
visit(visitor: AstVisitor) { return visitor.visitLiteralArray(this); } visit(visitor: AstVisitor): any { return visitor.visitLiteralArray(this); }
} }
export class LiteralMap extends AST { export class LiteralMap extends AST {
constructor(public keys: List<any>, public values: List<any>) { super(); } constructor(public keys: List<any>, public values: List<any>) { super(); }
eval(context, locals: Locals) { eval(context, locals: Locals): any {
var res = StringMapWrapper.create(); var res = StringMapWrapper.create();
for (var i = 0; i < this.keys.length; ++i) { for (var i = 0; i < this.keys.length; ++i) {
StringMapWrapper.set(res, this.keys[i], this.values[i].eval(context, locals)); StringMapWrapper.set(res, this.keys[i], this.values[i].eval(context, locals));
@ -176,13 +176,15 @@ export class LiteralMap extends AST {
return res; return res;
} }
visit(visitor: AstVisitor) { return visitor.visitLiteralMap(this); } visit(visitor: AstVisitor): any { return visitor.visitLiteralMap(this); }
} }
export class Interpolation extends AST { export class Interpolation extends AST {
constructor(public strings: List<any>, public expressions: List<any>) { super(); } constructor(public strings: List<any>, public expressions: List<any>) { super(); }
eval(context, locals) { throw new BaseException("evaluating an Interpolation is not supported"); } eval(context, locals): any {
throw new BaseException("evaluating an Interpolation is not supported");
}
visit(visitor: AstVisitor) { visitor.visitInterpolation(this); } visit(visitor: AstVisitor) { visitor.visitInterpolation(this); }
} }
@ -190,7 +192,7 @@ export class Interpolation extends AST {
export class Binary extends AST { export class Binary extends AST {
constructor(public operation: string, public left: AST, public right: AST) { super(); } constructor(public operation: string, public left: AST, public right: AST) { super(); }
eval(context, locals: Locals) { eval(context, locals: Locals): any {
var left: any = this.left.eval(context, locals); var left: any = this.left.eval(context, locals);
switch (this.operation) { switch (this.operation) {
case '&&': case '&&':
@ -235,25 +237,25 @@ export class Binary extends AST {
throw 'Internal error [$operation] not handled'; throw 'Internal error [$operation] not handled';
} }
visit(visitor: AstVisitor) { return visitor.visitBinary(this); } visit(visitor: AstVisitor): any { return visitor.visitBinary(this); }
} }
export class PrefixNot extends AST { export class PrefixNot extends AST {
constructor(public expression: AST) { super(); } constructor(public expression: AST) { super(); }
eval(context, locals: Locals) { return !this.expression.eval(context, locals); } eval(context, locals: Locals): any { return !this.expression.eval(context, locals); }
visit(visitor: AstVisitor) { return visitor.visitPrefixNot(this); } visit(visitor: AstVisitor): any { return visitor.visitPrefixNot(this); }
} }
export class Assignment extends AST { export class Assignment extends AST {
constructor(public target: AST, public value: AST) { super(); } constructor(public target: AST, public value: AST) { super(); }
eval(context, locals: Locals) { eval(context, locals: Locals): any {
return this.target.assign(context, locals, this.value.eval(context, locals)); return this.target.assign(context, locals, this.value.eval(context, locals));
} }
visit(visitor: AstVisitor) { return visitor.visitAssignment(this); } visit(visitor: AstVisitor): any { return visitor.visitAssignment(this); }
} }
export class MethodCall extends AST { export class MethodCall extends AST {
@ -262,7 +264,7 @@ export class MethodCall extends AST {
super(); super();
} }
eval(context, locals: Locals) { eval(context, locals: Locals): any {
var evaluatedArgs = evalList(context, locals, this.args); var evaluatedArgs = evalList(context, locals, this.args);
if (this.receiver instanceof ImplicitReceiver && isPresent(locals) && if (this.receiver instanceof ImplicitReceiver && isPresent(locals) &&
locals.contains(this.name)) { locals.contains(this.name)) {
@ -274,7 +276,7 @@ export class MethodCall extends AST {
} }
} }
visit(visitor: AstVisitor) { return visitor.visitMethodCall(this); } visit(visitor: AstVisitor): any { return visitor.visitMethodCall(this); }
} }
export class SafeMethodCall extends AST { export class SafeMethodCall extends AST {
@ -283,20 +285,20 @@ export class SafeMethodCall extends AST {
super(); super();
} }
eval(context, locals: Locals) { eval(context, locals: Locals): any {
var evaluatedReceiver = this.receiver.eval(context, locals); var evaluatedReceiver = this.receiver.eval(context, locals);
if (isBlank(evaluatedReceiver)) return null; if (isBlank(evaluatedReceiver)) return null;
var evaluatedArgs = evalList(context, locals, this.args); var evaluatedArgs = evalList(context, locals, this.args);
return this.fn(evaluatedReceiver, evaluatedArgs); return this.fn(evaluatedReceiver, evaluatedArgs);
} }
visit(visitor: AstVisitor) { return visitor.visitSafeMethodCall(this); } visit(visitor: AstVisitor): any { return visitor.visitSafeMethodCall(this); }
} }
export class FunctionCall extends AST { export class FunctionCall extends AST {
constructor(public target: AST, public args: List<any>) { super(); } constructor(public target: AST, public args: List<any>) { super(); }
eval(context, locals: Locals) { eval(context, locals: Locals): any {
var obj: any = this.target.eval(context, locals); var obj: any = this.target.eval(context, locals);
if (!(obj instanceof Function)) { if (!(obj instanceof Function)) {
throw new BaseException(`${obj} is not a function`); throw new BaseException(`${obj} is not a function`);
@ -304,19 +306,19 @@ export class FunctionCall extends AST {
return FunctionWrapper.apply(obj, evalList(context, locals, this.args)); return FunctionWrapper.apply(obj, evalList(context, locals, this.args));
} }
visit(visitor: AstVisitor) { return visitor.visitFunctionCall(this); } visit(visitor: AstVisitor): any { return visitor.visitFunctionCall(this); }
} }
export class ASTWithSource extends AST { export class ASTWithSource extends AST {
constructor(public ast: AST, public source: string, public location: string) { super(); } constructor(public ast: AST, public source: string, public location: string) { super(); }
eval(context, locals: Locals) { return this.ast.eval(context, locals); } eval(context, locals: Locals): any { return this.ast.eval(context, locals); }
get isAssignable(): boolean { return this.ast.isAssignable; } get isAssignable(): boolean { return this.ast.isAssignable; }
assign(context, locals: Locals, value) { return this.ast.assign(context, locals, value); } assign(context, locals: Locals, value): any { return this.ast.assign(context, locals, value); }
visit(visitor: AstVisitor) { return this.ast.visit(visitor); } visit(visitor: AstVisitor): any { return this.ast.visit(visitor); }
toString(): string { return `${this.source} in ${this.location}`; } toString(): string { return `${this.source} in ${this.location}`; }
} }
@ -348,58 +350,64 @@ export interface AstVisitor {
} }
export class AstTransformer implements AstVisitor { export class AstTransformer implements AstVisitor {
visitImplicitReceiver(ast: ImplicitReceiver) { return ast; } visitImplicitReceiver(ast: ImplicitReceiver): ImplicitReceiver { return ast; }
visitInterpolation(ast: Interpolation) { visitInterpolation(ast: Interpolation): Interpolation {
return new Interpolation(ast.strings, this.visitAll(ast.expressions)); return new Interpolation(ast.strings, this.visitAll(ast.expressions));
} }
visitLiteralPrimitive(ast: LiteralPrimitive) { return new LiteralPrimitive(ast.value); } visitLiteralPrimitive(ast: LiteralPrimitive): LiteralPrimitive {
return new LiteralPrimitive(ast.value);
}
visitAccessMember(ast: AccessMember) { visitAccessMember(ast: AccessMember): AccessMember {
return new AccessMember(ast.receiver.visit(this), ast.name, ast.getter, ast.setter); return new AccessMember(ast.receiver.visit(this), ast.name, ast.getter, ast.setter);
} }
visitSafeAccessMember(ast: SafeAccessMember) { visitSafeAccessMember(ast: SafeAccessMember): SafeAccessMember {
return new SafeAccessMember(ast.receiver.visit(this), ast.name, ast.getter, ast.setter); return new SafeAccessMember(ast.receiver.visit(this), ast.name, ast.getter, ast.setter);
} }
visitMethodCall(ast: MethodCall) { visitMethodCall(ast: MethodCall): MethodCall {
return new MethodCall(ast.receiver.visit(this), ast.name, ast.fn, this.visitAll(ast.args)); return new MethodCall(ast.receiver.visit(this), ast.name, ast.fn, this.visitAll(ast.args));
} }
visitSafeMethodCall(ast: SafeMethodCall) { visitSafeMethodCall(ast: SafeMethodCall): SafeMethodCall {
return new SafeMethodCall(ast.receiver.visit(this), ast.name, ast.fn, this.visitAll(ast.args)); return new SafeMethodCall(ast.receiver.visit(this), ast.name, ast.fn, this.visitAll(ast.args));
} }
visitFunctionCall(ast: FunctionCall) { visitFunctionCall(ast: FunctionCall): FunctionCall {
return new FunctionCall(ast.target.visit(this), this.visitAll(ast.args)); return new FunctionCall(ast.target.visit(this), this.visitAll(ast.args));
} }
visitLiteralArray(ast: LiteralArray) { return new LiteralArray(this.visitAll(ast.expressions)); } visitLiteralArray(ast: LiteralArray): LiteralArray {
return new LiteralArray(this.visitAll(ast.expressions));
}
visitLiteralMap(ast: LiteralMap) { return new LiteralMap(ast.keys, this.visitAll(ast.values)); } visitLiteralMap(ast: LiteralMap): LiteralMap {
return new LiteralMap(ast.keys, this.visitAll(ast.values));
}
visitBinary(ast: Binary) { visitBinary(ast: Binary): Binary {
return new Binary(ast.operation, ast.left.visit(this), ast.right.visit(this)); return new Binary(ast.operation, ast.left.visit(this), ast.right.visit(this));
} }
visitPrefixNot(ast: PrefixNot) { return new PrefixNot(ast.expression.visit(this)); } visitPrefixNot(ast: PrefixNot): PrefixNot { return new PrefixNot(ast.expression.visit(this)); }
visitConditional(ast: Conditional) { visitConditional(ast: Conditional): Conditional {
return new Conditional(ast.condition.visit(this), ast.trueExp.visit(this), return new Conditional(ast.condition.visit(this), ast.trueExp.visit(this),
ast.falseExp.visit(this)); ast.falseExp.visit(this));
} }
visitPipe(ast: BindingPipe) { visitPipe(ast: BindingPipe): BindingPipe {
return new BindingPipe(ast.exp.visit(this), ast.name, this.visitAll(ast.args)); return new BindingPipe(ast.exp.visit(this), ast.name, this.visitAll(ast.args));
} }
visitKeyedAccess(ast: KeyedAccess) { visitKeyedAccess(ast: KeyedAccess): KeyedAccess {
return new KeyedAccess(ast.obj.visit(this), ast.key.visit(this)); return new KeyedAccess(ast.obj.visit(this), ast.key.visit(this));
} }
visitAll(asts: List<any>) { visitAll(asts: List<any>): List<any> {
var res = ListWrapper.createFixedSize(asts.length); var res = ListWrapper.createFixedSize(asts.length);
for (var i = 0; i < asts.length; ++i) { for (var i = 0; i < asts.length; ++i) {
res[i] = asts[i].visit(this); res[i] = asts[i].visit(this);
@ -407,13 +415,13 @@ export class AstTransformer implements AstVisitor {
return res; return res;
} }
visitChain(ast: Chain) { return new Chain(this.visitAll(ast.expressions)); } visitChain(ast: Chain): Chain { return new Chain(this.visitAll(ast.expressions)); }
visitAssignment(ast: Assignment) { visitAssignment(ast: Assignment): Assignment {
return new Assignment(ast.target.visit(this), ast.value.visit(this)); return new Assignment(ast.target.visit(this), ast.value.visit(this));
} }
visitIf(ast: If) { visitIf(ast: If): If {
let falseExp = isPresent(ast.falseExp) ? ast.falseExp.visit(this) : null; let falseExp = isPresent(ast.falseExp) ? ast.falseExp.visit(this) : null;
return new If(ast.condition.visit(this), ast.trueExp.visit(this), falseExp); return new If(ast.condition.visit(this), ast.trueExp.visit(this), falseExp);
} }
@ -433,7 +441,7 @@ var _evalListCache = [
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
]; ];
function evalList(context, locals: Locals, exps: List<any>) { function evalList(context, locals: Locals, exps: List<any>): any[] {
var length = exps.length; var length = exps.length;
if (length > 10) { if (length > 10) {
throw new BaseException("Cannot have more than 10 argument"); throw new BaseException("Cannot have more than 10 argument");

View File

@ -16,7 +16,7 @@ export class Locals {
return false; return false;
} }
get(name: string) { get(name: string): any {
if (this.current.has(name)) { if (this.current.has(name)) {
return this.current.get(name); return this.current.get(name);
} }
@ -41,4 +41,4 @@ export class Locals {
} }
clearValues(): void { MapWrapper.clearValues(this.current); } clearValues(): void { MapWrapper.clearValues(this.current); }
} }

View File

@ -217,7 +217,7 @@ class _ParseAST {
return ast; return ast;
} }
parsePipe() { parsePipe(): AST {
var result = this.parseExpression(); var result = this.parseExpression();
if (this.optionalOperator("|")) { if (this.optionalOperator("|")) {
if (this.parseAction) { if (this.parseAction) {
@ -237,7 +237,7 @@ class _ParseAST {
return result; return result;
} }
parseExpression() { parseExpression(): AST {
var start = this.inputIndex; var start = this.inputIndex;
var result = this.parseConditional(); var result = this.parseConditional();
@ -259,7 +259,7 @@ class _ParseAST {
return result; return result;
} }
parseConditional() { parseConditional(): AST {
var start = this.inputIndex; var start = this.inputIndex;
var result = this.parseLogicalOr(); var result = this.parseLogicalOr();
@ -277,7 +277,7 @@ class _ParseAST {
} }
} }
parseLogicalOr() { parseLogicalOr(): AST {
// '||' // '||'
var result = this.parseLogicalAnd(); var result = this.parseLogicalAnd();
while (this.optionalOperator('||')) { while (this.optionalOperator('||')) {
@ -286,7 +286,7 @@ class _ParseAST {
return result; return result;
} }
parseLogicalAnd() { parseLogicalAnd(): AST {
// '&&' // '&&'
var result = this.parseEquality(); var result = this.parseEquality();
while (this.optionalOperator('&&')) { while (this.optionalOperator('&&')) {
@ -295,7 +295,7 @@ class _ParseAST {
return result; return result;
} }
parseEquality() { parseEquality(): AST {
// '==','!=','===','!==' // '==','!=','===','!=='
var result = this.parseRelational(); var result = this.parseRelational();
while (true) { while (true) {
@ -313,7 +313,7 @@ class _ParseAST {
} }
} }
parseRelational() { parseRelational(): AST {
// '<', '>', '<=', '>=' // '<', '>', '<=', '>='
var result = this.parseAdditive(); var result = this.parseAdditive();
while (true) { while (true) {
@ -331,7 +331,7 @@ class _ParseAST {
} }
} }
parseAdditive() { parseAdditive(): AST {
// '+', '-' // '+', '-'
var result = this.parseMultiplicative(); var result = this.parseMultiplicative();
while (true) { while (true) {
@ -345,7 +345,7 @@ class _ParseAST {
} }
} }
parseMultiplicative() { parseMultiplicative(): AST {
// '*', '%', '/' // '*', '%', '/'
var result = this.parsePrefix(); var result = this.parsePrefix();
while (true) { while (true) {
@ -361,7 +361,7 @@ class _ParseAST {
} }
} }
parsePrefix() { parsePrefix(): AST {
if (this.optionalOperator('+')) { if (this.optionalOperator('+')) {
return this.parsePrefix(); return this.parsePrefix();
} else if (this.optionalOperator('-')) { } else if (this.optionalOperator('-')) {
@ -398,12 +398,11 @@ class _ParseAST {
} }
} }
parsePrimary() { parsePrimary(): AST {
if (this.optionalCharacter($LPAREN)) { if (this.optionalCharacter($LPAREN)) {
let result = this.parsePipe(); let result = this.parsePipe();
this.expectCharacter($RPAREN); this.expectCharacter($RPAREN);
return result return result;
} else if (this.next.isKeywordNull() || this.next.isKeywordUndefined()) { } else if (this.next.isKeywordNull() || this.next.isKeywordUndefined()) {
this.advance(); this.advance();
return new LiteralPrimitive(null); return new LiteralPrimitive(null);
@ -427,7 +426,7 @@ class _ParseAST {
this.advance(); this.advance();
elseExp = this.parseExpressionOrBlock(); elseExp = this.parseExpressionOrBlock();
} }
return new If(condition, ifExp, elseExp) return new If(condition, ifExp, elseExp);
} else if (this.optionalCharacter($LBRACKET)) { } else if (this.optionalCharacter($LBRACKET)) {
var elements = this.parseExpressionList($RBRACKET); var elements = this.parseExpressionList($RBRACKET);
@ -456,6 +455,8 @@ class _ParseAST {
} else { } else {
this.error(`Unexpected token ${this.next}`); this.error(`Unexpected token ${this.next}`);
} }
// error() throws, so we don't reach here.
throw new BaseException("Fell through all cases in parsePrimary");
} }
parseExpressionList(terminator: int): List<any> { parseExpressionList(terminator: int): List<any> {
@ -468,7 +469,7 @@ class _ParseAST {
return result; return result;
} }
parseLiteralMap() { parseLiteralMap(): LiteralMap {
var keys = []; var keys = [];
var values = []; var values = [];
this.expectCharacter($LBRACE); this.expectCharacter($LBRACE);
@ -502,7 +503,7 @@ class _ParseAST {
} }
} }
parseCallArguments() { parseCallArguments(): BindingPipe[] {
if (this.next.isCharacter($RPAREN)) return []; if (this.next.isCharacter($RPAREN)) return [];
var positionals = []; var positionals = [];
do { do {
@ -545,7 +546,7 @@ class _ParseAST {
/** /**
* An identifier, a keyword, a string with an optional `-` inbetween. * An identifier, a keyword, a string with an optional `-` inbetween.
*/ */
expectTemplateBindingKey() { expectTemplateBindingKey(): string {
var result = ''; var result = '';
var operatorFound = false; var operatorFound = false;
do { do {
@ -559,7 +560,7 @@ class _ParseAST {
return result.toString(); return result.toString();
} }
parseTemplateBindings() { parseTemplateBindings(): any[] {
var bindings = []; var bindings = [];
var prefix = null; var prefix = null;
while (this.index < this.tokens.length) { while (this.index < this.tokens.length) {
@ -607,7 +608,7 @@ class _ParseAST {
} }
class SimpleExpressionChecker implements AstVisitor { class SimpleExpressionChecker implements AstVisitor {
static check(ast: AST) { static check(ast: AST): boolean {
var s = new SimpleExpressionChecker(); var s = new SimpleExpressionChecker();
ast.visit(s); ast.visit(s);
return s.simple; return s.simple;
@ -645,7 +646,7 @@ class SimpleExpressionChecker implements AstVisitor {
visitKeyedAccess(ast: KeyedAccess) { this.simple = false; } visitKeyedAccess(ast: KeyedAccess) { this.simple = false; }
visitAll(asts: List<any>) { visitAll(asts: List<any>): List<any> {
var res = ListWrapper.createFixedSize(asts.length); var res = ListWrapper.createFixedSize(asts.length);
for (var i = 0; i < asts.length; ++i) { for (var i = 0; i < asts.length; ++i) {
res[i] = asts[i].visit(this); res[i] = asts[i].visit(this);

View File

@ -19,9 +19,9 @@ export class NullPipe extends BasePipe {
static supportsObj(obj): boolean { return isBlank(obj); } static supportsObj(obj): boolean { return isBlank(obj); }
supports(obj) { return NullPipe.supportsObj(obj); } supports(obj): boolean { return NullPipe.supportsObj(obj); }
transform(value) { transform(value): WrappedValue {
if (!this.called) { if (!this.called) {
this.called = true; this.called = true;
return WrappedValue.wrap(null); return WrappedValue.wrap(null);

View File

@ -43,7 +43,7 @@ export class DynamicProtoChangeDetector implements ProtoChangeDetector {
this._records = this._createRecords(definition); this._records = this._createRecords(definition);
} }
instantiate(dispatcher: any) { instantiate(dispatcher: any): ChangeDetector {
return new DynamicChangeDetector(this.definition.id, this.definition.strategy, dispatcher, return new DynamicChangeDetector(this.definition.id, this.definition.strategy, dispatcher,
this._pipeRegistry, this._records, this._pipeRegistry, this._records,
this.definition.directiveRecords); this.definition.directiveRecords);
@ -95,19 +95,19 @@ class _ConvertAstIntoProtoRecords implements AstVisitor {
b.ast.visit(c); b.ast.visit(c);
} }
visitImplicitReceiver(ast: ImplicitReceiver) { return this._bindingRecord.implicitReceiver; } visitImplicitReceiver(ast: ImplicitReceiver): any { return this._bindingRecord.implicitReceiver; }
visitInterpolation(ast: Interpolation) { visitInterpolation(ast: Interpolation): number {
var args = this._visitAll(ast.expressions); var args = this._visitAll(ast.expressions);
return this._addRecord(RecordType.INTERPOLATE, "interpolate", _interpolationFn(ast.strings), return this._addRecord(RecordType.INTERPOLATE, "interpolate", _interpolationFn(ast.strings),
args, ast.strings, 0); args, ast.strings, 0);
} }
visitLiteralPrimitive(ast: LiteralPrimitive) { visitLiteralPrimitive(ast: LiteralPrimitive): number {
return this._addRecord(RecordType.CONST, "literal", ast.value, [], null, 0); return this._addRecord(RecordType.CONST, "literal", ast.value, [], null, 0);
} }
visitAccessMember(ast: AccessMember) { visitAccessMember(ast: AccessMember): number {
var receiver = ast.receiver.visit(this); var receiver = ast.receiver.visit(this);
if (isPresent(this._variableNames) && ListWrapper.contains(this._variableNames, ast.name) && if (isPresent(this._variableNames) && ListWrapper.contains(this._variableNames, ast.name) &&
ast.receiver instanceof ast.receiver instanceof
@ -118,12 +118,12 @@ class _ConvertAstIntoProtoRecords implements AstVisitor {
} }
} }
visitSafeAccessMember(ast: SafeAccessMember) { visitSafeAccessMember(ast: SafeAccessMember): number {
var receiver = ast.receiver.visit(this); var receiver = ast.receiver.visit(this);
return this._addRecord(RecordType.SAFE_PROPERTY, ast.name, ast.getter, [], null, receiver); return this._addRecord(RecordType.SAFE_PROPERTY, ast.name, ast.getter, [], null, receiver);
} }
visitMethodCall(ast: MethodCall) { visitMethodCall(ast: MethodCall): number {
var receiver = ast.receiver.visit(this); var receiver = ast.receiver.visit(this);
var args = this._visitAll(ast.args); var args = this._visitAll(ast.args);
if (isPresent(this._variableNames) && ListWrapper.contains(this._variableNames, ast.name)) { if (isPresent(this._variableNames) && ListWrapper.contains(this._variableNames, ast.name)) {
@ -134,44 +134,44 @@ class _ConvertAstIntoProtoRecords implements AstVisitor {
} }
} }
visitSafeMethodCall(ast: SafeMethodCall) { visitSafeMethodCall(ast: SafeMethodCall): number {
var receiver = ast.receiver.visit(this); var receiver = ast.receiver.visit(this);
var args = this._visitAll(ast.args); var args = this._visitAll(ast.args);
return this._addRecord(RecordType.SAFE_INVOKE_METHOD, ast.name, ast.fn, args, null, receiver); return this._addRecord(RecordType.SAFE_INVOKE_METHOD, ast.name, ast.fn, args, null, receiver);
} }
visitFunctionCall(ast: FunctionCall) { visitFunctionCall(ast: FunctionCall): number {
var target = ast.target.visit(this); var target = ast.target.visit(this);
var args = this._visitAll(ast.args); var args = this._visitAll(ast.args);
return this._addRecord(RecordType.INVOKE_CLOSURE, "closure", null, args, null, target); return this._addRecord(RecordType.INVOKE_CLOSURE, "closure", null, args, null, target);
} }
visitLiteralArray(ast: LiteralArray) { visitLiteralArray(ast: LiteralArray): number {
var primitiveName = `arrayFn${ast.expressions.length}`; var primitiveName = `arrayFn${ast.expressions.length}`;
return this._addRecord(RecordType.PRIMITIVE_OP, primitiveName, _arrayFn(ast.expressions.length), return this._addRecord(RecordType.PRIMITIVE_OP, primitiveName, _arrayFn(ast.expressions.length),
this._visitAll(ast.expressions), null, 0); this._visitAll(ast.expressions), null, 0);
} }
visitLiteralMap(ast: LiteralMap) { visitLiteralMap(ast: LiteralMap): number {
return this._addRecord(RecordType.PRIMITIVE_OP, _mapPrimitiveName(ast.keys), return this._addRecord(RecordType.PRIMITIVE_OP, _mapPrimitiveName(ast.keys),
ChangeDetectionUtil.mapFn(ast.keys), this._visitAll(ast.values), null, ChangeDetectionUtil.mapFn(ast.keys), this._visitAll(ast.values), null,
0); 0);
} }
visitBinary(ast: Binary) { visitBinary(ast: Binary): number {
var left = ast.left.visit(this); var left = ast.left.visit(this);
var right = ast.right.visit(this); var right = ast.right.visit(this);
return this._addRecord(RecordType.PRIMITIVE_OP, _operationToPrimitiveName(ast.operation), return this._addRecord(RecordType.PRIMITIVE_OP, _operationToPrimitiveName(ast.operation),
_operationToFunction(ast.operation), [left, right], null, 0); _operationToFunction(ast.operation), [left, right], null, 0);
} }
visitPrefixNot(ast: PrefixNot) { visitPrefixNot(ast: PrefixNot): number {
var exp = ast.expression.visit(this); var exp = ast.expression.visit(this);
return this._addRecord(RecordType.PRIMITIVE_OP, "operation_negate", return this._addRecord(RecordType.PRIMITIVE_OP, "operation_negate",
ChangeDetectionUtil.operation_negate, [exp], null, 0); ChangeDetectionUtil.operation_negate, [exp], null, 0);
} }
visitConditional(ast: Conditional) { visitConditional(ast: Conditional): number {
var c = ast.condition.visit(this); var c = ast.condition.visit(this);
var t = ast.trueExp.visit(this); var t = ast.trueExp.visit(this);
var f = ast.falseExp.visit(this); var f = ast.falseExp.visit(this);
@ -179,12 +179,12 @@ class _ConvertAstIntoProtoRecords implements AstVisitor {
null, 0); null, 0);
} }
visitPipe(ast: BindingPipe) { visitPipe(ast: BindingPipe): number {
var value = ast.exp.visit(this); var value = ast.exp.visit(this);
return this._addRecord(RecordType.PIPE, ast.name, ast.name, [], null, value); return this._addRecord(RecordType.PIPE, ast.name, ast.name, [], null, value);
} }
visitKeyedAccess(ast: KeyedAccess) { visitKeyedAccess(ast: KeyedAccess): number {
var obj = ast.obj.visit(this); var obj = ast.obj.visit(this);
var key = ast.key.visit(this); var key = ast.key.visit(this);
return this._addRecord(RecordType.KEYED_ACCESS, "keyedAccess", ChangeDetectionUtil.keyedAccess, return this._addRecord(RecordType.KEYED_ACCESS, "keyedAccess", ChangeDetectionUtil.keyedAccess,
@ -328,7 +328,7 @@ function _operationToFunction(operation: string): Function {
} }
} }
function s(v) { function s(v): string {
return isPresent(v) ? `${v}` : ''; return isPresent(v) ? `${v}` : '';
} }

View File

@ -42,7 +42,7 @@ export class Attribute extends DependencyAnnotation {
// account. // account.
return this; return this;
} }
toString() { return `@Attribute(${stringify(this.attributeName)})`; } toString(): string { return `@Attribute(${stringify(this.attributeName)})`; }
} }
/** /**
@ -67,5 +67,5 @@ export class Query extends DependencyAnnotation {
get varBindings(): List<string> { return StringWrapper.split(this.selector, new RegExp(",")); } get varBindings(): List<string> { return StringWrapper.split(this.selector, new RegExp(",")); }
toString() { return `@Query(${stringify(this.selector)})`; } toString(): string { return `@Query(${stringify(this.selector)})`; }
} }

View File

@ -326,7 +326,7 @@ export class ApplicationRef {
dispose() { dispose() {
// TODO: We also need to clean up the Zone, ... here! // TODO: We also need to clean up the Zone, ... here!
return this._hostComponent.dispose(); this._hostComponent.dispose();
} }
get injector() { return this._injector; } get injector() { return this._injector; }

View File

@ -14,7 +14,7 @@ export class BaseQueryList<T> {
protected _callbacks = []; protected _callbacks = [];
protected _dirty = false; protected _dirty = false;
[Symbol.iterator]() { return this._results[Symbol.iterator](); } [Symbol.iterator](): any { return this._results[Symbol.iterator](); }
reset(newList) { reset(newList) {
this._results = newList; this._results = newList;
@ -33,9 +33,9 @@ export class BaseQueryList<T> {
} }
} }
onChange(callback) { this._callbacks.push(callback); } onChange(callback): void { this._callbacks.push(callback); }
removeCallback(callback) { ListWrapper.remove(this._callbacks, callback); } removeCallback(callback): void { ListWrapper.remove(this._callbacks, callback); }
get length() { return this._results.length; } get length() { return this._results.length; }
get first() { return ListWrapper.first(this._results); } get first() { return ListWrapper.first(this._results); }

View File

@ -19,11 +19,11 @@ export class ElementBinder {
} }
} }
hasStaticComponent() { hasStaticComponent(): boolean {
return isPresent(this.componentDirective) && isPresent(this.nestedProtoView); return isPresent(this.componentDirective) && isPresent(this.nestedProtoView);
} }
hasEmbeddedProtoView() { hasEmbeddedProtoView(): boolean {
return !isPresent(this.componentDirective) && isPresent(this.nestedProtoView); return !isPresent(this.componentDirective) && isPresent(this.nestedProtoView);
} }
} }

View File

@ -190,11 +190,13 @@ export class DirectiveDependency extends Dependency {
} }
static _attributeName(properties): string { static _attributeName(properties): string {
var p = ListWrapper.find(properties, (p) => p instanceof Attribute); var p = <Attribute>ListWrapper.find(properties, (p) => p instanceof Attribute);
return isPresent(p) ? p.attributeName : null; return isPresent(p) ? p.attributeName : null;
} }
static _query(properties) { return ListWrapper.find(properties, (p) => p instanceof Query); } static _query(properties): Query {
return <Query>ListWrapper.find(properties, (p) => p instanceof Query);
}
} }
export class DirectiveBinding extends ResolvedBinding { export class DirectiveBinding extends ResolvedBinding {
@ -292,7 +294,7 @@ export class PreBuiltObjects {
export class EventEmitterAccessor { export class EventEmitterAccessor {
constructor(public eventName: string, public getter: Function) {} constructor(public eventName: string, public getter: Function) {}
subscribe(view: viewModule.AppView, boundElementIndex: number, directive: Object) { subscribe(view: viewModule.AppView, boundElementIndex: number, directive: Object): Object {
var eventEmitter = this.getter(directive); var eventEmitter = this.getter(directive);
return ObservableWrapper.subscribe( return ObservableWrapper.subscribe(
eventEmitter, eventEmitter,
@ -303,7 +305,7 @@ export class EventEmitterAccessor {
export class HostActionAccessor { export class HostActionAccessor {
constructor(public methodName: string, public getter: Function) {} constructor(public methodName: string, public getter: Function) {}
subscribe(view: viewModule.AppView, boundElementIndex: number, directive: Object) { subscribe(view: viewModule.AppView, boundElementIndex: number, directive: Object): Object {
var eventEmitter = this.getter(directive); var eventEmitter = this.getter(directive);
return ObservableWrapper.subscribe( return ObservableWrapper.subscribe(
eventEmitter, eventEmitter,
@ -314,9 +316,9 @@ export class HostActionAccessor {
export class BindingData { export class BindingData {
constructor(public binding: ResolvedBinding, public visibility: number) {} constructor(public binding: ResolvedBinding, public visibility: number) {}
getKeyId() { return this.binding.key.id; } getKeyId(): number { return this.binding.key.id; }
createEventEmitterAccessors() { createEventEmitterAccessors(): List<EventEmitterAccessor> {
if (!(this.binding instanceof DirectiveBinding)) return []; if (!(this.binding instanceof DirectiveBinding)) return [];
var db = <DirectiveBinding>this.binding; var db = <DirectiveBinding>this.binding;
return ListWrapper.map(db.eventEmitters, eventConfig => { return ListWrapper.map(db.eventEmitters, eventConfig => {
@ -331,11 +333,11 @@ export class BindingData {
// short format: 'name' when fieldName and eventName are the same // short format: 'name' when fieldName and eventName are the same
fieldName = eventName = eventConfig; fieldName = eventName = eventConfig;
} }
return new EventEmitterAccessor(eventName, reflector.getter(fieldName)) return new EventEmitterAccessor(eventName, reflector.getter(fieldName));
}); });
} }
createHostActionAccessors() { createHostActionAccessors(): HostActionAccessor[] {
if (!(this.binding instanceof DirectiveBinding)) return []; if (!(this.binding instanceof DirectiveBinding)) return [];
var res = []; var res = [];
var db = <DirectiveBinding>this.binding; var db = <DirectiveBinding>this.binding;
@ -355,7 +357,7 @@ export class ProtoElementInjector {
static create(parent: ProtoElementInjector, index: number, bindings: List<ResolvedBinding>, static create(parent: ProtoElementInjector, index: number, bindings: List<ResolvedBinding>,
firstBindingIsComponent: boolean, distanceToParent: number, firstBindingIsComponent: boolean, distanceToParent: number,
directiveVariableBindings: Map<string, number>) { directiveVariableBindings: Map<string, number>): ProtoElementInjector {
var bd = []; var bd = [];
ProtoElementInjector._createDirectiveBindingData(bindings, bd, firstBindingIsComponent); ProtoElementInjector._createDirectiveBindingData(bindings, bd, firstBindingIsComponent);
@ -808,7 +810,7 @@ export class ElementInjector extends TreeNode<ElementInjector> {
} }
} }
getDirectiveAtIndex(index: number) { return this._injector.getObjAtIndex(index); } getDirectiveAtIndex(index: number): any { return this._injector.getObjAtIndex(index); }
hasInstances(): boolean { return this._proto.hasBindings && this.hydrated; } hasInstances(): boolean { return this._proto.hasBindings && this.hydrated; }

View File

@ -286,12 +286,14 @@ function _collectNestedProtoViewsVariableNames(
return nestedPvVariableNames; return nestedPvVariableNames;
} }
function _createVariableNames(parentVariableNames, renderProtoView): List<string> { function _createVariableNames(parentVariableNames: List<string>, renderProtoView): List<string> {
var res = isBlank(parentVariableNames) ? [] : ListWrapper.clone(parentVariableNames); var res =
isBlank(parentVariableNames) ? <List<string>>[] : ListWrapper.clone(parentVariableNames);
MapWrapper.forEach(renderProtoView.variableBindings, MapWrapper.forEach(renderProtoView.variableBindings,
(mappedName, varName) => { res.push(mappedName); }); (mappedName, varName) => { res.push(mappedName); });
ListWrapper.forEach(renderProtoView.elementBinders, binder => { ListWrapper.forEach(renderProtoView.elementBinders, binder => {
MapWrapper.forEach(binder.variableBindings, (mappedName, varName) => { res.push(mappedName); }); MapWrapper.forEach(binder.variableBindings,
(mappedName: string, varName: string) => { res.push(mappedName); });
}); });
return res; return res;
} }

View File

@ -78,9 +78,9 @@ import {BaseQueryList} from './base_query_list';
export class QueryList<T> extends BaseQueryList<T> { export class QueryList<T> extends BaseQueryList<T> {
/** /**
*/ */
onChange(callback) { return super.onChange(callback); } onChange(callback) { super.onChange(callback); }
/** /**
*/ */
removeCallback(callback) { return super.removeCallback(callback); } removeCallback(callback) { super.removeCallback(callback); }
} }

View File

@ -134,12 +134,12 @@ export class AppView implements ChangeDispatcher, EventDispatcher {
} }
} }
getDirectiveFor(directive: DirectiveIndex) { getDirectiveFor(directive: DirectiveIndex): any {
var elementInjector = this.elementInjectors[directive.elementIndex]; var elementInjector = this.elementInjectors[directive.elementIndex];
return elementInjector.getDirectiveAtIndex(directive.directiveIndex); return elementInjector.getDirectiveAtIndex(directive.directiveIndex);
} }
getDetectorFor(directive: DirectiveIndex) { getDetectorFor(directive: DirectiveIndex): any {
var childView = this.componentChildViews[directive.elementIndex]; var childView = this.componentChildViews[directive.elementIndex];
return isPresent(childView) ? childView.changeDetector : null; return isPresent(childView) ? childView.changeDetector : null;
} }

View File

@ -42,7 +42,9 @@ export class ViewContainerRef {
return this.viewManager.attachViewInContainer(this.element, atIndex, viewRef); return this.viewManager.attachViewInContainer(this.element, atIndex, viewRef);
} }
indexOf(viewRef: ViewRef) { return ListWrapper.indexOf(this._getViews(), internalView(viewRef)); } indexOf(viewRef: ViewRef): number {
return ListWrapper.indexOf(this._getViews(), internalView(viewRef));
}
remove(atIndex: number = -1): void { remove(atIndex: number = -1): void {
if (atIndex == -1) atIndex = this.length - 1; if (atIndex == -1) atIndex = this.length - 1;

View File

@ -8,7 +8,7 @@ class PublicTestability {
whenStable(callback: Function) { this._testability.whenStable(callback); } whenStable(callback: Function) { this._testability.whenStable(callback); }
findBindings(using, binding: string, exactMatch: boolean) { findBindings(using, binding: string, exactMatch: boolean): List<any> {
return this._testability.findBindings(using, binding, exactMatch); return this._testability.findBindings(using, binding, exactMatch);
} }
} }

View File

@ -20,7 +20,7 @@ export class Testability {
this._callbacks = []; this._callbacks = [];
} }
increaseCount(delta: number = 1) { increaseCount(delta: number = 1): number {
this._pendingCount += delta; this._pendingCount += delta;
if (this._pendingCount < 0) { if (this._pendingCount < 0) {
throw new BaseException('pending async requests below zero'); throw new BaseException('pending async requests below zero');

View File

@ -103,7 +103,7 @@ export class NgZone {
* }); * });
* ``` * ```
*/ */
run(fn) { run(fn): any {
if (this._disabled) { if (this._disabled) {
return fn(); return fn();
} else { } else {
@ -127,7 +127,7 @@ export class NgZone {
* }); * });
* ``` * ```
*/ */
runOutsideAngular(fn) { runOutsideAngular(fn): any {
if (this._disabled) { if (this._disabled) {
return fn(); return fn();
} else { } else {

View File

@ -1,5 +1,5 @@
import {Type, isPresent, BaseException, isBlank} from 'angular2/src/facade/lang'; import {Type, isPresent, BaseException, isBlank} from 'angular2/src/facade/lang';
import {List, ListWrapper, MapWrapper} from 'angular2/src/facade/collection'; import {List, ListWrapper, MapWrapper, Predicate} from 'angular2/src/facade/collection';
import {DOM} from 'angular2/src/dom/dom_adapter'; import {DOM} from 'angular2/src/dom/dom_adapter';
@ -90,7 +90,7 @@ export class DebugElement {
getLocal(name: string): any { return this._parentView.locals.get(name); } getLocal(name: string): any { return this._parentView.locals.get(name); }
/** /**
* Return the first descendant TestElememt matching the given predicate * Return the first descendant TestElement matching the given predicate
* and scope. * and scope.
* *
* @param {Function: boolean} predicate * @param {Function: boolean} predicate
@ -98,7 +98,7 @@ export class DebugElement {
* *
* @return {DebugElement} * @return {DebugElement}
*/ */
query(predicate: Function, scope = Scope.all): DebugElement { query(predicate: Predicate<DebugElement>, scope = Scope.all): DebugElement {
var results = this.queryAll(predicate, scope); var results = this.queryAll(predicate, scope);
return results.length > 0 ? results[0] : null; return results.length > 0 ? results[0] : null;
} }
@ -112,7 +112,7 @@ export class DebugElement {
* *
* @return {List<DebugElement>} * @return {List<DebugElement>}
*/ */
queryAll(predicate: Function, scope = Scope.all): List<DebugElement> { queryAll(predicate: Predicate<DebugElement>, scope = Scope.all): List<DebugElement> {
var elementsInScope = scope(this); var elementsInScope = scope(this);
return ListWrapper.filter(elementsInScope, predicate); return ListWrapper.filter(elementsInScope, predicate);
@ -191,10 +191,10 @@ export class Scope {
export class By { export class By {
static all(): Function { return (debugElement) => true; } static all(): Function { return (debugElement) => true; }
static css(selector: string): Function { static css(selector: string): Predicate<DebugElement> {
return (debugElement) => { return DOM.elementMatches(debugElement.nativeElement, selector); }; return (debugElement) => { return DOM.elementMatches(debugElement.nativeElement, selector); };
} }
static directive(type: Type): Function { static directive(type: Type): Predicate<DebugElement> {
return (debugElement) => { return debugElement.hasDirective(type); }; return (debugElement) => { return debugElement.hasDirective(type); };
} }
} }

View File

@ -29,7 +29,9 @@ export class Dependency {
constructor(public key: Key, public optional: boolean, public visibility: Visibility, constructor(public key: Key, public optional: boolean, public visibility: Visibility,
public properties: List<any>) {} public properties: List<any>) {}
static fromKey(key: Key) { return new Dependency(key, false, _defaulVisiblity(key.token), []); } static fromKey(key: Key): Dependency {
return new Dependency(key, false, _defaulVisiblity(key.token), []);
}
} }
const _EMPTY_LIST = CONST_EXPR([]); const _EMPTY_LIST = CONST_EXPR([]);

View File

@ -91,7 +91,8 @@ export class NgFor {
view.setLocal('index', record.currentIndex); view.setLocal('index', record.currentIndex);
} }
static bulkRemove(tuples, viewContainer) { static bulkRemove(tuples: List<RecordViewTuple>,
viewContainer: ViewContainerRef): List<RecordViewTuple> {
tuples.sort((a, b) => a.record.previousIndex - b.record.previousIndex); tuples.sort((a, b) => a.record.previousIndex - b.record.previousIndex);
var movedTuples = []; var movedTuples = [];
for (var i = tuples.length - 1; i >= 0; i--) { for (var i = tuples.length - 1; i >= 0; i--) {
@ -107,7 +108,8 @@ export class NgFor {
return movedTuples; return movedTuples;
} }
static bulkInsert(tuples, viewContainer: ViewContainerRef, protoViewRef: ProtoViewRef) { static bulkInsert(tuples: List<RecordViewTuple>, viewContainer: ViewContainerRef,
protoViewRef: ProtoViewRef): List<RecordViewTuple> {
tuples.sort((a, b) => a.record.currentIndex - b.record.currentIndex); tuples.sort((a, b) => a.record.currentIndex - b.record.currentIndex);
for (var i = 0; i < tuples.length; i++) { for (var i = 0; i < tuples.length; i++) {
var tuple = tuples[i]; var tuple = tuples[i];

View File

@ -50,7 +50,7 @@ var _chromeNumKeyPadMap = {
export class BrowserDomAdapter extends GenericBrowserDomAdapter { export class BrowserDomAdapter extends GenericBrowserDomAdapter {
static makeCurrent() { setRootDomAdapter(new BrowserDomAdapter()); } static makeCurrent() { setRootDomAdapter(new BrowserDomAdapter()); }
hasProperty(element, name: string) { return name in element; } hasProperty(element, name: string): boolean { return name in element; }
setProperty(el: /*element*/ any, name: string, value: any) { el[name] = value; } setProperty(el: /*element*/ any, name: string, value: any) { el[name] = value; }
getProperty(el: /*element*/ any, name: string): any { return el[name]; } getProperty(el: /*element*/ any, name: string): any { return el[name]; }
invoke(el: /*element*/ any, methodName: string, args: List<any>): any { invoke(el: /*element*/ any, methodName: string, args: List<any>): any {
@ -87,8 +87,8 @@ export class BrowserDomAdapter extends GenericBrowserDomAdapter {
evt.preventDefault(); evt.preventDefault();
evt.returnValue = false; evt.returnValue = false;
} }
getInnerHTML(el) { return el.innerHTML; } getInnerHTML(el): string { return el.innerHTML; }
getOuterHTML(el) { return el.outerHTML; } getOuterHTML(el): string { return el.outerHTML; }
nodeName(node: Node): string { return node.nodeName; } nodeName(node: Node): string { return node.nodeName; }
nodeValue(node: Node): string { return node.nodeValue; } nodeValue(node: Node): string { return node.nodeValue; }
type(node: HTMLInputElement): string { return node.type; } type(node: HTMLInputElement): string { return node.type; }
@ -101,7 +101,7 @@ export class BrowserDomAdapter extends GenericBrowserDomAdapter {
} }
firstChild(el): Node { return el.firstChild; } firstChild(el): Node { return el.firstChild; }
nextSibling(el): Node { return el.nextSibling; } nextSibling(el): Node { return el.nextSibling; }
parentElement(el) { return el.parentElement; } parentElement(el): Node { return el.parentElement; }
childNodes(el): List<Node> { return el.childNodes; } childNodes(el): List<Node> { return el.childNodes; }
childNodesAsList(el): List<any> { childNodesAsList(el): List<any> {
var childNodes = el.childNodes; var childNodes = el.childNodes;
@ -119,7 +119,7 @@ export class BrowserDomAdapter extends GenericBrowserDomAdapter {
appendChild(el, node) { el.appendChild(node); } appendChild(el, node) { el.appendChild(node); }
removeChild(el, node) { el.removeChild(node); } removeChild(el, node) { el.removeChild(node); }
replaceChild(el: Node, newChild, oldChild) { el.replaceChild(newChild, oldChild); } replaceChild(el: Node, newChild, oldChild) { el.replaceChild(newChild, oldChild); }
remove(el) { remove(el): Node {
var parent = el.parentNode; var parent = el.parentNode;
parent.removeChild(el); parent.removeChild(el);
return el; return el;
@ -130,12 +130,12 @@ export class BrowserDomAdapter extends GenericBrowserDomAdapter {
} }
insertAfter(el, node) { el.parentNode.insertBefore(node, el.nextSibling); } insertAfter(el, node) { el.parentNode.insertBefore(node, el.nextSibling); }
setInnerHTML(el, value) { el.innerHTML = value; } setInnerHTML(el, value) { el.innerHTML = value; }
getText(el) { return el.textContent; } getText(el): string { return el.textContent; }
// TODO(vicb): removed Element type because it does not support StyleElement // TODO(vicb): removed Element type because it does not support StyleElement
setText(el, value: string) { el.textContent = value; } setText(el, value: string) { el.textContent = value; }
getValue(el) { return el.value; } getValue(el): string { return el.value; }
setValue(el, value: string) { el.value = value; } setValue(el, value: string) { el.value = value; }
getChecked(el) { return el.checked; } getChecked(el): boolean { return el.checked; }
setChecked(el, value: boolean) { el.checked = value; } setChecked(el, value: boolean) { el.checked = value; }
createTemplate(html): HTMLElement { createTemplate(html): HTMLElement {
var t = document.createElement('template'); var t = document.createElement('template');
@ -157,22 +157,26 @@ export class BrowserDomAdapter extends GenericBrowserDomAdapter {
createShadowRoot(el: HTMLElement): DocumentFragment { return (<any>el).createShadowRoot(); } createShadowRoot(el: HTMLElement): DocumentFragment { return (<any>el).createShadowRoot(); }
getShadowRoot(el: HTMLElement): DocumentFragment { return (<any>el).shadowRoot; } getShadowRoot(el: HTMLElement): DocumentFragment { return (<any>el).shadowRoot; }
getHost(el: HTMLElement): HTMLElement { return (<any>el).host; } getHost(el: HTMLElement): HTMLElement { return (<any>el).host; }
clone(node: Node) { return node.cloneNode(true); } clone(node: Node): Node { return node.cloneNode(true); }
getElementsByClassName(element, name: string) { return element.getElementsByClassName(name); } getElementsByClassName(element, name: string): List<HTMLElement> {
getElementsByTagName(element, name: string) { return element.getElementsByTagName(name); } return element.getElementsByClassName(name);
}
getElementsByTagName(element, name: string): List<HTMLElement> {
return element.getElementsByTagName(name);
}
classList(element): List<any> { classList(element): List<any> {
return <List<any>>Array.prototype.slice.call(element.classList, 0); return <List<any>>Array.prototype.slice.call(element.classList, 0);
} }
addClass(element, classname: string) { element.classList.add(classname); } addClass(element, classname: string) { element.classList.add(classname); }
removeClass(element, classname: string) { element.classList.remove(classname); } removeClass(element, classname: string) { element.classList.remove(classname); }
hasClass(element, classname: string) { return element.classList.contains(classname); } hasClass(element, classname: string): boolean { return element.classList.contains(classname); }
setStyle(element, stylename: string, stylevalue: string) { setStyle(element, stylename: string, stylevalue: string) {
element.style[stylename] = stylevalue; element.style[stylename] = stylevalue;
} }
removeStyle(element, stylename: string) { element.style[stylename] = null; } removeStyle(element, stylename: string) { element.style[stylename] = null; }
getStyle(element, stylename: string) { return element.style[stylename]; } getStyle(element, stylename: string): string { return element.style[stylename]; }
tagName(element): string { return element.tagName; } tagName(element): string { return element.tagName; }
attributeMap(element) { attributeMap(element): Map<string, string> {
var res = new Map(); var res = new Map();
var elAttrs = element.attributes; var elAttrs = element.attributes;
for (var i = 0; i < elAttrs.length; i++) { for (var i = 0; i < elAttrs.length; i++) {
@ -181,14 +185,16 @@ export class BrowserDomAdapter extends GenericBrowserDomAdapter {
} }
return res; return res;
} }
hasAttribute(element, attribute: string) { return element.hasAttribute(attribute); } hasAttribute(element, attribute: string): boolean { return element.hasAttribute(attribute); }
getAttribute(element, attribute: string) { return element.getAttribute(attribute); } getAttribute(element, attribute: string): string { return element.getAttribute(attribute); }
setAttribute(element, name: string, value: string) { element.setAttribute(name, value); } setAttribute(element, name: string, value: string) { element.setAttribute(name, value); }
removeAttribute(element, attribute: string) { return element.removeAttribute(attribute); } removeAttribute(element, attribute: string) { element.removeAttribute(attribute); }
templateAwareRoot(el) { return this.isTemplateElement(el) ? this.content(el) : el; } templateAwareRoot(el): any { return this.isTemplateElement(el) ? this.content(el) : el; }
createHtmlDocument() { return document.implementation.createHTMLDocument('fakeTitle'); } createHtmlDocument(): HTMLDocument {
defaultDoc() { return document; } return document.implementation.createHTMLDocument('fakeTitle');
getBoundingClientRect(el) { }
defaultDoc(): HTMLDocument { return document; }
getBoundingClientRect(el): any {
try { try {
return el.getBoundingClientRect(); return el.getBoundingClientRect();
} catch (e) { } catch (e) {
@ -209,7 +215,7 @@ export class BrowserDomAdapter extends GenericBrowserDomAdapter {
isElementNode(node: Node): boolean { return node.nodeType === Node.ELEMENT_NODE; } isElementNode(node: Node): boolean { return node.nodeType === Node.ELEMENT_NODE; }
hasShadowRoot(node): boolean { return node instanceof HTMLElement && isPresent(node.shadowRoot); } hasShadowRoot(node): boolean { return node instanceof HTMLElement && isPresent(node.shadowRoot); }
isShadowRoot(node): boolean { return node instanceof DocumentFragment; } isShadowRoot(node): boolean { return node instanceof DocumentFragment; }
importIntoDoc(node: Node) { importIntoDoc(node: Node): any {
var toImport = node; var toImport = node;
if (this.isTemplateElement(node)) { if (this.isTemplateElement(node)) {
toImport = this.content(node); toImport = this.content(node);
@ -256,9 +262,9 @@ export class BrowserDomAdapter extends GenericBrowserDomAdapter {
return document.body; return document.body;
} }
} }
getHistory() { return window.history; } getHistory(): History { return window.history; }
getLocation() { return window.location; } getLocation(): Location { return window.location; }
getBaseHref() { return relativePath(document.baseURI); } getBaseHref(): string { return relativePath(document.baseURI); }
getUserAgent(): string { return window.navigator.userAgent; } getUserAgent(): string { return window.navigator.userAgent; }
setData(element, name: string, value: string) { element.dataset[name] = value; } setData(element, name: string, value: string) { element.dataset[name] = value; }
getData(element, name: string): string { return element.dataset[name]; } getData(element, name: string): string { return element.dataset[name]; }
@ -268,7 +274,7 @@ export class BrowserDomAdapter extends GenericBrowserDomAdapter {
// based on urlUtils.js in AngularJS 1 // based on urlUtils.js in AngularJS 1
var urlParsingNode = null; var urlParsingNode = null;
function relativePath(url) { function relativePath(url): string {
if (isBlank(urlParsingNode)) { if (isBlank(urlParsingNode)) {
urlParsingNode = document.createElement("a"); urlParsingNode = document.createElement("a");
} }

View File

@ -17,9 +17,11 @@ function _abstract() {
*/ */
export class DomAdapter { export class DomAdapter {
hasProperty(element, name: string): boolean { throw _abstract(); } hasProperty(element, name: string): boolean { throw _abstract(); }
setProperty(el: /*element*/ any, name: string, value: any) { throw _abstract(); } setProperty(el: /*(#2770) Element*/ any, name: string, value: any) { throw _abstract(); }
getProperty(el: /*element*/ any, name: string): any { throw _abstract(); } getProperty(el: /*(#2770) Element*/ any, name: string): any { throw _abstract(); }
invoke(el: /*element*/ any, methodName: string, args: List<any>): any { throw _abstract(); } invoke(el: /*(#2770) Element*/ any, methodName: string, args: List<any>): any {
throw _abstract();
}
logError(error) { throw _abstract(); } logError(error) { throw _abstract(); }
@ -45,45 +47,53 @@ export class DomAdapter {
nodeValue(node): string { throw _abstract(); } nodeValue(node): string { throw _abstract(); }
type(node): string { throw _abstract(); } type(node): string { throw _abstract(); }
content(node): any { throw _abstract(); } content(node): any { throw _abstract(); }
firstChild(el): any { throw _abstract(); } firstChild(el): /*(#2770) Node*/ any { throw _abstract(); }
nextSibling(el): any { throw _abstract(); } nextSibling(el): /*(#2770) Node*/ any { throw _abstract(); }
parentElement(el): any { throw _abstract(); } parentElement(el): /*(#2770) Node*/ any { throw _abstract(); }
childNodes(el): List<any> { throw _abstract(); } childNodes(el): List</*(#2770) Node*/ any> { throw _abstract(); }
childNodesAsList(el): List<any> { throw _abstract(); } childNodesAsList(el): List</*(#2770) Node*/ any> { throw _abstract(); }
clearNodes(el) { throw _abstract(); } clearNodes(el) { throw _abstract(); }
appendChild(el, node) { throw _abstract(); } appendChild(el, node) { throw _abstract(); }
removeChild(el, node) { throw _abstract(); } removeChild(el, node) { throw _abstract(); }
replaceChild(el, newNode, oldNode) { throw _abstract(); } replaceChild(el, newNode, oldNode) { throw _abstract(); }
remove(el) { throw _abstract(); } remove(el): /*(#2770) Node*/ any { throw _abstract(); }
insertBefore(el, node) { throw _abstract(); } insertBefore(el, node) { throw _abstract(); }
insertAllBefore(el, nodes) { throw _abstract(); } insertAllBefore(el, nodes) { throw _abstract(); }
insertAfter(el, node) { throw _abstract(); } insertAfter(el, node) { throw _abstract(); }
setInnerHTML(el, value) { throw _abstract(); } setInnerHTML(el, value) { throw _abstract(); }
getText(el): any { throw _abstract(); } getText(el): string { throw _abstract(); }
setText(el, value: string) { throw _abstract(); } setText(el, value: string) { throw _abstract(); }
getValue(el): any { throw _abstract(); } getValue(el): string { throw _abstract(); }
setValue(el, value: string) { throw _abstract(); } setValue(el, value: string) { throw _abstract(); }
getChecked(el): any { throw _abstract(); } getChecked(el): boolean { throw _abstract(); }
setChecked(el, value: boolean) { throw _abstract(); } setChecked(el, value: boolean) { throw _abstract(); }
createTemplate(html): any { throw _abstract(); } createTemplate(html): /*(#2770) HTMLElement*/ any { throw _abstract(); }
createElement(tagName, doc = null): any { throw _abstract(); } createElement(tagName, doc = null): /*(#2770) HTMLElement*/ any { throw _abstract(); }
createTextNode(text: string, doc = null): any { throw _abstract(); } createTextNode(text: string, doc = null): /*(#2770) Text*/ any { throw _abstract(); }
createScriptTag(attrName: string, attrValue: string, doc = null): any { throw _abstract(); } createScriptTag(attrName: string, attrValue: string, doc = null): /*(#2770) HTMLElement*/ any {
createStyleElement(css: string, doc = null): any { throw _abstract(); } throw _abstract();
}
createStyleElement(css: string, doc = null): /*(#2770) HTMLStyleElement*/ any {
throw _abstract();
}
createShadowRoot(el): any { throw _abstract(); } createShadowRoot(el): any { throw _abstract(); }
getShadowRoot(el): any { throw _abstract(); } getShadowRoot(el): any { throw _abstract(); }
getHost(el): any { throw _abstract(); } getHost(el): any { throw _abstract(); }
getDistributedNodes(el): List<any> { throw _abstract(); } getDistributedNodes(el): List</*(#2770) Node*/ any> { throw _abstract(); }
clone(node): any { throw _abstract(); } clone(node: /*(#2770) Node*/ any): /*(#2770) Node*/ any { throw _abstract(); }
getElementsByClassName(element, name: string): List<any> { throw _abstract(); } getElementsByClassName(element, name: string): List</*(#2770) HTMLElement*/ any> {
getElementsByTagName(element, name: string): List<any> { throw _abstract(); } throw _abstract();
}
getElementsByTagName(element, name: string): List</*(#2770) HTMLElement*/ any> {
throw _abstract();
}
classList(element): List<any> { throw _abstract(); } classList(element): List<any> { throw _abstract(); }
addClass(element, classname: string) { throw _abstract(); } addClass(element, classname: string) { throw _abstract(); }
removeClass(element, classname: string) { throw _abstract(); } removeClass(element, classname: string) { throw _abstract(); }
hasClass(element, classname: string) { throw _abstract(); } hasClass(element, classname: string): boolean { throw _abstract(); }
setStyle(element, stylename: string, stylevalue: string) { throw _abstract(); } setStyle(element, stylename: string, stylevalue: string) { throw _abstract(); }
removeStyle(element, stylename: string) { throw _abstract(); } removeStyle(element, stylename: string) { throw _abstract(); }
getStyle(element, stylename: string) { throw _abstract(); } getStyle(element, stylename: string): string { throw _abstract(); }
tagName(element): string { throw _abstract(); } tagName(element): string { throw _abstract(); }
attributeMap(element): Map<string, string> { throw _abstract(); } attributeMap(element): Map<string, string> { throw _abstract(); }
hasAttribute(element, attribute: string): boolean { throw _abstract(); } hasAttribute(element, attribute: string): boolean { throw _abstract(); }
@ -91,8 +101,8 @@ export class DomAdapter {
setAttribute(element, name: string, value: string) { throw _abstract(); } setAttribute(element, name: string, value: string) { throw _abstract(); }
removeAttribute(element, attribute: string) { throw _abstract(); } removeAttribute(element, attribute: string) { throw _abstract(); }
templateAwareRoot(el) { throw _abstract(); } templateAwareRoot(el) { throw _abstract(); }
createHtmlDocument() { throw _abstract(); } createHtmlDocument(): /*(#2770) HTMLDocument*/ any { throw _abstract(); }
defaultDoc(): any { throw _abstract(); } defaultDoc(): /*(#2770) HTMLDocument*/ any { throw _abstract(); }
getBoundingClientRect(el) { throw _abstract(); } getBoundingClientRect(el) { throw _abstract(); }
getTitle(): string { throw _abstract(); } getTitle(): string { throw _abstract(); }
setTitle(newTitle: string) { throw _abstract(); } setTitle(newTitle: string) { throw _abstract(); }
@ -115,8 +125,8 @@ export class DomAdapter {
supportsDOMEvents(): boolean { throw _abstract(); } supportsDOMEvents(): boolean { throw _abstract(); }
supportsNativeShadowDOM(): boolean { throw _abstract(); } supportsNativeShadowDOM(): boolean { throw _abstract(); }
getGlobalEventTarget(target: string): any { throw _abstract(); } getGlobalEventTarget(target: string): any { throw _abstract(); }
getHistory(): any { throw _abstract(); } getHistory(): /*(#2770) History*/ any { throw _abstract(); }
getLocation(): any { throw _abstract(); } getLocation(): /*(#2770) Location*/ any { throw _abstract(); }
getBaseHref(): string { throw _abstract(); } getBaseHref(): string { throw _abstract(); }
getUserAgent(): string { throw _abstract(); } getUserAgent(): string { throw _abstract(); }
setData(element, name: string, value: string) { throw _abstract(); } setData(element, name: string, value: string) { throw _abstract(); }

View File

@ -6,7 +6,7 @@ import {DomAdapter} from './dom_adapter';
* Provides DOM operations in any browser environment. * Provides DOM operations in any browser environment.
*/ */
export class GenericBrowserDomAdapter extends DomAdapter { export class GenericBrowserDomAdapter extends DomAdapter {
getDistributedNodes(el) { return el.getDistributedNodes(); } getDistributedNodes(el): List</*(#2770) Node*/ any> { return el.getDistributedNodes(); }
resolveAndSetHref(el, baseUrl: string, href: string) { resolveAndSetHref(el, baseUrl: string, href: string) {
el.href = href == null ? baseUrl : baseUrl + '/../' + href; el.href = href == null ? baseUrl : baseUrl + '/../' + href;
} }
@ -19,7 +19,7 @@ export class GenericBrowserDomAdapter extends DomAdapter {
// with an @import // with an @import
// https://bugzilla.mozilla.org/show_bug.cgi?id=625013 // https://bugzilla.mozilla.org/show_bug.cgi?id=625013
try { try {
var rawRules = style.sheet.cssRules; var rawRules = (<any>style.sheet).cssRules;
rules = ListWrapper.createFixedSize(rawRules.length); rules = ListWrapper.createFixedSize(rawRules.length);
for (var i = 0; i < rawRules.length; i++) { for (var i = 0; i < rawRules.length; i++) {
rules[i] = rawRules[i]; rules[i] = rawRules[i];
@ -34,5 +34,7 @@ export class GenericBrowserDomAdapter extends DomAdapter {
return rules; return rules;
} }
supportsDOMEvents(): boolean { return true; } supportsDOMEvents(): boolean { return true; }
supportsNativeShadowDOM(): boolean { return isFunction(this.defaultDoc().body.createShadowRoot); } supportsNativeShadowDOM(): boolean {
return isFunction((<any>this.defaultDoc().body).createShadowRoot);
}
} }

View File

@ -26,7 +26,9 @@ function _notImplemented(methodName) {
export class Parse5DomAdapter extends DomAdapter { export class Parse5DomAdapter extends DomAdapter {
static makeCurrent() { setRootDomAdapter(new Parse5DomAdapter()); } static makeCurrent() { setRootDomAdapter(new Parse5DomAdapter()); }
hasProperty(element, name: string) { return _HTMLElementPropertyList.indexOf(name) > -1; } hasProperty(element, name: string): boolean {
return _HTMLElementPropertyList.indexOf(name) > -1;
}
// TODO(tbosch): don't even call this method when we run the tests on server side // TODO(tbosch): don't even call this method when we run the tests on server side
// by not using the DomRenderer in tests. Keeping this for now to make tests happy... // by not using the DomRenderer in tests. Keeping this for now to make tests happy...
setProperty(el: /*element*/ any, name: string, value: any) { setProperty(el: /*element*/ any, name: string, value: any) {
@ -45,8 +47,8 @@ export class Parse5DomAdapter extends DomAdapter {
get attrToPropMap() { return _attrToPropMap; } get attrToPropMap() { return _attrToPropMap; }
query(selector) { throw _notImplemented('query'); } query(selector) { throw _notImplemented('query'); }
querySelector(el, selector: string) { return this.querySelectorAll(el, selector)[0]; } querySelector(el, selector: string): any { return this.querySelectorAll(el, selector)[0]; }
querySelectorAll(el, selector: string) { querySelectorAll(el, selector: string): List<any> {
var res = []; var res = [];
var _recursive = (result, node, selector, matcher) => { var _recursive = (result, node, selector, matcher) => {
var cNodes = node.childNodes; var cNodes = node.childNodes;
@ -130,18 +132,18 @@ export class Parse5DomAdapter extends DomAdapter {
this.dispatchEvent(el._window, evt); this.dispatchEvent(el._window, evt);
} }
} }
createMouseEvent(eventType) { return this.createEvent(eventType); } createMouseEvent(eventType): Event { return this.createEvent(eventType); }
createEvent(eventType) { createEvent(eventType: string): Event {
var evt = { var evt = <Event>{
type: eventType, type: eventType,
defaultPrevented: false, defaultPrevented: false,
preventDefault: () => { evt.defaultPrevented = true } preventDefault: () => { evt.defaultPrevented = true; }
}; };
return evt; return evt;
} }
preventDefault(evt) { evt.returnValue = false; } preventDefault(evt) { evt.returnValue = false; }
getInnerHTML(el) { return serializer.serialize(this.templateAwareRoot(el)); } getInnerHTML(el): string { return serializer.serialize(this.templateAwareRoot(el)); }
getOuterHTML(el) { getOuterHTML(el): string {
serializer.html = ''; serializer.html = '';
serializer._serializeElement(el); serializer._serializeElement(el);
return serializer.html; return serializer.html;
@ -149,11 +151,11 @@ export class Parse5DomAdapter extends DomAdapter {
nodeName(node): string { return node.tagName; } nodeName(node): string { return node.tagName; }
nodeValue(node): string { return node.nodeValue; } nodeValue(node): string { return node.nodeValue; }
type(node: any): string { throw _notImplemented('type'); } type(node: any): string { throw _notImplemented('type'); }
content(node) { return node.childNodes[0]; } content(node): string { return node.childNodes[0]; }
firstChild(el) { return el.firstChild; } firstChild(el): Node { return el.firstChild; }
nextSibling(el) { return el.nextSibling; } nextSibling(el): Node { return el.nextSibling; }
parentElement(el) { return el.parent; } parentElement(el): Node { return el.parent; }
childNodes(el) { return el.childNodes; } childNodes(el): Node[] { return el.childNodes; }
childNodesAsList(el): List<any> { childNodesAsList(el): List<any> {
var childNodes = el.childNodes; var childNodes = el.childNodes;
var res = ListWrapper.createFixedSize(childNodes.length); var res = ListWrapper.createFixedSize(childNodes.length);
@ -176,7 +178,7 @@ export class Parse5DomAdapter extends DomAdapter {
this.remove(node); this.remove(node);
} }
} }
remove(el) { remove(el): HTMLElement {
var parent = el.parent; var parent = el.parent;
if (parent) { if (parent) {
var index = parent.childNodes.indexOf(el); var index = parent.childNodes.indexOf(el);
@ -216,7 +218,7 @@ export class Parse5DomAdapter extends DomAdapter {
treeAdapter.appendChild(el, content.childNodes[i]); treeAdapter.appendChild(el, content.childNodes[i]);
} }
} }
getText(el) { getText(el): string {
if (this.isTextNode(el)) { if (this.isTextNode(el)) {
return el.data; return el.data;
} else if (isBlank(el.childNodes) || el.childNodes.length == 0) { } else if (isBlank(el.childNodes) || el.childNodes.length == 0) {
@ -237,40 +239,40 @@ export class Parse5DomAdapter extends DomAdapter {
if (value !== '') treeAdapter.insertText(el, value); if (value !== '') treeAdapter.insertText(el, value);
} }
} }
getValue(el) { return el.value; } getValue(el): string { return el.value; }
setValue(el, value: string) { el.value = value; } setValue(el, value: string) { el.value = value; }
getChecked(el) { return el.checked; } getChecked(el): boolean { return el.checked; }
setChecked(el, value: boolean) { el.checked = value; } setChecked(el, value: boolean) { el.checked = value; }
createTemplate(html) { createTemplate(html): HTMLElement {
var template = treeAdapter.createElement("template", 'http://www.w3.org/1999/xhtml', []); var template = treeAdapter.createElement("template", 'http://www.w3.org/1999/xhtml', []);
var content = parser.parseFragment(html); var content = parser.parseFragment(html);
treeAdapter.appendChild(template, content); treeAdapter.appendChild(template, content);
return template; return template;
} }
createElement(tagName) { createElement(tagName): HTMLElement {
return treeAdapter.createElement(tagName, 'http://www.w3.org/1999/xhtml', []); return treeAdapter.createElement(tagName, 'http://www.w3.org/1999/xhtml', []);
} }
createTextNode(text: string) { throw _notImplemented('createTextNode'); } createTextNode(text: string): Text { throw _notImplemented('createTextNode'); }
createScriptTag(attrName: string, attrValue: string) { createScriptTag(attrName: string, attrValue: string): HTMLElement {
return treeAdapter.createElement("script", 'http://www.w3.org/1999/xhtml', return treeAdapter.createElement("script", 'http://www.w3.org/1999/xhtml',
[{name: attrName, value: attrValue}]); [{name: attrName, value: attrValue}]);
} }
createStyleElement(css: string) { createStyleElement(css: string): HTMLStyleElement {
var style = this.createElement('style'); var style = this.createElement('style');
this.setText(style, css); this.setText(style, css);
return style; return <HTMLStyleElement>style;
} }
createShadowRoot(el) { createShadowRoot(el): HTMLElement {
el.shadowRoot = treeAdapter.createDocumentFragment(); el.shadowRoot = treeAdapter.createDocumentFragment();
el.shadowRoot.parent = el; el.shadowRoot.parent = el;
return el.shadowRoot; return el.shadowRoot;
} }
getShadowRoot(el) { return el.shadowRoot; } getShadowRoot(el): Element { return el.shadowRoot; }
getHost(el) { return el.host; } getHost(el): string { return el.host; }
getDistributedNodes(el: any): List<any> { throw _notImplemented('getDistributedNodes'); } getDistributedNodes(el: any): List<Node> { throw _notImplemented('getDistributedNodes'); }
clone(node) { clone(node: Node): Node {
// e.g. document fragment // e.g. document fragment
if (node.type === 'root') { if ((<any>node).type === 'root') {
var serialized = serializer.serialize(node); var serialized = serializer.serialize(node);
var newParser = new parse5.Parser(parse5.TreeAdapters.htmlparser2); var newParser = new parse5.Parser(parse5.TreeAdapters.htmlparser2);
return newParser.parseFragment(serialized); return newParser.parseFragment(serialized);
@ -282,10 +284,10 @@ export class Parse5DomAdapter extends DomAdapter {
return newParser.parseFragment(serialized).childNodes[0]; return newParser.parseFragment(serialized).childNodes[0];
} }
} }
getElementsByClassName(element, name: string) { getElementsByClassName(element, name: string): List<HTMLElement> {
return this.querySelectorAll(element, "." + name); return this.querySelectorAll(element, "." + name);
} }
getElementsByTagName(element: any, name: string): List<any> { getElementsByTagName(element: any, name: string): List<HTMLElement> {
throw _notImplemented('getElementsByTagName'); throw _notImplemented('getElementsByTagName');
} }
classList(element): List<string> { classList(element): List<string> {
@ -312,7 +314,7 @@ export class Parse5DomAdapter extends DomAdapter {
element.attribs["class"] = element.className = ListWrapper.join(classList, " "); element.attribs["class"] = element.className = ListWrapper.join(classList, " ");
} }
} }
hasClass(element, classname: string) { hasClass(element, classname: string): boolean {
return ListWrapper.contains(this.classList(element), classname); return ListWrapper.contains(this.classList(element), classname);
} }
_readStyleAttribute(element) { _readStyleAttribute(element) {
@ -346,12 +348,12 @@ export class Parse5DomAdapter extends DomAdapter {
this._writeStyleAttribute(element, styleMap); this._writeStyleAttribute(element, styleMap);
} }
removeStyle(element, stylename: string) { this.setStyle(element, stylename, null); } removeStyle(element, stylename: string) { this.setStyle(element, stylename, null); }
getStyle(element, stylename: string) { getStyle(element, stylename: string): string {
var styleMap = this._readStyleAttribute(element); var styleMap = this._readStyleAttribute(element);
return styleMap.hasOwnProperty(stylename) ? styleMap[stylename] : ""; return styleMap.hasOwnProperty(stylename) ? styleMap[stylename] : "";
} }
tagName(element): string { return element.tagName == "style" ? "STYLE" : element.tagName; } tagName(element): string { return element.tagName == "style" ? "STYLE" : element.tagName; }
attributeMap(element) { attributeMap(element): Map<string, string> {
var res = new Map(); var res = new Map();
var elAttrs = treeAdapter.getAttrList(element); var elAttrs = treeAdapter.getAttrList(element);
for (var i = 0; i < elAttrs.length; i++) { for (var i = 0; i < elAttrs.length; i++) {
@ -360,10 +362,10 @@ export class Parse5DomAdapter extends DomAdapter {
} }
return res; return res;
} }
hasAttribute(element, attribute: string) { hasAttribute(element, attribute: string): boolean {
return element.attribs && element.attribs.hasOwnProperty(attribute); return element.attribs && element.attribs.hasOwnProperty(attribute);
} }
getAttribute(element, attribute: string) { getAttribute(element, attribute: string): string {
return element.attribs && element.attribs.hasOwnProperty(attribute) ? return element.attribs && element.attribs.hasOwnProperty(attribute) ?
element.attribs[attribute] : element.attribs[attribute] :
null; null;
@ -378,8 +380,8 @@ export class Parse5DomAdapter extends DomAdapter {
StringMapWrapper.delete(element.attribs, attribute); StringMapWrapper.delete(element.attribs, attribute);
} }
} }
templateAwareRoot(el) { return this.isTemplateElement(el) ? this.content(el) : el; } templateAwareRoot(el): any { return this.isTemplateElement(el) ? this.content(el) : el; }
createHtmlDocument() { createHtmlDocument(): Document {
var newDoc = treeAdapter.createDocument(); var newDoc = treeAdapter.createDocument();
newDoc.title = "fake title"; newDoc.title = "fake title";
var head = treeAdapter.createElement("head", null, []); var head = treeAdapter.createElement("head", null, []);
@ -391,14 +393,14 @@ export class Parse5DomAdapter extends DomAdapter {
StringMapWrapper.set(newDoc, "_window", StringMapWrapper.create()); StringMapWrapper.set(newDoc, "_window", StringMapWrapper.create());
return newDoc; return newDoc;
} }
defaultDoc() { defaultDoc(): Document {
if (defDoc === null) { if (defDoc === null) {
defDoc = this.createHtmlDocument(); defDoc = this.createHtmlDocument();
} }
return defDoc; return defDoc;
} }
getBoundingClientRect(el) { return {left: 0, top: 0, width: 0, height: 0}; } getBoundingClientRect(el): any { return {left: 0, top: 0, width: 0, height: 0}; }
getTitle() { return this.defaultDoc().title || ""; } getTitle(): string { return this.defaultDoc().title || ""; }
setTitle(newTitle: string) { this.defaultDoc().title = newTitle; } setTitle(newTitle: string) { this.defaultDoc().title = newTitle; }
isTemplateElement(el: any): boolean { isTemplateElement(el: any): boolean {
return this.isElementNode(el) && this.tagName(el) === "template"; return this.isElementNode(el) && this.tagName(el) === "template";
@ -408,7 +410,7 @@ export class Parse5DomAdapter extends DomAdapter {
isElementNode(node): boolean { return node ? treeAdapter.isElementNode(node) : false; } isElementNode(node): boolean { return node ? treeAdapter.isElementNode(node) : false; }
hasShadowRoot(node): boolean { return isPresent(node.shadowRoot); } hasShadowRoot(node): boolean { return isPresent(node.shadowRoot); }
isShadowRoot(node): boolean { return this.getShadowRoot(node) == node; } isShadowRoot(node): boolean { return this.getShadowRoot(node) == node; }
importIntoDoc(node) { return this.clone(node); } importIntoDoc(node): any { return this.clone(node); }
isPageRule(rule): boolean { isPageRule(rule): boolean {
return rule.type === 6; // CSSRule.PAGE_RULE return rule.type === 6; // CSSRule.PAGE_RULE
} }
@ -476,18 +478,18 @@ export class Parse5DomAdapter extends DomAdapter {
} }
supportsDOMEvents(): boolean { return false; } supportsDOMEvents(): boolean { return false; }
supportsNativeShadowDOM(): boolean { return false; } supportsNativeShadowDOM(): boolean { return false; }
getGlobalEventTarget(target: string) { getGlobalEventTarget(target: string): any {
if (target == "window") { if (target == "window") {
return this.defaultDoc()._window; return (<any>this.defaultDoc())._window;
} else if (target == "document") { } else if (target == "document") {
return this.defaultDoc(); return this.defaultDoc();
} else if (target == "body") { } else if (target == "body") {
return this.defaultDoc().body; return this.defaultDoc().body;
} }
} }
getHistory() { throw 'not implemented'; } getHistory(): History { throw 'not implemented'; }
getLocation() { throw 'not implemented'; } getLocation(): Location { throw 'not implemented'; }
getUserAgent() { return "Fake user agent"; } getUserAgent(): string { return "Fake user agent"; }
getData(el, name: string): string { return this.getAttribute(el, 'data-' + name); } getData(el, name: string): string { return this.getAttribute(el, 'data-' + name); }
setData(el, name: string, value: string) { this.setAttribute(el, 'data-' + name, value); } setData(el, name: string, value: string) { this.setAttribute(el, 'data-' + name, value); }
// TODO(tbosch): move this into a separate environment class once we have it // TODO(tbosch): move this into a separate environment class once we have it

View File

@ -7,6 +7,12 @@ import * as Rx from 'rx';
export var Promise = (<any>global).Promise; export var Promise = (<any>global).Promise;
export interface PromiseCompleter<R> {
promise: Promise<R>;
resolve: (value?: R | Thenable<R>) => void;
reject: (error?: any, stackTrace?: string) => void;
}
export class PromiseWrapper { export class PromiseWrapper {
static resolve(obj): Promise<any> { return Promise.resolve(obj); } static resolve(obj): Promise<any> { return Promise.resolve(obj); }
@ -38,7 +44,7 @@ export class PromiseWrapper {
}); });
} }
static completer() { static completer(): PromiseCompleter<any> {
var resolve; var resolve;
var reject; var reject;
@ -103,7 +109,7 @@ export class EventEmitter extends Observable {
} }
} }
observer(generator) { observer(generator): Rx.IDisposable {
return this._subject.observeOn(this._immediateScheduler) return this._subject.observeOn(this._immediateScheduler)
.subscribe((value) => { setTimeout(() => generator.next(value)); }, .subscribe((value) => { setTimeout(() => generator.next(value)); },
(error) => generator.throw ? generator.throw(error) : null, (error) => generator.throw ? generator.throw(error) : null,

View File

@ -90,6 +90,8 @@ class StringMapWrapper {
} }
} }
typedef bool Predicate<T>(T item);
class ListWrapper { class ListWrapper {
static List clone(Iterable l) => new List.from(l); static List clone(Iterable l) => new List.from(l);
static List createFixedSize(int size) => new List(size); static List createFixedSize(int size) => new List(size);

View File

@ -65,10 +65,10 @@ export class MapWrapper {
} }
static createFromPairs(pairs: List<any>): Map<any, any> { return createMapFromPairs(pairs); } static createFromPairs(pairs: List<any>): Map<any, any> { return createMapFromPairs(pairs); }
static forEach<K, V>(m: Map<K, V>, fn: /*(V, K) => void*/ Function) { m.forEach(<any>fn); } static forEach<K, V>(m: Map<K, V>, fn: /*(V, K) => void*/ Function) { m.forEach(<any>fn); }
static size(m: Map<any, any>) { return m.size; } static size(m: Map<any, any>): number { return m.size; }
static delete<K>(m: Map<K, any>, k: K) { m.delete(k); } static delete<K>(m: Map<K, any>, k: K) { m.delete(k); }
static clearValues(m: Map<any, any>) { _clearValues(m); } static clearValues(m: Map<any, any>) { _clearValues(m); }
static iterable(m) { return m; } static iterable<T>(m: T): T { return m; }
static keys<K>(m: Map<K, any>): List<K> { return (<any>Array).from(m.keys()); } static keys<K>(m: Map<K, any>): List<K> { return (<any>Array).from(m.keys()); }
static values<V>(m: Map<any, V>): List<V> { return (<any>Array).from(m.values()); } static values<V>(m: Map<any, V>): List<V> { return (<any>Array).from(m.values()); }
} }
@ -83,13 +83,15 @@ export class StringMapWrapper {
// http://jsperf.com/ng2-object-create-null // http://jsperf.com/ng2-object-create-null
return {}; return {};
} }
static contains(map: StringMap<string, any>, key: string) { return map.hasOwnProperty(key); } static contains(map: StringMap<string, any>, key: string): boolean {
return map.hasOwnProperty(key);
}
static get<V>(map: StringMap<string, V>, key: string): V { static get<V>(map: StringMap<string, V>, key: string): V {
return map.hasOwnProperty(key) ? map[key] : undefined; return map.hasOwnProperty(key) ? map[key] : undefined;
} }
static set<V>(map: StringMap<string, V>, key: string, value: V) { map[key] = value; } static set<V>(map: StringMap<string, V>, key: string, value: V) { map[key] = value; }
static keys(map: StringMap<string, any>): List<string> { return Object.keys(map); } static keys(map: StringMap<string, any>): List<string> { return Object.keys(map); }
static isEmpty(map: StringMap<string, any>) { static isEmpty(map: StringMap<string, any>): boolean {
for (var prop in map) { for (var prop in map) {
return false; return false;
} }
@ -139,57 +141,59 @@ export class StringMapWrapper {
} }
} }
export interface Predicate<T> { (value: T, index?: number, array?: T[]): boolean; }
export class ListWrapper { export class ListWrapper {
// JS has no way to express a staticly fixed size list, but dart does so we // JS has no way to express a staticly fixed size list, but dart does so we
// keep both methods. // keep both methods.
static createFixedSize(size): List<any> { return new List(size); } static createFixedSize(size): List<any> { return new List(size); }
static createGrowableSize(size): List<any> { return new List(size); } static createGrowableSize(size): List<any> { return new List(size); }
static get(m, k) { return m[k]; } static get(m, k): any { return m[k]; }
static set(m, k, v) { m[k] = v; } static set(m, k, v) { m[k] = v; }
static clone(array: List<any>) { return array.slice(0); } static clone<T>(array: List<T>): T[] { return array.slice(0); }
static map(array, fn) { return array.map(fn); } static map(array, fn): any { return array.map(fn); }
static forEach(array: List<any>, fn: Function) { static forEach(array: List<any>, fn: Function) {
for (var i = 0; i < array.length; i++) { for (var i = 0; i < array.length; i++) {
fn(array[i]); fn(array[i]);
} }
} }
static first(array) { static first<T>(array: List<T>): T {
if (!array) return null; if (!array) return null;
return array[0]; return array[0];
} }
static last(array) { static last<T>(array: List<T>): T {
if (!array || array.length == 0) return null; if (!array || array.length == 0) return null;
return array[array.length - 1]; return array[array.length - 1];
} }
static find(list: List<any>, pred: Function) { static find<T>(list: List<T>, pred: Predicate<T>): T {
for (var i = 0; i < list.length; ++i) { for (var i = 0; i < list.length; ++i) {
if (pred(list[i])) return list[i]; if (pred(list[i])) return list[i];
} }
return null; return null;
} }
static indexOf(array: List<any>, value, startIndex = 0) { static indexOf(array: List<any>, value, startIndex = 0): number {
return array.indexOf(value, startIndex); return array.indexOf(value, startIndex);
} }
static reduce<T, E>(list: List<T>, static reduce<T, E>(list: List<T>,
fn: (accumValue: E, currentValue: T, currentIndex: number, array: T[]) => E, fn: (accumValue: E, currentValue: T, currentIndex: number, array: T[]) => E,
init: E) { init: E): E {
return list.reduce(fn, init); return list.reduce(fn, init);
} }
static filter(array, pred: Function) { return array.filter(pred); } static filter<T>(array: List<T>, pred: Predicate<T>): T[] { return array.filter(pred); }
static any(list: List<any>, pred: Function) { static any(list: List<any>, pred: Function): boolean {
for (var i = 0; i < list.length; ++i) { for (var i = 0; i < list.length; ++i) {
if (pred(list[i])) return true; if (pred(list[i])) return true;
} }
return false; return false;
} }
static contains(list: List<any>, el) { return list.indexOf(el) !== -1; } static contains(list: List<any>, el): boolean { return list.indexOf(el) !== -1; }
static reversed(array) { static reversed<T>(array: List<T>): T[] {
var a = ListWrapper.clone(array); var a = ListWrapper.clone(array);
return a.reverse(); return a.reverse();
} }
static concat(a, b) { return a.concat(b); } static concat(a, b): List<any> { return a.concat(b); }
static insert(list, index: int, value) { list.splice(index, 0, value); } static insert(list, index: int, value) { list.splice(index, 0, value); }
static removeAt(list, index: int) { static removeAt<T>(list: List<T>, index: int): T {
var res = list[index]; var res = list[index];
list.splice(index, 1); list.splice(index, 1);
return res; return res;
@ -210,8 +214,8 @@ export class ListWrapper {
return false; return false;
} }
static clear(list) { list.splice(0, list.length); } static clear(list) { list.splice(0, list.length); }
static join(list, s) { return list.join(s); } static join(list, s: string): string { return list.join(s); }
static isEmpty(list) { return list.length == 0; } static isEmpty(list): boolean { return list.length == 0; }
static fill(list: List<any>, value, start: int = 0, end: int = null) { static fill(list: List<any>, value, start: int = 0, end: int = null) {
list.fill(value, start, end === null ? undefined : end); list.fill(value, start, end === null ? undefined : end);
} }

View File

@ -37,18 +37,18 @@ export function CONST_EXPR<T>(expr: T): T {
return expr; return expr;
} }
export function CONST() { export function CONST():<T>(target: T) => T {
return (target) => target; return (target) => target;
} }
export function ABSTRACT() { export function ABSTRACT():<T>(target: T) => T {
return (t) => t; return (t) => t;
} }
// Note: This is only a marker annotation needed for ts2dart. // Note: This is only a marker annotation needed for ts2dart.
// This is written so that is can be used as a Traceur annotation // This is written so that is can be used as a Traceur annotation
// or a Typescript decorator. // or a Typescript decorator.
export function IMPLEMENTS(_) { export function IMPLEMENTS(_):<T>(target: T) => T {
return (t) => t; return (t) => t;
} }
@ -152,7 +152,7 @@ export class NumberParseError extends BaseException {
constructor(public message: string) { super(); } constructor(public message: string) { super(); }
toString() { return this.message; } toString(): string { return this.message; }
} }
@ -211,7 +211,11 @@ export class RegExpWrapper {
return regExp.exec(input); return regExp.exec(input);
} }
static test(regExp: RegExp, input: string): boolean { return regExp.test(input); } static test(regExp: RegExp, input: string): boolean { return regExp.test(input); }
static matcher(regExp, input) { static matcher(regExp, input): {
re: RegExp;
input: string
}
{
// Reset regex state for the case // Reset regex state for the case
// someone did not loop over all matches // someone did not loop over all matches
// last time. // last time.
@ -221,11 +225,11 @@ export class RegExpWrapper {
} }
export class RegExpMatcherWrapper { export class RegExpMatcherWrapper {
static next(matcher) { return matcher.re.exec(matcher.input); } static next(matcher): string { return matcher.re.exec(matcher.input); }
} }
export class FunctionWrapper { export class FunctionWrapper {
static apply(fn: Function, posArgs) { return fn.apply(null, posArgs); } static apply(fn: Function, posArgs): any { return fn.apply(null, posArgs); }
} }
// JS has NaN !== NaN // JS has NaN !== NaN
@ -235,11 +239,11 @@ export function looseIdentical(a, b): boolean {
// JS considers NaN is the same as NaN for map Key (while NaN !== NaN otherwise) // JS considers NaN is the same as NaN for map Key (while NaN !== NaN otherwise)
// see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map // see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
export function getMapKey(value) { export function getMapKey(value): any {
return value; return value;
} }
export function normalizeBlank(obj) { export function normalizeBlank(obj): any {
return isBlank(obj) ? null : obj; return isBlank(obj) ? null : obj;
} }
@ -261,7 +265,7 @@ export function print(obj) {
// Can't be all uppercase as our transpiler would think it is a special directive... // Can't be all uppercase as our transpiler would think it is a special directive...
export class Json { export class Json {
static parse(s: string) { return _global.JSON.parse(s); } static parse(s: string): Object { return _global.JSON.parse(s); }
static stringify(data): string { static stringify(data): string {
// Dart doesn't take 3 arguments // Dart doesn't take 3 arguments
return _global.JSON.stringify(data, null, 2); return _global.JSON.stringify(data, null, 2);
@ -269,8 +273,8 @@ export class Json {
} }
export class DateWrapper { export class DateWrapper {
static fromMillis(ms) { return new Date(ms); } static fromMillis(ms): Date { return new Date(ms); }
static toMillis(date: Date) { return date.getTime(); } static toMillis(date: Date): number { return date.getTime(); }
static now() { return new Date(); } static now(): Date { return new Date(); }
static toJson(date) { return date.toJSON(); } static toJson(date): string { return date.toJSON(); }
} }

View File

@ -123,7 +123,7 @@ export class NgForm extends ControlContainer implements Form {
}); });
} }
onSubmit() { onSubmit(): boolean {
ObservableWrapper.callNext(this.ngSubmit, null); ObservableWrapper.callNext(this.ngSubmit, null);
return false; return false;
} }

View File

@ -124,7 +124,7 @@ export class NgFormModel extends ControlContainer implements Form {
c.updateValue(value); c.updateValue(value);
} }
onSubmit() { onSubmit(): boolean {
ObservableWrapper.callNext(this.ngSubmit, null); ObservableWrapper.callNext(this.ngSubmit, null);
return false; return false;
} }

View File

@ -9,7 +9,7 @@ import {Validators} from '../validators';
import {Renderer, ElementRef, QueryList} from 'angular2/angular2'; import {Renderer, ElementRef, QueryList} from 'angular2/angular2';
export function controlPath(name, parent: ControlContainer) { export function controlPath(name: string, parent: ControlContainer): string[] {
var p = ListWrapper.clone(parent.path); var p = ListWrapper.clone(parent.path);
p.push(name); p.push(name);
return p; return p;

View File

@ -122,7 +122,7 @@ export class AbstractControl {
find(path: List<string | number>| string): AbstractControl { return _find(this, path); } find(path: List<string | number>| string): AbstractControl { return _find(this, path); }
getError(errorCode: string, path: List<string> = null) { getError(errorCode: string, path: List<string> = null): any {
var c = isPresent(path) && !ListWrapper.isEmpty(path) ? this.find(path) : this; var c = isPresent(path) && !ListWrapper.isEmpty(path) ? this.find(path) : this;
if (isPresent(c) && isPresent(c._errors)) { if (isPresent(c) && isPresent(c._errors)) {
return StringMapWrapper.get(c._errors, errorCode); return StringMapWrapper.get(c._errors, errorCode);
@ -131,7 +131,7 @@ export class AbstractControl {
} }
} }
hasError(errorCode: string, path: List<string> = null) { hasError(errorCode: string, path: List<string> = null): boolean {
return isPresent(this.getError(errorCode, path)); return isPresent(this.getError(errorCode, path));
} }

View File

@ -229,7 +229,7 @@ export class MockBackend implements ConnectionBackend {
* observable of this `MockBackend` instance. This method will usually only be used by tests * observable of this `MockBackend` instance. This method will usually only be used by tests
* against the framework itself, not by end-users. * against the framework itself, not by end-users.
*/ */
createConnection(req: Request) { createConnection(req: Request): Connection {
if (!req || !(req instanceof Request)) { if (!req || !(req instanceof Request)) {
throw new Error(`createConnection requires an instance of Request, got ${req}`); throw new Error(`createConnection requires an instance of Request, got ${req}`);
} }

View File

@ -49,13 +49,13 @@ export class Headers {
delete (name: string): void { MapWrapper.delete(this._headersMap, name); } delete (name: string): void { MapWrapper.delete(this._headersMap, name); }
forEach(fn: Function) { return MapWrapper.forEach(this._headersMap, fn); } forEach(fn: Function) { MapWrapper.forEach(this._headersMap, fn); }
get(header: string): string { return ListWrapper.first(this._headersMap.get(header)); } get(header: string): string { return ListWrapper.first(this._headersMap.get(header)); }
has(header: string) { return this._headersMap.has(header); } has(header: string): boolean { return this._headersMap.has(header); }
keys() { return MapWrapper.keys(this._headersMap); } keys(): List<string> { return MapWrapper.keys(this._headersMap); }
// TODO: this implementation seems wrong. create list then check if it's iterable? // TODO: this implementation seems wrong. create list then check if it's iterable?
set(header: string, value: string | List<string>): void { set(header: string, value: string | List<string>): void {
@ -69,7 +69,7 @@ export class Headers {
this._headersMap.set(header, list); this._headersMap.set(header, list);
} }
values() { return MapWrapper.values(this._headersMap); } values(): List<List<string>> { return MapWrapper.values(this._headersMap); }
getAll(header: string): Array<string> { return this._headersMap.get(header) || []; } getAll(header: string): Array<string> { return this._headersMap.get(header) || []; }

View File

@ -1,7 +1,7 @@
/// <reference path="../../typings/rx/rx.all.d.ts" /> /// <reference path="../../typings/rx/rx.all.d.ts" />
import {Injectable} from 'angular2/src/di/decorators'; import {Injectable} from 'angular2/src/di/decorators';
import {IRequestOptions, Connection} from './interfaces'; import {IRequestOptions, Connection, IHttp} from './interfaces';
import {Request} from './static_request'; import {Request} from './static_request';
import {Response} from './static_response'; import {Response} from './static_response';
import {XHRBackend} from './backends/xhr_backend'; import {XHRBackend} from './backends/xhr_backend';
@ -10,15 +10,15 @@ import {RequestMethods} from './enums';
import {URLSearchParams} from './url_search_params'; import {URLSearchParams} from './url_search_params';
import * as Rx from 'rx'; import * as Rx from 'rx';
function httpRequest(backend: XHRBackend, request: Request) { function httpRequest(backend: XHRBackend, request: Request): Rx.Observable<Response> {
return <Rx.Observable<Response>>(Observable.create(observer => { return <Rx.Observable<Response>>(Observable.create(observer => {
var connection: Connection = backend.createConnection(request); var connection: Connection = backend.createConnection(request);
var internalSubscription = connection.response.subscribe(observer); var internalSubscription = connection.response.subscribe(observer);
return () => { return () => {
internalSubscription.dispose(); internalSubscription.dispose();
connection.dispose(); connection.dispose();
} };
})) }));
} }
/** /**
@ -91,7 +91,7 @@ export class Http {
/** /**
* Performs a request with `get` http method. * Performs a request with `get` http method.
*/ */
get(url: string, options?: IRequestOptions) { get(url: string, options?: IRequestOptions): Rx.Observable<Response> {
return httpRequest(this._backend, new Request(url, this._defaultOptions.merge(options) return httpRequest(this._backend, new Request(url, this._defaultOptions.merge(options)
.merge({method: RequestMethods.GET}))); .merge({method: RequestMethods.GET})));
} }
@ -99,7 +99,8 @@ export class Http {
/** /**
* Performs a request with `post` http method. * Performs a request with `post` http method.
*/ */
post(url: string, body: URLSearchParams | FormData | Blob | string, options?: IRequestOptions) { post(url: string, body: URLSearchParams | FormData | Blob | string,
options?: IRequestOptions): Rx.Observable<Response> {
return httpRequest(this._backend, return httpRequest(this._backend,
new Request(url, this._defaultOptions.merge(options) new Request(url, this._defaultOptions.merge(options)
@ -109,7 +110,8 @@ export class Http {
/** /**
* Performs a request with `put` http method. * Performs a request with `put` http method.
*/ */
put(url: string, body: URLSearchParams | FormData | Blob | string, options?: IRequestOptions) { put(url: string, body: URLSearchParams | FormData | Blob | string,
options?: IRequestOptions): Rx.Observable<Response> {
return httpRequest(this._backend, return httpRequest(this._backend,
new Request(url, this._defaultOptions.merge(options) new Request(url, this._defaultOptions.merge(options)
.merge({body: body, method: RequestMethods.PUT}))); .merge({body: body, method: RequestMethods.PUT})));
@ -118,7 +120,7 @@ export class Http {
/** /**
* Performs a request with `delete` http method. * Performs a request with `delete` http method.
*/ */
delete (url: string, options?: IRequestOptions) { delete (url: string, options?: IRequestOptions): Rx.Observable<Response> {
return httpRequest(this._backend, new Request(url, this._defaultOptions.merge(options).merge( return httpRequest(this._backend, new Request(url, this._defaultOptions.merge(options).merge(
{method: RequestMethods.DELETE}))); {method: RequestMethods.DELETE})));
} }
@ -126,7 +128,8 @@ export class Http {
/** /**
* Performs a request with `patch` http method. * Performs a request with `patch` http method.
*/ */
patch(url: string, body: URLSearchParams | FormData | Blob | string, options?: IRequestOptions) { patch(url: string, body: URLSearchParams | FormData | Blob | string,
options?: IRequestOptions): Rx.Observable<Response> {
return httpRequest(this._backend, return httpRequest(this._backend,
new Request(url, this._defaultOptions.merge(options) new Request(url, this._defaultOptions.merge(options)
.merge({body: body, method: RequestMethods.PATCH}))); .merge({body: body, method: RequestMethods.PATCH})));
@ -135,7 +138,7 @@ export class Http {
/** /**
* Performs a request with `head` http method. * Performs a request with `head` http method.
*/ */
head(url: string, options?: IRequestOptions) { head(url: string, options?: IRequestOptions): Rx.Observable<Response> {
return httpRequest(this._backend, new Request(url, this._defaultOptions.merge(options) return httpRequest(this._backend, new Request(url, this._defaultOptions.merge(options)
.merge({method: RequestMethods.HEAD}))); .merge({method: RequestMethods.HEAD})));
} }
@ -171,12 +174,12 @@ if (Rx.hasOwnProperty('default')) {
* } * }
* ``` * ```
**/ **/
export function HttpFactory(backend: XHRBackend, defaultOptions: BaseRequestOptions) { export function HttpFactory(backend: XHRBackend, defaultOptions: BaseRequestOptions): IHttp {
return function(url: string | Request, options?: IRequestOptions) { return function(url: string | Request, options?: IRequestOptions) {
if (typeof url === 'string') { if (typeof url === 'string') {
return httpRequest(backend, new Request(url, defaultOptions.merge(options))); return httpRequest(backend, new Request(url, defaultOptions.merge(options)));
} else if (url instanceof Request) { } else if (url instanceof Request) {
return httpRequest(backend, url); return httpRequest(backend, url);
} }
} };
} }

View File

@ -30,7 +30,7 @@ export class SpyLocation extends SpyObject {
simulateUrlPop(pathname: string) { ObservableWrapper.callNext(this._subject, {'url': pathname}); } simulateUrlPop(pathname: string) { ObservableWrapper.callNext(this._subject, {'url': pathname}); }
normalizeAbsolutely(url) { return this._baseHref + url; } normalizeAbsolutely(url): string { return this._baseHref + url; }
go(url: string) { go(url: string) {
url = this.normalizeAbsolutely(url); url = this.normalizeAbsolutely(url);
@ -53,5 +53,5 @@ export class SpyLocation extends SpyObject {
ObservableWrapper.subscribe(this._subject, onNext, onThrow, onReturn); ObservableWrapper.subscribe(this._subject, onNext, onThrow, onReturn);
} }
noSuchMethod(m) { return super.noSuchMethod(m); } noSuchMethod(m) { super.noSuchMethod(m); }
} }

View File

@ -3,7 +3,7 @@ import {NgZone} from 'angular2/src/core/zone/ng_zone';
export class MockNgZone extends NgZone { export class MockNgZone extends NgZone {
constructor() { super({enableLongStackTrace: false}); } constructor() { super({enableLongStackTrace: false}); }
run(fn) { return fn(); } run(fn): any { return fn(); }
runOutsideAngular(fn) { return fn(); } runOutsideAngular(fn): any { return fn(); }
} }

View File

@ -217,7 +217,7 @@ export class DirectiveMetadata {
callOnAllChangesDone?: boolean, callOnAllChangesDone?: boolean,
changeDetection?: string, changeDetection?: string,
exportAs?: string exportAs?: string
}) { }): DirectiveMetadata {
let hostListeners = new Map(); let hostListeners = new Map();
let hostProperties = new Map(); let hostProperties = new Map();
let hostAttributes = new Map(); let hostAttributes = new Map();

View File

@ -11,13 +11,14 @@ export class CompileControl {
_currentStepIndex: number = 0; _currentStepIndex: number = 0;
_parent: CompileElement = null; _parent: CompileElement = null;
_results: any[] = null; _results: any[] = null;
_additionalChildren: any[] = null; _additionalChildren: CompileElement[] = null;
_ignoreCurrentElement: boolean; _ignoreCurrentElement: boolean;
constructor(public _steps: List<CompileStep>) {} constructor(public _steps: List<CompileStep>) {}
// only public so that it can be used by compile_pipeline // only public so that it can be used by compile_pipeline
internalProcess(results: any[], startStepIndex, parent: CompileElement, current: CompileElement) { internalProcess(results: any[], startStepIndex, parent: CompileElement,
current: CompileElement): CompileElement[] {
this._results = results; this._results = results;
var previousStepIndex = this._currentStepIndex; var previousStepIndex = this._currentStepIndex;
var previousParent = this._parent; var previousParent = this._parent;

View File

@ -33,11 +33,11 @@ export class CompileElement {
} }
} }
isBound() { isBound(): boolean {
return isPresent(this.inheritedElementBinder) && this.distanceToInheritedBinder === 0; return isPresent(this.inheritedElementBinder) && this.distanceToInheritedBinder === 0;
} }
bindElement() { bindElement(): ElementBinderBuilder {
if (!this.isBound()) { if (!this.isBound()) {
var parentBinder = this.inheritedElementBinder; var parentBinder = this.inheritedElementBinder;
this.inheritedElementBinder = this.inheritedElementBinder =

View File

@ -135,7 +135,7 @@ export class CssSelector {
* are contained in a given CssSelector. * are contained in a given CssSelector.
*/ */
export class SelectorMatcher { export class SelectorMatcher {
static createNotMatcher(notSelectors: List<CssSelector>) { static createNotMatcher(notSelectors: List<CssSelector>): SelectorMatcher {
var notMatcher = new SelectorMatcher(); var notMatcher = new SelectorMatcher();
notMatcher.addSelectables(notSelectors, null); notMatcher.addSelectables(notSelectors, null);
return notMatcher; return notMatcher;
@ -353,7 +353,7 @@ class SelectorContext {
this.notSelectors = selector.notSelectors; this.notSelectors = selector.notSelectors;
} }
finalize(cssSelector: CssSelector, callback /*: (CssSelector, any) => void*/) { finalize(cssSelector: CssSelector, callback /*: (CssSelector, any) => void*/): boolean {
var result = true; var result = true;
if (this.notSelectors.length > 0 && if (this.notSelectors.length > 0 &&
(isBlank(this.listContext) || !this.listContext.alreadyMatched)) { (isBlank(this.listContext) || !this.listContext.alreadyMatched)) {

View File

@ -12,7 +12,7 @@ import {UrlResolver} from 'angular2/src/services/url_resolver';
export class StyleUrlResolver { export class StyleUrlResolver {
constructor(public _resolver: UrlResolver) {} constructor(public _resolver: UrlResolver) {}
resolveUrls(cssText: string, baseUrl: string) { resolveUrls(cssText: string, baseUrl: string): string {
cssText = this._replaceUrls(cssText, _cssUrlRe, baseUrl); cssText = this._replaceUrls(cssText, _cssUrlRe, baseUrl);
cssText = this._replaceUrls(cssText, _cssImportRe, baseUrl); cssText = this._replaceUrls(cssText, _cssImportRe, baseUrl);
return cssText; return cssText;

View File

@ -53,7 +53,7 @@ export class DomRenderer extends Renderer {
// noop for now // noop for now
} }
getNativeElementSync(location: RenderElementRef) { getNativeElementSync(location: RenderElementRef): any {
return resolveInternalDomView(location.renderView) return resolveInternalDomView(location.renderView)
.boundElements[location.boundElementIndex] .boundElements[location.boundElementIndex]
.element; .element;

View File

@ -90,7 +90,7 @@ export class DomEventsPlugin extends EventManagerPlugin {
DomEventsPlugin.sameElementCallback(element, handler, zone); DomEventsPlugin.sameElementCallback(element, handler, zone);
} }
static sameElementCallback(element, handler, zone) { static sameElementCallback(element, handler, zone): (event: Event) => void {
return (event) => { return (event) => {
if (event.target === element) { if (event.target === element) {
zone.run(() => handler(event)); zone.run(() => handler(event));
@ -98,7 +98,7 @@ export class DomEventsPlugin extends EventManagerPlugin {
}; };
} }
static bubbleCallback(element, handler, zone) { static bubbleCallback(element, handler, zone): (event: Event) => void {
return (event) => zone.run(() => handler(event)); return (event) => zone.run(() => handler(event));
} }
} }

View File

@ -11,13 +11,12 @@ import {StringMapWrapper, ListWrapper} from 'angular2/src/facade/collection';
import {EventManagerPlugin} from './event_manager'; import {EventManagerPlugin} from './event_manager';
var modifierKeys = ['alt', 'control', 'meta', 'shift']; var modifierKeys = ['alt', 'control', 'meta', 'shift'];
var modifierKeyGetters: StringMap<string, Function> = var modifierKeyGetters: StringMap<string, Function> = {
{ 'alt': (event) => event.altKey,
'alt': (event) => event.altKey, 'control': (event) => event.ctrlKey,
'control': (event) => event.ctrlKey, 'meta': (event) => event.metaKey,
'meta': (event) => event.metaKey, 'shift': (event) => event.shiftKey
'shift': (event) => event.shiftKey };
}
export class KeyEventsPlugin extends EventManagerPlugin { export class KeyEventsPlugin extends EventManagerPlugin {
constructor() { super(); } constructor() { super(); }
@ -38,7 +37,7 @@ export class KeyEventsPlugin extends EventManagerPlugin {
}); });
} }
static parseEventName(eventName: string) /* {'domEventName': string, 'fullKey': string} */ { static parseEventName(eventName: string): StringMap<string, string> {
var parts = eventName.toLowerCase().split('.'); var parts = eventName.toLowerCase().split('.');
var domEventName = ListWrapper.removeAt(parts, 0); var domEventName = ListWrapper.removeAt(parts, 0);
@ -63,8 +62,10 @@ export class KeyEventsPlugin extends EventManagerPlugin {
// returning null instead of throwing to let another plugin process the event // returning null instead of throwing to let another plugin process the event
return null; return null;
} }
var result = StringMapWrapper.create();
return {'domEventName': domEventName, 'fullKey': fullKey}; StringMapWrapper.set(result, 'domEventName', domEventName);
StringMapWrapper.set(result, 'fullKey', fullKey);
return result;
} }
static getEventFullKey(event): string { static getEventFullKey(event): string {
@ -88,7 +89,8 @@ export class KeyEventsPlugin extends EventManagerPlugin {
return fullKey; return fullKey;
} }
static eventCallback(element, shouldSupportBubble, fullKey, handler, zone) { static eventCallback(element, shouldSupportBubble, fullKey, handler,
zone): (event: Event) => void {
return (event) => { return (event) => {
var correctElement = shouldSupportBubble || event.target === element; var correctElement = shouldSupportBubble || event.target === element;
if (correctElement && StringWrapper.equals(KeyEventsPlugin.getEventFullKey(event), fullKey)) { if (correctElement && StringWrapper.equals(KeyEventsPlugin.getEventFullKey(event), fullKey)) {

View File

@ -20,7 +20,7 @@ export class EmulatedUnscopedShadowDomStrategy extends ShadowDomStrategy {
hasNativeContentElement(): boolean { return false; } hasNativeContentElement(): boolean { return false; }
prepareShadowRoot(el) { return el; } prepareShadowRoot(el): /*(#2770) Node*/ any { return el; }
constructLightDom(lightDomView: viewModule.DomView, el): LightDom { constructLightDom(lightDomView: viewModule.DomView, el): LightDom {
return new LightDom(lightDomView, el); return new LightDom(lightDomView, el);

View File

@ -10,5 +10,5 @@ import {ShadowDomStrategy} from './shadow_dom_strategy';
*/ */
@Injectable() @Injectable()
export class NativeShadowDomStrategy extends ShadowDomStrategy { export class NativeShadowDomStrategy extends ShadowDomStrategy {
prepareShadowRoot(el) { return DOM.createShadowRoot(el); } prepareShadowRoot(el): /*(#2770) Node*/ any { return DOM.createShadowRoot(el); }
} }

View File

@ -10,7 +10,7 @@ var _nextComponentUID: int = 0;
var _sharedStyleTexts: Map<string, boolean> = new Map(); var _sharedStyleTexts: Map<string, boolean> = new Map();
var _lastInsertedStyleEl; var _lastInsertedStyleEl;
export function getComponentId(componentStringId: string) { export function getComponentId(componentStringId: string): number {
var id = _componentUIDs.get(componentStringId); var id = _componentUIDs.get(componentStringId);
if (isBlank(id)) { if (isBlank(id)) {
id = _nextComponentUID++; id = _nextComponentUID++;
@ -43,12 +43,12 @@ export function insertStyleElement(host, styleEl) {
} }
// Return the attribute to be added to the component // Return the attribute to be added to the component
export function getHostAttribute(id: int) { export function getHostAttribute(id: int): string {
return `_nghost-${id}`; return `_nghost-${id}`;
} }
// Returns the attribute to be added on every single element nodes in the component // Returns the attribute to be added on every single element nodes in the component
export function getContentAttribute(id: int) { export function getContentAttribute(id: int): string {
return `_ngcontent-${id}`; return `_ngcontent-${id}`;
} }

View File

@ -8,12 +8,12 @@ export const EVENT_TARGET_SEPARATOR = ':';
var CAMEL_CASE_REGEXP = RegExpWrapper.create('([A-Z])'); var CAMEL_CASE_REGEXP = RegExpWrapper.create('([A-Z])');
var DASH_CASE_REGEXP = RegExpWrapper.create('-([a-z])'); var DASH_CASE_REGEXP = RegExpWrapper.create('-([a-z])');
export function camelCaseToDashCase(input: string) { export function camelCaseToDashCase(input: string): string {
return StringWrapper.replaceAllMapped(input, CAMEL_CASE_REGEXP, return StringWrapper.replaceAllMapped(input, CAMEL_CASE_REGEXP,
(m) => { return '-' + m[1].toLowerCase(); }); (m) => { return '-' + m[1].toLowerCase(); });
} }
export function dashCaseToCamelCase(input: string) { export function dashCaseToCamelCase(input: string): string {
return StringWrapper.replaceAllMapped(input, DASH_CASE_REGEXP, return StringWrapper.replaceAllMapped(input, DASH_CASE_REGEXP,
(m) => { return m[1].toUpperCase(); }); (m) => { return m[1].toUpperCase(); });
} }

View File

@ -293,7 +293,7 @@ export class EventBuilder extends AstTransformer {
return result; return result;
} }
visitAccessMember(ast: AccessMember) { visitAccessMember(ast: AccessMember): AccessMember {
var isEventAccess = false; var isEventAccess = false;
var current: AST = ast; var current: AST = ast;
while (!isEventAccess && (current instanceof AccessMember)) { while (!isEventAccess && (current instanceof AccessMember)) {
@ -313,11 +313,11 @@ export class EventBuilder extends AstTransformer {
} }
} }
buildEventLocals() { return this.locals; } buildEventLocals(): List<AST> { return this.locals; }
buildLocalEvents() { return this.localEvents; } buildLocalEvents(): List<Event> { return this.localEvents; }
buildGlobalEvents() { return this.globalEvents; } buildGlobalEvents(): List<Event> { return this.globalEvents; }
merge(eventBuilder: EventBuilder) { merge(eventBuilder: EventBuilder) {
this._merge(this.localEvents, eventBuilder.localEvents); this._merge(this.localEvents, eventBuilder.localEvents);
@ -343,9 +343,10 @@ const ATTRIBUTE_PREFIX = 'attr';
const CLASS_PREFIX = 'class'; const CLASS_PREFIX = 'class';
const STYLE_PREFIX = 'style'; const STYLE_PREFIX = 'style';
function buildElementPropertyBindings(protoElement: /*element*/ any, isNgComponent: boolean, function buildElementPropertyBindings(
bindingsInTemplate: Map<string, ASTWithSource>, protoElement: /*element*/ any, isNgComponent: boolean,
directiveTempaltePropertyNames: Set<string>) { bindingsInTemplate: Map<string, ASTWithSource>,
directiveTempaltePropertyNames: Set<string>): List<api.ElementPropertyBinding> {
var propertyBindings = []; var propertyBindings = [];
MapWrapper.forEach(bindingsInTemplate, (ast, propertyNameInTemplate) => { MapWrapper.forEach(bindingsInTemplate, (ast, propertyNameInTemplate) => {
var propertyBinding = createElementPropertyBinding(ast, propertyNameInTemplate); var propertyBinding = createElementPropertyBinding(ast, propertyNameInTemplate);

View File

@ -9,7 +9,7 @@ import {DomElement} from './element';
import {RenderViewRef, EventDispatcher} from '../../api'; import {RenderViewRef, EventDispatcher} from '../../api';
import {camelCaseToDashCase} from '../util'; import {camelCaseToDashCase} from '../util';
export function resolveInternalDomView(viewRef: RenderViewRef) { export function resolveInternalDomView(viewRef: RenderViewRef): DomView {
return (<DomViewRef>viewRef)._view; return (<DomViewRef>viewRef)._view;
} }

View File

@ -6,7 +6,7 @@ export class DomViewContainer {
// The order in this list matches the DOM order. // The order in this list matches the DOM order.
views: List<viewModule.DomView> = []; views: List<viewModule.DomView> = [];
contentTagContainers() { return this.views; } contentTagContainers(): List<viewModule.DomView> { return this.views; }
nodes(): List</*node*/ any> { nodes(): List</*node*/ any> {
var r = []; var r = [];

View File

@ -72,7 +72,7 @@ class StarSegment {
var paramMatcher = RegExpWrapper.create("^:([^\/]+)$"); var paramMatcher = RegExpWrapper.create("^:([^\/]+)$");
var wildcardMatcher = RegExpWrapper.create("^\\*([^\/]+)$"); var wildcardMatcher = RegExpWrapper.create("^\\*([^\/]+)$");
function parsePathString(route: string) { function parsePathString(route: string): StringMap<string, any> {
// normalize route as not starting with a "/". Recognition will // normalize route as not starting with a "/". Recognition will
// also normalize. // also normalize.
if (StringWrapper.startsWith(route, "/")) { if (StringWrapper.startsWith(route, "/")) {
@ -117,8 +117,10 @@ function parsePathString(route: string) {
specificity += 100 * (100 - i); specificity += 100 * (100 - i);
} }
} }
var result = StringMapWrapper.create();
return {segments: results, specificity}; StringMapWrapper.set(result, 'segments', results);
StringMapWrapper.set(result, 'specificity', specificity);
return result;
} }
function splitBySlash(url: string): List<string> { function splitBySlash(url: string): List<string> {

View File

@ -106,7 +106,7 @@ export class RouteRegistry {
ListWrapper.map(possibleMatches, (candidate) => this._completeRouteMatch(candidate)); ListWrapper.map(possibleMatches, (candidate) => this._completeRouteMatch(candidate));
return PromiseWrapper.all(matchPromises) return PromiseWrapper.all(matchPromises)
.then((solutions) => { .then((solutions: List<Instruction>) => {
// remove nulls // remove nulls
var fullSolutions = ListWrapper.filter(solutions, (solution) => isPresent(solution)); var fullSolutions = ListWrapper.filter(solutions, (solution) => isPresent(solution));

View File

@ -11,7 +11,7 @@ export interface TypeDecorator {
Class(obj: ClassDefinition): Type; Class(obj: ClassDefinition): Type;
} }
function extractAnnotation(annotation: any) { function extractAnnotation(annotation: any): any {
if (isFunction(annotation) && annotation.hasOwnProperty('annotation')) { if (isFunction(annotation) && annotation.hasOwnProperty('annotation')) {
// it is a decorator, extract annotation // it is a decorator, extract annotation
annotation = annotation.annotation; annotation = annotation.annotation;
@ -121,7 +121,7 @@ export function makeDecorator(annotationCls, chainFn: (fn: Function) => void = n
} }
export function makeParamDecorator(annotationCls): any { export function makeParamDecorator(annotationCls): any {
function ParamDecoratorFactory(...args) { function ParamDecoratorFactory(...args): any {
var annotationInstance = Object.create(annotationCls.prototype); var annotationInstance = Object.create(annotationCls.prototype);
annotationCls.apply(annotationInstance, args); annotationCls.apply(annotationInstance, args);
if (this instanceof annotationCls) { if (this instanceof annotationCls) {
@ -131,7 +131,7 @@ export function makeParamDecorator(annotationCls): any {
return ParamDecorator; return ParamDecorator;
} }
function ParamDecorator(cls, unusedKey, index) { function ParamDecorator(cls, unusedKey, index): any {
var parameters: Array<Array<any>> = Reflect.getMetadata('parameters', cls); var parameters: Array<Array<any>> = Reflect.getMetadata('parameters', cls);
parameters = parameters || []; parameters = parameters || [];

View File

@ -58,8 +58,9 @@ export function main() {
rootProtoView = createRootProtoView(directiveResolver, MainComponent); rootProtoView = createRootProtoView(directiveResolver, MainComponent);
}); });
function createCompiler(renderCompileResults: List<renderApi.ProtoViewDto>, function createCompiler(
protoViewFactoryResults: List<List<AppProtoView>>) { renderCompileResults: List<renderApi.ProtoViewDto | Promise<renderApi.ProtoViewDto>>,
protoViewFactoryResults: List<List<AppProtoView>>) {
var urlResolver = new UrlResolver(); var urlResolver = new UrlResolver();
renderCompileRequests = []; renderCompileRequests = [];
renderCompiler.spy('compile').andCallFake((view) => { renderCompiler.spy('compile').andCallFake((view) => {

View File

@ -115,10 +115,9 @@ export function main() {
tc.detectChanges(); tc.detectChanges();
var newlyInsertedElement = DOM.childNodes(tc.nativeElement)[1]; var newlyInsertedElement = DOM.childNodes(tc.nativeElement)[1];
expect(newlyInsertedElement.id) expect((</*(#2770) HTMLElement*/ any>newlyInsertedElement).id)
.toEqual("new value") .toEqual("new value");
async.done();
async.done();
}); });
}); });
})); }));
@ -211,10 +210,10 @@ export function main() {
tc.detectChanges(); tc.detectChanges();
var newlyInsertedElement = DOM.nextSibling(tc.nativeElement); var newlyInsertedElement = DOM.nextSibling(tc.nativeElement);
expect(newlyInsertedElement.id) expect((</*(#2770) HTMLElement*/ any>newlyInsertedElement).id)
.toEqual("new value") .toEqual("new value");
async.done(); async.done();
}); });
}); });
})); }));

View File

@ -107,10 +107,11 @@ export function main() {
var el = DOM.childNodes(tb.rootEl)[0]; var el = DOM.childNodes(tb.rootEl)[0];
tb.renderer.setElementProperty(elRef(cmpView.viewRef, 0), 'value', 'hello'); tb.renderer.setElementProperty(elRef(cmpView.viewRef, 0), 'value', 'hello');
expect(el.value).toEqual('hello'); expect((</*(#2770) HTMLInputElement*/ any>el).value).toEqual('hello');
tb.renderer.setElementClass(elRef(cmpView.viewRef, 0), 'a', true); tb.renderer.setElementClass(elRef(cmpView.viewRef, 0), 'a', true);
expect(DOM.childNodes(tb.rootEl)[0].value).toEqual('hello'); expect((</*(#2770) HTMLInputElement*/ any>DOM.childNodes(tb.rootEl)[0]).value)
.toEqual('hello');
tb.renderer.setElementClass(elRef(cmpView.viewRef, 0), 'a', false); tb.renderer.setElementClass(elRef(cmpView.viewRef, 0), 'a', false);
expect(DOM.hasClass(el, 'a')).toBe(false); expect(DOM.hasClass(el, 'a')).toBe(false);