refactor(change_detector): made change detection responsible for processing events

Closes #3666
This commit is contained in:
vsavkin
2015-08-12 16:26:21 -07:00
committed by Victor Savkin
parent 8b655c7be3
commit 4845583dcf
34 changed files with 837 additions and 1014 deletions
@@ -66,6 +66,10 @@ export class AbstractChangeDetector<T> implements ChangeDetector {
remove(): void { this.parent.removeChild(this); }
handleEvent(eventName: string, elIndex: number, locals: Locals): boolean {
throw new BaseException("Not implemented");
}
detectChanges(): void { this.runDetectChanges(false); }
checkNoChanges(): void { throw new BaseException("Not implemented"); }
@@ -10,11 +10,13 @@ const ELEMENT_ATTRIBUTE = "elementAttribute";
const ELEMENT_CLASS = "elementClass";
const ELEMENT_STYLE = "elementStyle";
const TEXT_NODE = "textNode";
const EVENT = "event";
const HOST_EVENT = "hostEvent";
export class BindingRecord {
constructor(public mode: string, public implicitReceiver: any, public ast: AST,
public elementIndex: number, public propertyName: string, public propertyUnit: string,
public setter: SetterFn, public lifecycleEvent: string,
public eventName: string, public setter: SetterFn, public lifecycleEvent: string,
public directiveRecord: DirectiveRecord) {}
callOnChange(): boolean {
@@ -41,73 +43,83 @@ export class BindingRecord {
static createForDirective(ast: AST, propertyName: string, setter: SetterFn,
directiveRecord: DirectiveRecord): BindingRecord {
return new BindingRecord(DIRECTIVE, 0, ast, 0, propertyName, null, setter, null,
return new BindingRecord(DIRECTIVE, 0, ast, 0, propertyName, null, null, setter, null,
directiveRecord);
}
static createDirectiveOnCheck(directiveRecord: DirectiveRecord): BindingRecord {
return new BindingRecord(DIRECTIVE_LIFECYCLE, 0, null, 0, null, null, null, "onCheck",
return new BindingRecord(DIRECTIVE_LIFECYCLE, 0, null, 0, null, null, null, null, "onCheck",
directiveRecord);
}
static createDirectiveOnInit(directiveRecord: DirectiveRecord): BindingRecord {
return new BindingRecord(DIRECTIVE_LIFECYCLE, 0, null, 0, null, null, null, "onInit",
return new BindingRecord(DIRECTIVE_LIFECYCLE, 0, null, 0, null, null, null, null, "onInit",
directiveRecord);
}
static createDirectiveOnChange(directiveRecord: DirectiveRecord): BindingRecord {
return new BindingRecord(DIRECTIVE_LIFECYCLE, 0, null, 0, null, null, null, "onChange",
return new BindingRecord(DIRECTIVE_LIFECYCLE, 0, null, 0, null, null, null, null, "onChange",
directiveRecord);
}
static createForElementProperty(ast: AST, elementIndex: number,
propertyName: string): BindingRecord {
return new BindingRecord(ELEMENT_PROPERTY, 0, ast, elementIndex, propertyName, null, null, null,
null);
null, null);
}
static createForElementAttribute(ast: AST, elementIndex: number,
attributeName: string): BindingRecord {
return new BindingRecord(ELEMENT_ATTRIBUTE, 0, ast, elementIndex, attributeName, null, null,
null, null);
null, null, null);
}
static createForElementClass(ast: AST, elementIndex: number, className: string): BindingRecord {
return new BindingRecord(ELEMENT_CLASS, 0, ast, elementIndex, className, null, null, null,
return new BindingRecord(ELEMENT_CLASS, 0, ast, elementIndex, className, null, null, null, null,
null);
}
static createForElementStyle(ast: AST, elementIndex: number, styleName: string,
unit: string): BindingRecord {
return new BindingRecord(ELEMENT_STYLE, 0, ast, elementIndex, styleName, unit, null, null,
return new BindingRecord(ELEMENT_STYLE, 0, ast, elementIndex, styleName, unit, null, null, null,
null);
}
static createForHostProperty(directiveIndex: DirectiveIndex, ast: AST,
propertyName: string): BindingRecord {
return new BindingRecord(ELEMENT_PROPERTY, directiveIndex, ast, directiveIndex.elementIndex,
propertyName, null, null, null, null);
propertyName, null, null, null, null, null);
}
static createForHostAttribute(directiveIndex: DirectiveIndex, ast: AST,
attributeName: string): BindingRecord {
return new BindingRecord(ELEMENT_ATTRIBUTE, directiveIndex, ast, directiveIndex.elementIndex,
attributeName, null, null, null, null);
attributeName, null, null, null, null, null);
}
static createForHostClass(directiveIndex: DirectiveIndex, ast: AST,
className: string): BindingRecord {
return new BindingRecord(ELEMENT_CLASS, directiveIndex, ast, directiveIndex.elementIndex,
className, null, null, null, null);
className, null, null, null, null, null);
}
static createForHostStyle(directiveIndex: DirectiveIndex, ast: AST, styleName: string,
unit: string): BindingRecord {
return new BindingRecord(ELEMENT_STYLE, directiveIndex, ast, directiveIndex.elementIndex,
styleName, unit, null, null, null);
styleName, unit, null, null, null, null);
}
static createForTextNode(ast: AST, elementIndex: number): BindingRecord {
return new BindingRecord(TEXT_NODE, 0, ast, elementIndex, null, null, null, null, null);
return new BindingRecord(TEXT_NODE, 0, ast, elementIndex, null, null, null, null, null, null);
}
static createForEvent(ast: AST, eventName: string, elementIndex: number): BindingRecord {
return new BindingRecord(EVENT, 0, ast, elementIndex, null, null, eventName, null, null, null);
}
static createForHostEvent(ast: AST, eventName: string,
directiveIndex: DirectiveIndex): BindingRecord {
return new BindingRecord(EVENT, directiveIndex, ast, directiveIndex.elementIndex, null, null,
eventName, null, null, null);
}
}
@@ -14,7 +14,7 @@ export {
ASTWithSource,
AST,
AstTransformer,
AccessMember,
PropertyRead,
LiteralArray,
ImplicitReceiver
} from './parser/ast';
@@ -8,6 +8,7 @@ import {DirectiveIndex, DirectiveRecord} from './directive_record';
import {ProtoRecord, RecordType} from './proto_record';
import {CodegenNameUtil, sanitizeName} from './codegen_name_util';
import {CodegenLogicUtil} from './codegen_logic_util';
import {EventBinding} from './event_binding';
/**
@@ -30,9 +31,10 @@ export class ChangeDetectorJITGenerator {
_typeName: string;
constructor(public id: string, private changeDetectionStrategy: string,
public records: List<ProtoRecord>, public directiveRecords: List<any>,
private generateCheckNoChanges: boolean) {
this._names = new CodegenNameUtil(this.records, this.directiveRecords, UTIL);
public records: List<ProtoRecord>, public eventBindings: EventBinding[],
public directiveRecords: List<any>, private generateCheckNoChanges: boolean) {
this._names =
new CodegenNameUtil(this.records, this.eventBindings, this.directiveRecords, UTIL);
this._logic = new CodegenLogicUtil(this._names, UTIL);
this._typeName = sanitizeName(`ChangeDetector_${this.id}`);
}
@@ -48,6 +50,13 @@ export class ChangeDetectorJITGenerator {
${this._typeName}.prototype = Object.create(${ABSTRACT_CHANGE_DETECTOR}.prototype);
${this._typeName}.prototype.handleEvent = function(eventName, elIndex, locals) {
var ${this._names.getPreventDefaultAccesor()} = false;
${this._names.genInitEventLocals()}
${this._genHandleEvent()}
return ${this._names.getPreventDefaultAccesor()};
}
${this._typeName}.prototype.detectChangesInRecordsInternal = function(throwOnChange) {
${this._names.genInitLocals()}
var ${IS_CHANGED_LOCAL} = false;
@@ -75,6 +84,33 @@ export class ChangeDetectorJITGenerator {
AbstractChangeDetector, ChangeDetectionUtil, this.records, this.directiveRecords);
}
_genHandleEvent(): string {
return this.eventBindings.map(eb => this._genEventBinding(eb)).join("\n");
}
_genEventBinding(eb: EventBinding): string {
var recs = eb.records.map(r => this._genEventBindingEval(eb, r)).join("\n");
return `
if (eventName === "${eb.eventName}" && elIndex === ${eb.elIndex}) {
${recs}
}`;
}
_genEventBindingEval(eb: EventBinding, r: ProtoRecord): string {
if (r.lastInBinding) {
var evalRecord = this._logic.genEventBindingEvalValue(eb, r);
var prevDefault = this._genUpdatePreventDefault(eb, r);
return `${evalRecord}\n${prevDefault}`;
} else {
return this._logic.genEventBindingEvalValue(eb, r);
}
}
_genUpdatePreventDefault(eb: EventBinding, r: ProtoRecord): string {
var local = this._names.getEventLocalName(eb, r.selfIndex);
return `if (${local} === false) { ${this._names.getPreventDefaultAccesor()} = true};`;
}
_maybeGenDehydrateDirectives(): string {
var destroyPipesCode = this._names.genPipeOnDestroy();
if (destroyPipesCode) {
@@ -204,7 +240,7 @@ export class ChangeDetectorJITGenerator {
var oldValue = this._names.getFieldName(r.selfIndex);
var newValue = this._names.getLocalName(r.selfIndex);
var read = `
${this._logic.genUpdateCurrentValue(r)}
${this._logic.genPropertyBindingEvalValue(r)}
`;
var check = `
@@ -13,3 +13,7 @@ String codify(funcOrValue) => JSON.encode(funcOrValue).replaceAll(r'$', r'\$');
String combineGeneratedStrings(List<String> vals) {
return '"${vals.map((v) => '\${$v}').join('')}"';
}
String rawString(String str) {
return "r'$str'";
}
@@ -7,6 +7,10 @@ export function codify(obj: any): string {
return JSON.stringify(obj);
}
export function rawString(str: string): string {
return `'${str}'`;
}
/**
* Combine the strings of generated code into a single interpolated string.
* Each element of `vals` is expected to be a string literal or a codegen'd
@@ -1,7 +1,7 @@
import {ListWrapper} from 'angular2/src/facade/collection';
import {BaseException, Json} from 'angular2/src/facade/lang';
import {CodegenNameUtil} from './codegen_name_util';
import {codify, combineGeneratedStrings} from './codegen_facade';
import {codify, combineGeneratedStrings, rawString} from './codegen_facade';
import {ProtoRecord, RecordType} from './proto_record';
/**
@@ -12,14 +12,28 @@ export class CodegenLogicUtil {
/**
* Generates a statement which updates the local variable representing `protoRec` with the current
* value of the record.
* value of the record. Used by property bindings.
*/
genUpdateCurrentValue(protoRec: ProtoRecord): string {
genPropertyBindingEvalValue(protoRec: ProtoRecord): string {
return this.genEvalValue(protoRec, idx => this._names.getLocalName(idx),
this._names.getLocalsAccessorName());
}
/**
* Generates a statement which updates the local variable representing `protoRec` with the current
* value of the record. Used by event bindings.
*/
genEventBindingEvalValue(eventRecord: any, protoRec: ProtoRecord): string {
return this.genEvalValue(protoRec, idx => this._names.getEventLocalName(eventRecord, idx),
"locals");
}
private genEvalValue(protoRec: ProtoRecord, getLocalName: Function,
localsAccessor: string): string {
var context = (protoRec.contextIndex == -1) ?
this._names.getDirectiveName(protoRec.directiveIndex) :
this._names.getLocalName(protoRec.contextIndex);
var argString =
ListWrapper.map(protoRec.args, (arg) => this._names.getLocalName(arg)).join(", ");
getLocalName(protoRec.contextIndex);
var argString = ListWrapper.map(protoRec.args, (arg) => getLocalName(arg)).join(", ");
var rhs: string;
switch (protoRec.mode) {
@@ -31,7 +45,7 @@ export class CodegenLogicUtil {
rhs = codify(protoRec.funcOrValue);
break;
case RecordType.PROPERTY:
case RecordType.PROPERTY_READ:
rhs = `${context}.${protoRec.name}`;
break;
@@ -39,8 +53,12 @@ export class CodegenLogicUtil {
rhs = `${this._utilName}.isValueBlank(${context}) ? null : ${context}.${protoRec.name}`;
break;
case RecordType.PROPERTY_WRITE:
rhs = `${context}.${protoRec.name} = ${getLocalName(protoRec.args[0])}`;
break;
case RecordType.LOCAL:
rhs = `${this._names.getLocalsAccessorName()}.get('${protoRec.name}')`;
rhs = `${localsAccessor}.get(${rawString(protoRec.name)})`;
break;
case RecordType.INVOKE_METHOD:
@@ -68,16 +86,25 @@ export class CodegenLogicUtil {
rhs = this._genInterpolation(protoRec);
break;
case RecordType.KEYED_ACCESS:
rhs = `${context}[${this._names.getLocalName(protoRec.args[0])}]`;
case RecordType.KEYED_READ:
rhs = `${context}[${getLocalName(protoRec.args[0])}]`;
break;
case RecordType.KEYED_WRITE:
rhs = `${context}[${getLocalName(protoRec.args[0])}] = ${getLocalName(protoRec.args[1])}`;
break;
case RecordType.CHAIN:
rhs = 'null';
break;
default:
throw new BaseException(`Unknown operation ${protoRec.mode}`);
}
return `${this._names.getLocalName(protoRec.selfIndex)} = ${rhs};`;
return `${getLocalName(protoRec.selfIndex)} = ${rhs};`;
}
_genInterpolation(protoRec: ProtoRecord): string {
var iVals = [];
for (var i = 0; i < protoRec.args.length; ++i) {
@@ -1,9 +1,10 @@
import {RegExpWrapper, StringWrapper} from 'angular2/src/facade/lang';
import {List, ListWrapper} from 'angular2/src/facade/collection';
import {List, ListWrapper, MapWrapper, Map} from 'angular2/src/facade/collection';
import {DirectiveIndex} from './directive_record';
import {ProtoRecord} from './proto_record';
import {EventBinding} from './event_binding';
// The names of these fields must be kept in sync with abstract_change_detector.ts or change
// detection will fail.
@@ -41,14 +42,25 @@ export class CodegenNameUtil {
* See [sanitizeName] for details.
*/
_sanitizedNames: List<string>;
_sanitizedEventNames: Map<EventBinding, List<string>>;
constructor(private records: List<ProtoRecord>, private directiveRecords: List<any>,
private utilName: string) {
constructor(private records: List<ProtoRecord>, private eventBindings: EventBinding[],
private directiveRecords: List<any>, private utilName: string) {
this._sanitizedNames = ListWrapper.createFixedSize(this.records.length + 1);
this._sanitizedNames[CONTEXT_INDEX] = _CONTEXT_ACCESSOR;
for (var i = 0, iLen = this.records.length; i < iLen; ++i) {
this._sanitizedNames[i + 1] = sanitizeName(`${this.records[i].name}${i}`);
}
this._sanitizedEventNames = new Map();
for (var ebIndex = 0; ebIndex < eventBindings.length; ++ebIndex) {
var eb = eventBindings[ebIndex];
var names = [_CONTEXT_ACCESSOR];
for (var i = 0, iLen = eb.records.length; i < iLen; ++i) {
names.push(sanitizeName(`${eb.records[i].name}${i}_${ebIndex}`));
}
this._sanitizedEventNames.set(eb, names);
}
}
_addFieldPrefix(name: string): string { return `${_FIELD_PREFIX}${name}`; }
@@ -73,6 +85,10 @@ export class CodegenNameUtil {
getLocalName(idx: int): string { return `l_${this._sanitizedNames[idx]}`; }
getEventLocalName(eb: EventBinding, idx: int): string {
return `l_${MapWrapper.get(this._sanitizedEventNames, eb)[idx]}`;
}
getChangeName(idx: int): string { return `c_${this._sanitizedNames[idx]}`; }
/**
@@ -100,6 +116,23 @@ export class CodegenNameUtil {
return `var ${ListWrapper.join(declarations, ',')};${assignmentsCode}`;
}
/**
* Generate a statement initializing local variables for event handlers.
*/
genInitEventLocals(): string {
var res = [`${this.getLocalName(CONTEXT_INDEX)} = ${this.getFieldName(CONTEXT_INDEX)}`];
MapWrapper.forEach(this._sanitizedEventNames, (names, eb) => {
for (var i = 0; i < names.length; ++i) {
if (i !== CONTEXT_INDEX) {
res.push(this.getEventLocalName(eb, i));
}
}
});
return res.length > 1 ? `var ${res.join(',')};` : '';
}
getPreventDefaultAccesor(): string { return "preventDefault"; }
getFieldCount(): int { return this._sanitizedNames.length; }
getFieldName(idx: int): string { return this._addFieldPrefix(this._sanitizedNames[idx]); }
@@ -2,7 +2,9 @@ import {isPresent, isBlank, BaseException, FunctionWrapper} from 'angular2/src/f
import {List, ListWrapper, MapWrapper, StringMapWrapper} from 'angular2/src/facade/collection';
import {AbstractChangeDetector} from './abstract_change_detector';
import {EventBinding} from './event_binding';
import {BindingRecord} from './binding_record';
import {Locals} from './parser/locals';
import {ChangeDetectionUtil, SimpleChange} from './change_detection_util';
@@ -16,7 +18,8 @@ export class DynamicChangeDetector extends AbstractChangeDetector<any> {
directives: any = null;
constructor(id: string, changeDetectionStrategy: string, dispatcher: any,
protos: List<ProtoRecord>, directiveRecords: List<any>) {
protos: List<ProtoRecord>, public eventBindings: EventBinding[],
directiveRecords: List<any>) {
super(id, dispatcher, protos, directiveRecords,
ChangeDetectionUtil.changeDetectionMode(changeDetectionStrategy));
var len = protos.length + 1;
@@ -28,6 +31,41 @@ export class DynamicChangeDetector extends AbstractChangeDetector<any> {
this.dehydrateDirectives(false);
}
handleEvent(eventName: string, elIndex: number, locals: Locals): boolean {
var preventDefault = false;
this._matchingEventBindings(eventName, elIndex)
.forEach(rec => {
var res = this._processEventBinding(rec, locals);
if (res === false) {
preventDefault = true;
}
});
return preventDefault;
}
_processEventBinding(eb: EventBinding, locals: Locals): any {
var values = ListWrapper.createFixedSize(eb.records.length);
values[0] = this.values[0];
for (var i = 0; i < eb.records.length; ++i) {
var proto = eb.records[i];
var res = this._calculateCurrValue(proto, values, locals);
if (proto.lastInBinding) {
return res;
} else {
this._writeSelf(proto, res, values);
}
}
throw new BaseException("Cannot be reached");
}
_matchingEventBindings(eventName: string, elIndex: number): EventBinding[] {
return ListWrapper.filter(this.eventBindings,
eb => eb.eventName == eventName && eb.elIndex === elIndex);
}
hydrateDirectives(directives: any): void {
this.values[0] = this.context;
this.directives = directives;
@@ -79,7 +117,7 @@ export class DynamicChangeDetector extends AbstractChangeDetector<any> {
}
} else {
var change = this._check(proto, throwOnChange);
var change = this._check(proto, throwOnChange, this.values, this.locals);
if (isPresent(change)) {
this._updateDirectiveOrElement(change, bindingRecord);
isChanged = true;
@@ -137,33 +175,33 @@ export class DynamicChangeDetector extends AbstractChangeDetector<any> {
_getDetectorFor(directiveIndex) { return this.directives.getDetectorFor(directiveIndex); }
_check(proto: ProtoRecord, throwOnChange: boolean): SimpleChange {
_check(proto: ProtoRecord, throwOnChange: boolean, values: any[], locals: Locals): SimpleChange {
if (proto.isPipeRecord()) {
return this._pipeCheck(proto, throwOnChange);
return this._pipeCheck(proto, throwOnChange, values);
} else {
return this._referenceCheck(proto, throwOnChange);
return this._referenceCheck(proto, throwOnChange, values, locals);
}
}
_referenceCheck(proto: ProtoRecord, throwOnChange: boolean) {
_referenceCheck(proto: ProtoRecord, throwOnChange: boolean, values: any[], locals: Locals) {
if (this._pureFuncAndArgsDidNotChange(proto)) {
this._setChanged(proto, false);
return null;
}
var currValue = this._calculateCurrValue(proto);
var currValue = this._calculateCurrValue(proto, values, locals);
if (proto.shouldBeChecked()) {
var prevValue = this._readSelf(proto);
var prevValue = this._readSelf(proto, values);
if (!isSame(prevValue, currValue)) {
if (proto.lastInBinding) {
var change = ChangeDetectionUtil.simpleChange(prevValue, currValue);
if (throwOnChange) this.throwOnChangeError(prevValue, currValue);
this._writeSelf(proto, currValue);
this._writeSelf(proto, currValue, values);
this._setChanged(proto, true);
return change;
} else {
this._writeSelf(proto, currValue);
this._writeSelf(proto, currValue, values);
this._setChanged(proto, true);
return null;
}
@@ -173,70 +211,88 @@ export class DynamicChangeDetector extends AbstractChangeDetector<any> {
}
} else {
this._writeSelf(proto, currValue);
this._writeSelf(proto, currValue, values);
this._setChanged(proto, true);
return null;
}
}
_calculateCurrValue(proto: ProtoRecord) {
_calculateCurrValue(proto: ProtoRecord, values: any[], locals: Locals) {
switch (proto.mode) {
case RecordType.SELF:
return this._readContext(proto);
return this._readContext(proto, values);
case RecordType.CONST:
return proto.funcOrValue;
case RecordType.PROPERTY:
var context = this._readContext(proto);
case RecordType.PROPERTY_READ:
var context = this._readContext(proto, values);
return proto.funcOrValue(context);
case RecordType.SAFE_PROPERTY:
var context = this._readContext(proto);
var context = this._readContext(proto, values);
return isBlank(context) ? null : proto.funcOrValue(context);
case RecordType.PROPERTY_WRITE:
var context = this._readContext(proto, values);
var value = this._readArgs(proto, values)[0];
proto.funcOrValue(context, value);
return value;
case RecordType.KEYED_WRITE:
var context = this._readContext(proto, values);
var key = this._readArgs(proto, values)[0];
var value = this._readArgs(proto, values)[1];
context[key] = value;
return value;
case RecordType.LOCAL:
return this.locals.get(proto.name);
return locals.get(proto.name);
case RecordType.INVOKE_METHOD:
var context = this._readContext(proto);
var args = this._readArgs(proto);
var context = this._readContext(proto, values);
var args = this._readArgs(proto, values);
return proto.funcOrValue(context, args);
case RecordType.SAFE_INVOKE_METHOD:
var context = this._readContext(proto);
var context = this._readContext(proto, values);
if (isBlank(context)) {
return null;
}
var args = this._readArgs(proto);
var args = this._readArgs(proto, values);
return proto.funcOrValue(context, args);
case RecordType.KEYED_ACCESS:
var arg = this._readArgs(proto)[0];
return this._readContext(proto)[arg];
case RecordType.KEYED_READ:
var arg = this._readArgs(proto, values)[0];
return this._readContext(proto, values)[arg];
case RecordType.CHAIN:
var args = this._readArgs(proto, values);
return args[args.length - 1];
case RecordType.INVOKE_CLOSURE:
return FunctionWrapper.apply(this._readContext(proto), this._readArgs(proto));
return FunctionWrapper.apply(this._readContext(proto, values),
this._readArgs(proto, values));
case RecordType.INTERPOLATE:
case RecordType.PRIMITIVE_OP:
case RecordType.COLLECTION_LITERAL:
return FunctionWrapper.apply(proto.funcOrValue, this._readArgs(proto));
return FunctionWrapper.apply(proto.funcOrValue, this._readArgs(proto, values));
default:
throw new BaseException(`Unknown operation ${proto.mode}`);
}
}
_pipeCheck(proto: ProtoRecord, throwOnChange: boolean) {
var context = this._readContext(proto);
var args = this._readArgs(proto);
_pipeCheck(proto: ProtoRecord, throwOnChange: boolean, values: any[]) {
var context = this._readContext(proto, values);
var args = this._readArgs(proto, values);
var pipe = this._pipeFor(proto, context);
var currValue = pipe.transform(context, args);
if (proto.shouldBeChecked()) {
var prevValue = this._readSelf(proto);
var prevValue = this._readSelf(proto, values);
if (!isSame(prevValue, currValue)) {
currValue = ChangeDetectionUtil.unwrapValue(currValue);
@@ -244,13 +300,13 @@ export class DynamicChangeDetector extends AbstractChangeDetector<any> {
var change = ChangeDetectionUtil.simpleChange(prevValue, currValue);
if (throwOnChange) this.throwOnChangeError(prevValue, currValue);
this._writeSelf(proto, currValue);
this._writeSelf(proto, currValue, values);
this._setChanged(proto, true);
return change;
} else {
this._writeSelf(proto, currValue);
this._writeSelf(proto, currValue, values);
this._setChanged(proto, true);
return null;
}
@@ -259,7 +315,7 @@ export class DynamicChangeDetector extends AbstractChangeDetector<any> {
return null;
}
} else {
this._writeSelf(proto, currValue);
this._writeSelf(proto, currValue, values);
this._setChanged(proto, true);
return null;
}
@@ -274,19 +330,19 @@ export class DynamicChangeDetector extends AbstractChangeDetector<any> {
return pipe;
}
_readContext(proto: ProtoRecord) {
_readContext(proto: ProtoRecord, values: any[]) {
if (proto.contextIndex == -1) {
return this._getDirectiveFor(proto.directiveIndex);
} else {
return this.values[proto.contextIndex];
return values[proto.contextIndex];
}
return this.values[proto.contextIndex];
return values[proto.contextIndex];
}
_readSelf(proto: ProtoRecord) { return this.values[proto.selfIndex]; }
_readSelf(proto: ProtoRecord, values: any[]) { return values[proto.selfIndex]; }
_writeSelf(proto: ProtoRecord, value) { this.values[proto.selfIndex] = value; }
_writeSelf(proto: ProtoRecord, value, values: any[]) { values[proto.selfIndex] = value; }
_readPipe(proto: ProtoRecord) { return this.localPipes[proto.selfIndex]; }
@@ -310,11 +366,11 @@ export class DynamicChangeDetector extends AbstractChangeDetector<any> {
return false;
}
_readArgs(proto: ProtoRecord) {
_readArgs(proto: ProtoRecord, values: any[]) {
var res = ListWrapper.createFixedSize(proto.args.length);
var args = proto.args;
for (var i = 0; i < args.length; ++i) {
res[i] = this.values[args[i]];
res[i] = values[args[i]];
}
return res;
}
@@ -0,0 +1,7 @@
import {DirectiveIndex} from './directive_record';
import {ProtoRecord} from './proto_record';
export class EventBinding {
constructor(public eventName: string, public elIndex: number, public dirIndex: DirectiveIndex,
public records: ProtoRecord[]) {}
}
@@ -62,6 +62,7 @@ export interface ChangeDetector {
dehydrate(): void;
markPathToRootAsCheckOnce(): void;
handleEvent(eventName: string, elIndex: number, locals: Locals);
detectChanges(): void;
checkNoChanges(): void;
}
@@ -70,7 +71,6 @@ export interface ProtoChangeDetector { instantiate(dispatcher: ChangeDispatcher)
export class ChangeDetectorDefinition {
constructor(public id: string, public strategy: string, public variableNames: List<string>,
public bindingRecords: List<BindingRecord>,
public directiveRecords: List<DirectiveRecord>,
public generateCheckNoChanges: boolean) {}
public bindingRecords: BindingRecord[], public eventRecords: BindingRecord[],
public directiveRecords: DirectiveRecord[], public generateCheckNoChanges: boolean) {}
}
@@ -4,7 +4,7 @@ import {ProtoChangeDetector, ChangeDetector, ChangeDetectorDefinition} from './i
import {ChangeDetectorJITGenerator} from './change_detection_jit_generator';
import {coalesce} from './coalesce';
import {ProtoRecordBuilder} from './proto_change_detector';
import {createPropertyRecords, createEventRecords} from './proto_change_detector';
export class JitProtoChangeDetector implements ProtoChangeDetector {
_factory: Function;
@@ -18,13 +18,11 @@ export class JitProtoChangeDetector implements ProtoChangeDetector {
instantiate(dispatcher: any): ChangeDetector { return this._factory(dispatcher); }
_createFactory(definition: ChangeDetectorDefinition) {
var recordBuilder = new ProtoRecordBuilder();
ListWrapper.forEach(definition.bindingRecords,
(b) => { recordBuilder.add(b, definition.variableNames); });
var records = coalesce(recordBuilder.records);
return new ChangeDetectorJITGenerator(definition.id, definition.strategy, records,
this.definition.directiveRecords,
this.definition.generateCheckNoChanges)
var propertyBindingRecords = createPropertyRecords(definition);
var eventBindingRecords = createEventRecords(definition);
return new ChangeDetectorJITGenerator(
definition.id, definition.strategy, propertyBindingRecords, eventBindingRecords,
this.definition.directiveRecords, this.definition.generateCheckNoChanges)
.generate();
}
}
@@ -1,30 +1,18 @@
import {isBlank, isPresent, FunctionWrapper, BaseException} from "angular2/src/facade/lang";
import {List, Map, ListWrapper, StringMapWrapper} from "angular2/src/facade/collection";
import {Locals} from "./locals";
export class AST {
eval(context: any, locals: Locals): any { throw new BaseException("Not supported"); }
get isAssignable(): boolean { return false; }
assign(context: any, locals: Locals, value: any) { throw new BaseException("Not supported"); }
visit(visitor: AstVisitor): any { return null; }
toString(): string { return "AST"; }
}
export class EmptyExpr extends AST {
eval(context: any, locals: Locals): any { return null; }
visit(visitor: AstVisitor) {
// do nothing
}
}
export class ImplicitReceiver extends AST {
eval(context: any, locals: Locals): any { return context; }
visit(visitor: AstVisitor): any { return visitor.visitImplicitReceiver(this); }
}
@@ -33,112 +21,45 @@ export class ImplicitReceiver extends AST {
*/
export class Chain extends AST {
constructor(public expressions: List<any>) { super(); }
eval(context: any, locals: Locals): any {
var result;
for (var i = 0; i < this.expressions.length; i++) {
var last = this.expressions[i].eval(context, locals);
if (isPresent(last)) result = last;
}
return result;
}
visit(visitor: AstVisitor): any { return visitor.visitChain(this); }
}
export class Conditional extends AST {
constructor(public condition: AST, public trueExp: AST, public falseExp: AST) { super(); }
eval(context: any, locals: Locals): any {
if (this.condition.eval(context, locals)) {
return this.trueExp.eval(context, locals);
} else {
return this.falseExp.eval(context, locals);
}
}
visit(visitor: AstVisitor): any { return visitor.visitConditional(this); }
}
export class If extends AST {
constructor(public condition: AST, public trueExp: AST, public falseExp?: AST) { super(); }
eval(context: any, locals: Locals) {
if (this.condition.eval(context, locals)) {
this.trueExp.eval(context, locals);
} else if (isPresent(this.falseExp)) {
this.falseExp.eval(context, locals);
}
}
visit(visitor: AstVisitor): any { return visitor.visitIf(this); }
}
export class AccessMember extends AST {
constructor(public receiver: AST, public name: string, public getter: Function,
public setter: Function) {
super();
}
eval(context: any, locals: Locals): any {
if (this.receiver instanceof ImplicitReceiver && isPresent(locals) &&
locals.contains(this.name)) {
return locals.get(this.name);
} else {
var evaluatedReceiver = this.receiver.eval(context, locals);
return this.getter(evaluatedReceiver);
}
}
get isAssignable(): boolean { return true; }
assign(context: any, locals: Locals, value: any): any {
var evaluatedContext = this.receiver.eval(context, locals);
if (this.receiver instanceof ImplicitReceiver && isPresent(locals) &&
locals.contains(this.name)) {
throw new BaseException(`Cannot reassign a variable binding ${this.name}`);
} else {
return this.setter(evaluatedContext, value);
}
}
visit(visitor: AstVisitor): any { return visitor.visitAccessMember(this); }
export class PropertyRead extends AST {
constructor(public receiver: AST, public name: string, public getter: Function) { super(); }
visit(visitor: AstVisitor): any { return visitor.visitPropertyRead(this); }
}
export class SafeAccessMember extends AST {
constructor(public receiver: AST, public name: string, public getter: Function,
public setter: Function) {
export class PropertyWrite extends AST {
constructor(public receiver: AST, public name: string, public setter: Function,
public value: AST) {
super();
}
eval(context: any, locals: Locals): any {
var evaluatedReceiver = this.receiver.eval(context, locals);
return isBlank(evaluatedReceiver) ? null : this.getter(evaluatedReceiver);
}
visit(visitor: AstVisitor): any { return visitor.visitSafeAccessMember(this); }
visit(visitor: AstVisitor): any { return visitor.visitPropertyWrite(this); }
}
export class KeyedAccess extends AST {
export class SafePropertyRead extends AST {
constructor(public receiver: AST, public name: string, public getter: Function) { super(); }
visit(visitor: AstVisitor): any { return visitor.visitSafePropertyRead(this); }
}
export class KeyedRead extends AST {
constructor(public obj: AST, public key: AST) { super(); }
visit(visitor: AstVisitor): any { return visitor.visitKeyedRead(this); }
}
eval(context: any, locals: Locals): any {
var obj: any = this.obj.eval(context, locals);
var key: any = this.key.eval(context, locals);
return obj[key];
}
get isAssignable(): boolean { return true; }
assign(context: any, locals: Locals, value: any): any {
var obj: any = this.obj.eval(context, locals);
var key: any = this.key.eval(context, locals);
obj[key] = value;
return value;
}
visit(visitor: AstVisitor): any { return visitor.visitKeyedAccess(this); }
export class KeyedWrite extends AST {
constructor(public obj: AST, public key: AST, public value: AST) { super(); }
visit(visitor: AstVisitor): any { return visitor.visitKeyedWrite(this); }
}
export class BindingPipe extends AST {
@@ -149,133 +70,39 @@ export class BindingPipe extends AST {
export class LiteralPrimitive extends AST {
constructor(public value) { super(); }
eval(context: any, locals: Locals): any { return this.value; }
visit(visitor: AstVisitor): any { return visitor.visitLiteralPrimitive(this); }
}
export class LiteralArray extends AST {
constructor(public expressions: List<any>) { super(); }
eval(context: any, locals: Locals): any {
return ListWrapper.map(this.expressions, (e) => e.eval(context, locals));
}
visit(visitor: AstVisitor): any { return visitor.visitLiteralArray(this); }
}
export class LiteralMap extends AST {
constructor(public keys: List<any>, public values: List<any>) { super(); }
eval(context: any, locals: Locals): any {
var res = StringMapWrapper.create();
for (var i = 0; i < this.keys.length; ++i) {
StringMapWrapper.set(res, this.keys[i], this.values[i].eval(context, locals));
}
return res;
}
visit(visitor: AstVisitor): any { return visitor.visitLiteralMap(this); }
}
export class Interpolation extends AST {
constructor(public strings: List<any>, public expressions: List<any>) { super(); }
eval(context: any, locals: Locals): any {
throw new BaseException("evaluating an Interpolation is not supported");
}
visit(visitor: AstVisitor) { visitor.visitInterpolation(this); }
}
export class Binary extends AST {
constructor(public operation: string, public left: AST, public right: AST) { super(); }
eval(context: any, locals: Locals): any {
var left: any = this.left.eval(context, locals);
switch (this.operation) {
case '&&':
return left && this.right.eval(context, locals);
case '||':
return left || this.right.eval(context, locals);
}
var right: any = this.right.eval(context, locals);
switch (this.operation) {
case '+':
return left + right;
case '-':
return left - right;
case '*':
return left * right;
case '/':
return left / right;
case '%':
return left % right;
case '==':
return left == right;
case '!=':
return left != right;
case '===':
return left === right;
case '!==':
return left !== right;
case '<':
return left < right;
case '>':
return left > right;
case '<=':
return left <= right;
case '>=':
return left >= right;
case '^':
return left ^ right;
case '&':
return left & right;
}
throw 'Internal error [$operation] not handled';
}
visit(visitor: AstVisitor): any { return visitor.visitBinary(this); }
}
export class PrefixNot extends AST {
constructor(public expression: AST) { super(); }
eval(context: any, locals: Locals): any { return !this.expression.eval(context, locals); }
visit(visitor: AstVisitor): any { return visitor.visitPrefixNot(this); }
}
export class Assignment extends AST {
constructor(public target: AST, public value: any) { super(); }
eval(context: any, locals: Locals): any {
return this.target.assign(context, locals, this.value.eval(context, locals));
}
visit(visitor: AstVisitor): any { return visitor.visitAssignment(this); }
}
export class MethodCall extends AST {
constructor(public receiver: AST, public name: string, public fn: Function,
public args: List<any>) {
super();
}
eval(context: any, locals: Locals): any {
var evaluatedArgs = evalList(context, locals, this.args);
if (this.receiver instanceof ImplicitReceiver && isPresent(locals) &&
locals.contains(this.name)) {
var fn = locals.get(this.name);
return FunctionWrapper.apply(fn, evaluatedArgs);
} else {
var evaluatedReceiver = this.receiver.eval(context, locals);
return this.fn(evaluatedReceiver, evaluatedArgs);
}
}
visit(visitor: AstVisitor): any { return visitor.visitMethodCall(this); }
}
@@ -284,44 +111,17 @@ export class SafeMethodCall extends AST {
public args: List<any>) {
super();
}
eval(context: any, locals: Locals): any {
var evaluatedReceiver = this.receiver.eval(context, locals);
if (isBlank(evaluatedReceiver)) return null;
var evaluatedArgs = evalList(context, locals, this.args);
return this.fn(evaluatedReceiver, evaluatedArgs);
}
visit(visitor: AstVisitor): any { return visitor.visitSafeMethodCall(this); }
}
export class FunctionCall extends AST {
constructor(public target: AST, public args: List<any>) { super(); }
eval(context: any, locals: Locals): any {
var obj: any = this.target.eval(context, locals);
if (!(obj instanceof Function)) {
throw new BaseException(`${obj} is not a function`);
}
return FunctionWrapper.apply(obj, evalList(context, locals, this.args));
}
visit(visitor: AstVisitor): any { return visitor.visitFunctionCall(this); }
}
export class ASTWithSource extends AST {
constructor(public ast: AST, public source: string, public location: string) { super(); }
eval(context: any, locals: Locals): any { return this.ast.eval(context, locals); }
get isAssignable(): boolean { return this.ast.isAssignable; }
assign(context: any, locals: Locals, value: any): any {
return this.ast.assign(context, locals, value);
}
visit(visitor: AstVisitor): any { return this.ast.visit(visitor); }
toString(): string { return `${this.source} in ${this.location}`; }
}
@@ -331,8 +131,8 @@ export class TemplateBinding {
}
export interface AstVisitor {
visitAccessMember(ast: AccessMember): any;
visitAssignment(ast: Assignment): any;
visitPropertyRead(ast: PropertyRead): any;
visitPropertyWrite(ast: PropertyWrite): any;
visitBinary(ast: Binary): any;
visitChain(ast: Chain): any;
visitConditional(ast: Conditional): any;
@@ -341,13 +141,14 @@ export interface AstVisitor {
visitFunctionCall(ast: FunctionCall): any;
visitImplicitReceiver(ast: ImplicitReceiver): any;
visitInterpolation(ast: Interpolation): any;
visitKeyedAccess(ast: KeyedAccess): any;
visitKeyedRead(ast: KeyedRead): any;
visitKeyedWrite(ast: KeyedWrite): any;
visitLiteralArray(ast: LiteralArray): any;
visitLiteralMap(ast: LiteralMap): any;
visitLiteralPrimitive(ast: LiteralPrimitive): any;
visitMethodCall(ast: MethodCall): any;
visitPrefixNot(ast: PrefixNot): any;
visitSafeAccessMember(ast: SafeAccessMember): any;
visitSafePropertyRead(ast: SafePropertyRead): any;
visitSafeMethodCall(ast: SafeMethodCall): any;
}
@@ -362,12 +163,16 @@ export class AstTransformer implements AstVisitor {
return new LiteralPrimitive(ast.value);
}
visitAccessMember(ast: AccessMember): AccessMember {
return new AccessMember(ast.receiver.visit(this), ast.name, ast.getter, ast.setter);
visitPropertyRead(ast: PropertyRead): PropertyRead {
return new PropertyRead(ast.receiver.visit(this), ast.name, ast.getter);
}
visitSafeAccessMember(ast: SafeAccessMember): SafeAccessMember {
return new SafeAccessMember(ast.receiver.visit(this), ast.name, ast.getter, ast.setter);
visitPropertyWrite(ast: PropertyWrite): PropertyWrite {
return new PropertyWrite(ast.receiver.visit(this), ast.name, ast.setter, ast.value);
}
visitSafePropertyRead(ast: SafePropertyRead): SafePropertyRead {
return new SafePropertyRead(ast.receiver.visit(this), ast.name, ast.getter);
}
visitMethodCall(ast: MethodCall): MethodCall {
@@ -405,8 +210,12 @@ export class AstTransformer implements AstVisitor {
return new BindingPipe(ast.exp.visit(this), ast.name, this.visitAll(ast.args));
}
visitKeyedAccess(ast: KeyedAccess): KeyedAccess {
return new KeyedAccess(ast.obj.visit(this), ast.key.visit(this));
visitKeyedRead(ast: KeyedRead): KeyedRead {
return new KeyedRead(ast.obj.visit(this), ast.key.visit(this));
}
visitKeyedWrite(ast: KeyedWrite): KeyedWrite {
return new KeyedWrite(ast.obj.visit(this), ast.key.visit(this), ast.value.visit(this));
}
visitAll(asts: List<any>): List<any> {
@@ -419,39 +228,8 @@ export class AstTransformer implements AstVisitor {
visitChain(ast: Chain): Chain { return new Chain(this.visitAll(ast.expressions)); }
visitAssignment(ast: Assignment): Assignment {
return new Assignment(ast.target.visit(this), ast.value.visit(this));
}
visitIf(ast: If): If {
let falseExp = isPresent(ast.falseExp) ? ast.falseExp.visit(this) : null;
return new If(ast.condition.visit(this), ast.trueExp.visit(this), falseExp);
}
}
var _evalListCache = [
[],
[0],
[0, 0],
[0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 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>): any[] {
var length = exps.length;
if (length > 10) {
throw new BaseException("Cannot have more than 10 argument");
}
var result = _evalListCache[length];
for (var i = 0; i < length; i++) {
result[i] = exps[i].eval(context, locals);
}
return result;
}
}
@@ -21,17 +21,18 @@ import {
AST,
EmptyExpr,
ImplicitReceiver,
AccessMember,
SafeAccessMember,
PropertyRead,
PropertyWrite,
SafePropertyRead,
LiteralPrimitive,
Binary,
PrefixNot,
Conditional,
If,
BindingPipe,
Assignment,
Chain,
KeyedAccess,
KeyedRead,
KeyedWrite,
LiteralArray,
LiteralMap,
Interpolation,
@@ -245,27 +246,7 @@ export class _ParseAST {
return result;
}
parseExpression(): AST {
var start = this.inputIndex;
var result = this.parseConditional();
while (this.next.isOperator('=')) {
if (!result.isAssignable) {
var end = this.inputIndex;
var expression = this.input.substring(start, end);
this.error(`Expression ${expression} is not assignable`);
}
if (!this.parseAction) {
this.error("Binding expression cannot contain assignments");
}
this.expectOperator('=');
result = new Assignment(result, this.parseConditional());
}
return result;
}
parseExpression(): AST { return this.parseConditional(); }
parseConditional(): AST {
var start = this.inputIndex;
@@ -393,7 +374,12 @@ export class _ParseAST {
} else if (this.optionalCharacter($LBRACKET)) {
var key = this.parsePipe();
this.expectCharacter($RBRACKET);
result = new KeyedAccess(result, key);
if (this.optionalOperator("=")) {
var value = this.parseConditional();
result = new KeyedWrite(result, key, value);
} else {
result = new KeyedRead(result, key);
}
} else if (this.optionalCharacter($LPAREN)) {
var args = this.parseCallArguments();
@@ -506,9 +492,28 @@ export class _ParseAST {
} else {
let getter = this.reflector.getter(id);
let setter = this.reflector.setter(id);
return isSafe ? new SafeAccessMember(receiver, id, getter, setter) :
new AccessMember(receiver, id, getter, setter);
if (isSafe) {
if (this.optionalOperator("=")) {
this.error("The '?.' operator cannot be used in the assignment");
} else {
return new SafePropertyRead(receiver, id, getter);
}
} else {
if (this.optionalOperator("=")) {
if (!this.parseAction) {
this.error("Bindings cannot contain assignments");
}
let value = this.parseConditional();
return new PropertyWrite(receiver, id, setter, value);
} else {
return new PropertyRead(receiver, id, getter);
}
}
}
return null;
}
parseCallArguments(): BindingPipe[] {
@@ -629,9 +634,11 @@ class SimpleExpressionChecker implements AstVisitor {
visitLiteralPrimitive(ast: LiteralPrimitive) {}
visitAccessMember(ast: AccessMember) {}
visitPropertyRead(ast: PropertyRead) {}
visitSafeAccessMember(ast: SafeAccessMember) { this.simple = false; }
visitPropertyWrite(ast: PropertyWrite) { this.simple = false; }
visitSafePropertyRead(ast: SafePropertyRead) { this.simple = false; }
visitMethodCall(ast: MethodCall) { this.simple = false; }
@@ -651,7 +658,9 @@ class SimpleExpressionChecker implements AstVisitor {
visitPipe(ast: BindingPipe) { this.simple = false; }
visitKeyedAccess(ast: KeyedAccess) { this.simple = false; }
visitKeyedRead(ast: KeyedRead) { this.simple = false; }
visitKeyedWrite(ast: KeyedWrite) { this.simple = false; }
visitAll(asts: List<any>): List<any> {
var res = ListWrapper.createFixedSize(asts.length);
@@ -663,7 +672,5 @@ class SimpleExpressionChecker implements AstVisitor {
visitChain(ast: Chain) { this.simple = false; }
visitAssignment(ast: Assignment) { this.simple = false; }
visitIf(ast: If) { this.simple = false; }
}
@@ -2,8 +2,9 @@ import {BaseException, Type, isBlank, isPresent, isString} from 'angular2/src/fa
import {List, ListWrapper, MapWrapper, StringMapWrapper} from 'angular2/src/facade/collection';
import {
AccessMember,
Assignment,
PropertyRead,
PropertyWrite,
KeyedWrite,
AST,
ASTWithSource,
AstVisitor,
@@ -15,13 +16,13 @@ import {
FunctionCall,
ImplicitReceiver,
Interpolation,
KeyedAccess,
KeyedRead,
LiteralArray,
LiteralMap,
LiteralPrimitive,
MethodCall,
PrefixNot,
SafeAccessMember,
SafePropertyRead,
SafeMethodCall
} from './parser/ast';
@@ -30,29 +31,42 @@ import {ChangeDetectionUtil} from './change_detection_util';
import {DynamicChangeDetector} from './dynamic_change_detector';
import {BindingRecord} from './binding_record';
import {DirectiveRecord, DirectiveIndex} from './directive_record';
import {EventBinding} from './event_binding';
import {coalesce} from './coalesce';
import {ProtoRecord, RecordType} from './proto_record';
export class DynamicProtoChangeDetector implements ProtoChangeDetector {
_records: List<ProtoRecord>;
_propertyBindingRecords: ProtoRecord[];
_eventBindingRecords: EventBinding[];
constructor(private definition: ChangeDetectorDefinition) {
this._records = this._createRecords(definition);
this._propertyBindingRecords = createPropertyRecords(definition);
this._eventBindingRecords = createEventRecords(definition);
}
instantiate(dispatcher: any): ChangeDetector {
return new DynamicChangeDetector(this.definition.id, this.definition.strategy, dispatcher,
this._records, this.definition.directiveRecords);
this._propertyBindingRecords, this._eventBindingRecords,
this.definition.directiveRecords);
}
}
_createRecords(definition: ChangeDetectorDefinition) {
var recordBuilder = new ProtoRecordBuilder();
ListWrapper.forEach(definition.bindingRecords,
(b) => { recordBuilder.add(b, definition.variableNames); });
return coalesce(recordBuilder.records);
}
export function createPropertyRecords(definition: ChangeDetectorDefinition): ProtoRecord[] {
var recordBuilder = new ProtoRecordBuilder();
ListWrapper.forEach(definition.bindingRecords,
(b) => { recordBuilder.add(b, definition.variableNames); });
return coalesce(recordBuilder.records);
}
export function createEventRecords(definition: ChangeDetectorDefinition): EventBinding[] {
// TODO: vsavkin: remove $event when the compiler handles render-side variables properly
var varNames = ListWrapper.concat(['$event'], definition.variableNames);
return definition.eventRecords.map(er => {
var records = _ConvertAstIntoProtoRecords.create(er, varNames);
var dirIndex = er.implicitReceiver instanceof DirectiveIndex ? er.implicitReceiver : null;
return new EventBinding(er.eventName, er.elementIndex, dirIndex, records);
});
}
export class ProtoRecordBuilder {
@@ -105,6 +119,13 @@ class _ConvertAstIntoProtoRecords implements AstVisitor {
b.ast.visit(c);
}
static create(b: BindingRecord, variableNames: List<any>): ProtoRecord[] {
var rec = [];
_ConvertAstIntoProtoRecords.append(rec, b, variableNames);
rec[rec.length - 1].lastInBinding = true;
return rec;
}
visitImplicitReceiver(ast: ImplicitReceiver): any { return this._bindingRecord.implicitReceiver; }
visitInterpolation(ast: Interpolation): number {
@@ -117,17 +138,36 @@ class _ConvertAstIntoProtoRecords implements AstVisitor {
return this._addRecord(RecordType.CONST, "literal", ast.value, [], null, 0);
}
visitAccessMember(ast: AccessMember): number {
visitPropertyRead(ast: PropertyRead): number {
var receiver = ast.receiver.visit(this);
if (isPresent(this._variableNames) && ListWrapper.contains(this._variableNames, ast.name) &&
ast.receiver instanceof ImplicitReceiver) {
return this._addRecord(RecordType.LOCAL, ast.name, ast.name, [], null, receiver);
} else {
return this._addRecord(RecordType.PROPERTY, ast.name, ast.getter, [], null, receiver);
return this._addRecord(RecordType.PROPERTY_READ, ast.name, ast.getter, [], null, receiver);
}
}
visitSafeAccessMember(ast: SafeAccessMember): number {
visitPropertyWrite(ast: PropertyWrite): number {
if (isPresent(this._variableNames) && ListWrapper.contains(this._variableNames, ast.name) &&
ast.receiver instanceof ImplicitReceiver) {
throw new BaseException(`Cannot reassign a variable binding ${ast.name}`);
} else {
var receiver = ast.receiver.visit(this);
var value = ast.value.visit(this);
return this._addRecord(RecordType.PROPERTY_WRITE, ast.name, ast.setter, [value], null,
receiver);
}
}
visitKeyedWrite(ast: KeyedWrite): number {
var obj = ast.obj.visit(this);
var key = ast.key.visit(this);
var value = ast.value.visit(this);
return this._addRecord(RecordType.KEYED_WRITE, null, null, [key, value], null, obj);
}
visitSafePropertyRead(ast: SafePropertyRead): number {
var receiver = ast.receiver.visit(this);
return this._addRecord(RecordType.SAFE_PROPERTY, ast.name, ast.getter, [], null, receiver);
}
@@ -195,16 +235,17 @@ class _ConvertAstIntoProtoRecords implements AstVisitor {
return this._addRecord(RecordType.PIPE, ast.name, ast.name, args, null, value);
}
visitKeyedAccess(ast: KeyedAccess): number {
visitKeyedRead(ast: KeyedRead): number {
var obj = ast.obj.visit(this);
var key = ast.key.visit(this);
return this._addRecord(RecordType.KEYED_ACCESS, "keyedAccess", ChangeDetectionUtil.keyedAccess,
return this._addRecord(RecordType.KEYED_READ, "keyedAccess", ChangeDetectionUtil.keyedAccess,
[key], null, obj);
}
visitAssignment(ast: Assignment) { throw new BaseException('Not supported'); }
visitChain(ast: Chain) { throw new BaseException('Not supported'); }
visitChain(ast: Chain): number {
var args = ast.expressions.map(e => e.visit(this));
return this._addRecord(RecordType.CHAIN, "chain", null, args, null, 0);
}
visitIf(ast: If) { throw new BaseException('Not supported'); }
@@ -6,17 +6,20 @@ export enum RecordType {
SELF,
CONST,
PRIMITIVE_OP,
PROPERTY,
PROPERTY_READ,
PROPERTY_WRITE,
LOCAL,
INVOKE_METHOD,
INVOKE_CLOSURE,
KEYED_ACCESS,
KEYED_READ,
KEYED_WRITE,
PIPE,
INTERPOLATE,
SAFE_PROPERTY,
COLLECTION_LITERAL,
SAFE_INVOKE_METHOD,
DIRECTIVE_LIFECYCLE
DIRECTIVE_LIFECYCLE,
CHAIN
}
export class ProtoRecord {
@@ -1,15 +1,11 @@
import {AST} from 'angular2/src/change_detection/change_detection';
import {isBlank, isPresent, BaseException} from 'angular2/src/facade/lang';
import * as eiModule from './element_injector';
import {DirectiveBinding} from './element_injector';
import {List, StringMap} from 'angular2/src/facade/collection';
import * as viewModule from './view';
export class ElementBinder {
// updated later, so we are able to resolve cycles
nestedProtoView: viewModule.AppProtoView = null;
// updated later when events are bound
hostListeners: StringMap<string, Map<number, AST>> = null;
constructor(public index: int, public parent: ElementBinder, public distanceToParent: int,
public protoElementInjector: eiModule.ProtoElementInjector,
@@ -23,12 +23,50 @@ import {AppProtoView} from './view';
import {ElementBinder} from './element_binder';
import {ProtoElementInjector, DirectiveBinding} from './element_injector';
class BindingRecordsCreator {
export class BindingRecordsCreator {
_directiveRecordsMap: Map<number, DirectiveRecord> = new Map();
getBindingRecords(textBindings: List<ASTWithSource>,
elementBinders: List<renderApi.ElementBinder>,
allDirectiveMetadatas: List<renderApi.DirectiveMetadata>): List<BindingRecord> {
getEventBindingRecords(elementBinders: List<renderApi.ElementBinder>,
allDirectiveMetadatas: renderApi.DirectiveMetadata[]): BindingRecord[] {
var res = [];
for (var boundElementIndex = 0; boundElementIndex < elementBinders.length;
boundElementIndex++) {
var renderElementBinder = elementBinders[boundElementIndex];
this._createTemplateEventRecords(res, renderElementBinder, boundElementIndex);
this._createHostEventRecords(res, renderElementBinder, allDirectiveMetadatas,
boundElementIndex);
}
return res;
}
private _createTemplateEventRecords(res: BindingRecord[],
renderElementBinder: renderApi.ElementBinder,
boundElementIndex: number): void {
renderElementBinder.eventBindings.forEach(eb => {
res.push(BindingRecord.createForEvent(eb.source, eb.fullName, boundElementIndex));
});
}
private _createHostEventRecords(res: BindingRecord[],
renderElementBinder: renderApi.ElementBinder,
allDirectiveMetadatas: renderApi.DirectiveMetadata[],
boundElementIndex: number): void {
for (var i = 0; i < renderElementBinder.directives.length; ++i) {
var dir = renderElementBinder.directives[i];
var directiveMetadata = allDirectiveMetadatas[dir.directiveIndex];
var dirRecord = this._getDirectiveRecord(boundElementIndex, i, directiveMetadata);
dir.eventBindings.forEach(heb => {
res.push(
BindingRecord.createForHostEvent(heb.source, heb.fullName, dirRecord.directiveIndex));
});
}
}
getPropertyBindingRecords(textBindings: List<ASTWithSource>,
elementBinders: List<renderApi.ElementBinder>,
allDirectiveMetadatas:
List<renderApi.DirectiveMetadata>): List<BindingRecord> {
var bindings = [];
this._createTextNodeRecords(bindings, textBindings);
@@ -232,8 +270,10 @@ function _getChangeDetectorDefinitions(
return ListWrapper.map(nestedPvsWithIndex, (pvWithIndex) => {
var elementBinders = pvWithIndex.renderProtoView.elementBinders;
var bindingRecordsCreator = new BindingRecordsCreator();
var bindingRecords = bindingRecordsCreator.getBindingRecords(
var propBindingRecords = bindingRecordsCreator.getPropertyBindingRecords(
pvWithIndex.renderProtoView.textBindings, elementBinders, allRenderDirectiveMetadata);
var eventBindingRecords =
bindingRecordsCreator.getEventBindingRecords(elementBinders, allRenderDirectiveMetadata);
var directiveRecords =
bindingRecordsCreator.getDirectiveRecords(elementBinders, allRenderDirectiveMetadata);
var strategyName = DEFAULT;
@@ -248,8 +288,8 @@ function _getChangeDetectorDefinitions(
}
var id = `${hostComponentMetadata.id}_${typeString}_${pvWithIndex.index}`;
var variableNames = nestedPvVariableNames[pvWithIndex.index];
return new ChangeDetectorDefinition(id, strategyName, variableNames, bindingRecords,
directiveRecords, assertionsEnabled());
return new ChangeDetectorDefinition(id, strategyName, variableNames, propBindingRecords,
eventBindingRecords, directiveRecords, assertionsEnabled());
});
}
@@ -266,8 +306,6 @@ function _createAppProtoView(
protoChangeDetector, variableBindings, createVariableLocations(elementBinders),
renderProtoView.textBindings.length, protoPipes);
_createElementBinders(protoView, elementBinders, allDirectives);
_bindDirectiveEvents(protoView, elementBinders);
return protoView;
}
@@ -393,8 +431,6 @@ function _createElementBinder(protoView: AppProtoView, boundElementIndex, render
}
var elBinder = protoView.bindElement(parent, renderElementBinder.distanceToParent,
protoElementInjector, componentDirectiveBinding);
protoView.bindEvent(renderElementBinder.eventBindings, boundElementIndex, -1);
// variables
// The view's locals needs to have a full set of variable names at construction time
// in order to prevent new variables from being set later in the lifecycle. Since we don't want
// to actually create variable bindings for the $implicit bindings, add to the
@@ -450,19 +486,6 @@ function _directiveExportAs(directive): string {
}
}
function _bindDirectiveEvents(protoView, elementBinders: List<renderApi.ElementBinder>) {
for (var boundElementIndex = 0; boundElementIndex < elementBinders.length; ++boundElementIndex) {
var dirs = elementBinders[boundElementIndex].directives;
for (var i = 0; i < dirs.length; i++) {
var directiveBinder = dirs[i];
// directive events
protoView.bindEvent(directiveBinder.eventBindings, boundElementIndex, i);
}
}
}
class RenderProtoViewWithIndex {
constructor(public renderProtoView: renderApi.ProtoViewDto, public index: number,
public parentIndex: number, public boundElementIndex: number) {}
+4 -54
View File
@@ -262,29 +262,12 @@ export class AppView implements ChangeDispatcher, RenderEventDispatcher {
// returns false if preventDefault must be applied to the DOM event
dispatchEvent(boundElementIndex: number, eventName: string, locals: Map<string, any>): boolean {
try {
// Most of the time the event will be fired only when the view is in the live document.
// However, in a rare circumstance the view might get dehydrated, in between the event
// queuing up and firing.
var allowDefaultBehavior = true;
if (this.hydrated()) {
var elBinder = this.proto.elementBinders[boundElementIndex - this.elementOffset];
if (isBlank(elBinder.hostListeners)) return allowDefaultBehavior;
var eventMap = elBinder.hostListeners[eventName];
if (isBlank(eventMap)) return allowDefaultBehavior;
MapWrapper.forEach(eventMap, (expr, directiveIndex) => {
var context;
if (directiveIndex === -1) {
context = this.context;
} else {
context = this.elementInjectors[boundElementIndex].getDirectiveAtIndex(directiveIndex);
}
var result = expr.eval(context, new Locals(this.locals, locals));
if (isPresent(result)) {
allowDefaultBehavior = allowDefaultBehavior && result == true;
}
});
return !this.changeDetector.handleEvent(eventName, boundElementIndex - this.elementOffset,
new Locals(this.locals, locals));
} else {
return true;
}
return allowDefaultBehavior;
} catch (e) {
var c = this.getDebugContext(boundElementIndex - this.elementOffset, null);
var context = isPresent(c) ? new _Context(c.element, c.componentElement, c.context, c.locals,
@@ -354,37 +337,4 @@ export class AppProtoView {
this.elementBinders.push(elBinder);
return elBinder;
}
/**
* Adds an event binding for the last created ElementBinder via bindElement.
*
* If the directive index is a positive integer, the event is evaluated in the context of
* the given directive.
*
* If the directive index is -1, the event is evaluated in the context of the enclosing view.
*
* @param {string} eventName
* @param {AST} expression
* @param {int} directiveIndex The directive index in the binder or -1 when the event is not bound
* to a directive
*/
bindEvent(eventBindings: List<renderApi.EventBinding>, boundElementIndex: number,
directiveIndex: int = -1): void {
var elBinder = this.elementBinders[boundElementIndex];
var events = elBinder.hostListeners;
if (isBlank(events)) {
events = StringMapWrapper.create();
elBinder.hostListeners = events;
}
for (var i = 0; i < eventBindings.length; i++) {
var eventBinding = eventBindings[i];
var eventName = eventBinding.fullName;
var event = StringMapWrapper.get(events, eventName);
if (isBlank(event)) {
event = new Map();
StringMapWrapper.set(events, eventName, event);
}
event.set(directiveIndex, eventBinding.source);
}
}
}
@@ -13,7 +13,7 @@ import {
ASTWithSource,
AST,
AstTransformer,
AccessMember,
PropertyRead,
LiteralArray,
ImplicitReceiver
} from 'angular2/src/change_detection/change_detection';
@@ -278,11 +278,11 @@ export class EventBuilder extends AstTransformer {
return result;
}
visitAccessMember(ast: AccessMember): AccessMember {
visitPropertyRead(ast: PropertyRead): PropertyRead {
var isEventAccess = false;
var current: AST = ast;
while (!isEventAccess && (current instanceof AccessMember)) {
var am = <AccessMember>current;
while (!isEventAccess && (current instanceof PropertyRead)) {
var am = <PropertyRead>current;
if (am.name == '$event') {
isEventAccess = true;
}
@@ -292,7 +292,7 @@ export class EventBuilder extends AstTransformer {
if (isEventAccess) {
this.locals.push(ast);
var index = this.locals.length - 1;
return new AccessMember(this._implicitReceiver, `${index}`, (arr) => arr[index], null);
return new PropertyRead(this._implicitReceiver, `${index}`, (arr) => arr[index]);
} else {
return ast;
}
@@ -1,7 +1,6 @@
library angular2.transform.template_compiler.change_detector_codegen;
import 'package:angular2/src/change_detection/change_detection_util.dart';
import 'package:angular2/src/change_detection/coalesce.dart';
import 'package:angular2/src/change_detection/codegen_facade.dart';
import 'package:angular2/src/change_detection/codegen_logic_util.dart';
import 'package:angular2/src/change_detection/codegen_name_util.dart';
@@ -9,6 +8,7 @@ import 'package:angular2/src/change_detection/directive_record.dart';
import 'package:angular2/src/change_detection/interfaces.dart';
import 'package:angular2/src/change_detection/proto_change_detector.dart';
import 'package:angular2/src/change_detection/proto_record.dart';
import 'package:angular2/src/change_detection/event_binding.dart';
import 'package:angular2/src/facade/lang.dart' show BaseException;
/// Responsible for generating change detector classes for Angular 2.
@@ -74,8 +74,9 @@ class _CodegenState {
/// detail and should not be visible to users.
final String _changeDetectorTypeName;
final String _changeDetectionMode;
final List<ProtoRecord> _records;
final List<DirectiveRecord> _directiveRecords;
final List<ProtoRecord> _records;
final List<EventBinding> _eventBindings;
final CodegenLogicUtil _logic;
final CodegenNameUtil _names;
final bool _generateCheckNoChanges;
@@ -86,6 +87,7 @@ class _CodegenState {
this._changeDetectorTypeName,
String changeDetectionStrategy,
this._records,
this._eventBindings,
this._directiveRecords,
this._logic,
this._names,
@@ -95,10 +97,9 @@ class _CodegenState {
factory _CodegenState(String typeName, String changeDetectorTypeName,
ChangeDetectorDefinition def) {
var recBuilder = new ProtoRecordBuilder();
def.bindingRecords.forEach((rec) => recBuilder.add(rec, def.variableNames));
var protoRecords = coalesce(recBuilder.records);
var names = new CodegenNameUtil(protoRecords, def.directiveRecords, _UTIL);
var protoRecords = createPropertyRecords(def);
var eventBindings = createEventRecords(def);
var names = new CodegenNameUtil(protoRecords, eventBindings, def.directiveRecords, _UTIL);
var logic = new CodegenLogicUtil(names, _UTIL);
return new _CodegenState._(
def.id,
@@ -106,6 +107,7 @@ class _CodegenState {
changeDetectorTypeName,
def.strategy,
protoRecords,
eventBindings,
def.directiveRecords,
logic,
names,
@@ -123,6 +125,13 @@ class _CodegenState {
dehydrateDirectives(false);
}
bool handleEvent(eventName, elIndex, locals) {
var ${_names.getPreventDefaultAccesor()} = false;
${_names.genInitEventLocals()}
${_genHandleEvent()}
return ${this._names.getPreventDefaultAccesor()};
}
void detectChangesInRecordsInternal(throwOnChange) {
${_names.genInitLocals()}
var $_IS_CHANGED_LOCAL = false;
@@ -152,6 +161,33 @@ class _CodegenState {
''');
}
String _genHandleEvent() {
return _eventBindings.map((eb) => _genEventBinding(eb)).join("\n");
}
String _genEventBinding(EventBinding eb) {
var recs = eb.records.map((r) => _genEventBindingEval(eb, r)).join("\n");
return '''
if (eventName == "${eb.eventName}" && elIndex == ${eb.elIndex}) {
${recs}
}''';
}
String _genEventBindingEval(EventBinding eb, ProtoRecord r){
if (r.lastInBinding) {
var evalRecord = _logic.genEventBindingEvalValue(eb, r);
var prevDefault = _genUpdatePreventDefault(eb, r);
return "${evalRecord}\n${prevDefault}";
} else {
return _logic.genEventBindingEvalValue(eb, r);
}
}
String _genUpdatePreventDefault(EventBinding eb, ProtoRecord r) {
var local = this._names.getEventLocalName(eb, r.selfIndex);
return """if (${local} == false) { ${_names.getPreventDefaultAccesor()} = true; }""";
}
void _writeInitToBuf(StringBuffer buf) {
buf.write('''
$_GEN_PREFIX.preGeneratedProtoDetectors['$_changeDetectorDefId'] =
@@ -295,7 +331,7 @@ class _CodegenState {
var oldValue = _names.getFieldName(r.selfIndex);
var newValue = _names.getLocalName(r.selfIndex);
var read = '''
${_logic.genUpdateCurrentValue(r)}
${_logic.genPropertyBindingEvalValue(r)}
''';
var check = '''