Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(696)

Side by Side Diff: third_party/pkg/angular/lib/core/scope.dart

Issue 180873006: Update the Angular/DI tests to latest from github. (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: Review feedback Created 6 years, 9 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
1 part of angular.core; 1 part of angular.core;
2 2
3 NOT_IMPLEMENTED() {
4 throw new StateError('Not Implemented');
5 }
6
7 typedef EvalFunction0();
8 typedef EvalFunction1(context);
3 9
4 /** 10 /**
5 * Injected into the listener function within [Scope.$on] to provide event-speci fic 11 * Injected into the listener function within [Scope.on] to provide
6 * details to the scope listener. 12 * event-specific details to the scope listener.
7 */ 13 */
8 class ScopeEvent { 14 class ScopeEvent {
15 static final String DESTROY = 'ng-destroy';
16
17 /**
18 * Data attached to the event. This would be the optional parameter
19 * from [Scope.emit] and [Scope.broadcast].
20 */
21 final data;
9 22
10 /** 23 /**
11 * The name of the intercepted scope event. 24 * The name of the intercepted scope event.
12 */ 25 */
13 String name; 26 final String name;
14 27
15 /** 28 /**
16 * The origin scope that triggered the event (via $broadcast or $emit). 29 * The origin scope that triggered the event (via broadcast or emit).
17 */ 30 */
18 Scope targetScope; 31 final Scope targetScope;
19 32
20 /** 33 /**
21 * The destination scope that intercepted the event. 34 * The destination scope that intercepted the event. As
22 */ 35 * the event traverses the scope hierarchy the the event instance
23 Scope currentScope; 36 * stays the same, but the [currentScope] reflects the scope
24 37 * of the current listener which is firing.
25 /** 38 */
26 * true or false depending on if stopPropagation() was executed. 39 Scope get currentScope => _currentScope;
27 */ 40 Scope _currentScope;
28 bool propagationStopped = false; 41
29 42 /**
30 /** 43 * true or false depending on if [stopPropagation] was executed.
31 * true or false depending on if preventDefault() was executed. 44 */
32 */ 45 bool get propagationStopped => _propagationStopped;
33 bool defaultPrevented = false; 46 bool _propagationStopped = false;
34 47
35 /** 48 /**
36 ** [name] - The name of the scope event. 49 * true or false depending on if [preventDefault] was executed.
37 ** [targetScope] - The destination scope that is listening on the event. 50 */
38 */ 51 bool get defaultPrevented => _defaultPrevented;
39 ScopeEvent(this.name, this.targetScope); 52 bool _defaultPrevented = false;
40 53
41 /** 54 /**
42 * Prevents the intercepted event from propagating further to successive scope s. 55 * [name] - The name of the scope event.
43 */ 56 * [targetScope] - The destination scope that is listening on the event.
44 stopPropagation () => propagationStopped = true; 57 */
58 ScopeEvent(this.name, this.targetScope, this.data);
59
60 /**
61 * Prevents the intercepted event from propagating further to successive
62 * scopes.
63 */
64 void stopPropagation () {
65 _propagationStopped = true;
66 }
45 67
46 /** 68 /**
47 * Sets the defaultPrevented flag to true. 69 * Sets the defaultPrevented flag to true.
48 */ 70 */
49 preventDefault() => defaultPrevented = true; 71 void preventDefault() {
72 _defaultPrevented = true;
73 }
50 } 74 }
51 75
52 /** 76 /**
53 * Allows the configuration of [Scope.$digest] iteration maximum time-to-live 77 * Allows the configuration of [Scope.digest] iteration maximum time-to-live
54 * value. Digest keeps checking the state of the watcher getters until it 78 * value. Digest keeps checking the state of the watcher getters until it
55 * can execute one full iteration with no watchers triggering. TTL is used 79 * can execute one full iteration with no watchers triggering. TTL is used
56 * to prevent an infinite loop where watch A triggers watch B which in turn 80 * to prevent an infinite loop where watch A triggers watch B which in turn
57 * triggers watch A. If the system does not stabilize in TTL iteration then 81 * triggers watch A. If the system does not stabilize in TTL iterations then
58 * an digest is stop an an exception is thrown. 82 * the digest is stopped and an exception is thrown.
59 */ 83 */
60 @NgInjectableService() 84 @NgInjectableService()
61 class ScopeDigestTTL { 85 class ScopeDigestTTL {
62 final num ttl; 86 final int ttl;
63 ScopeDigestTTL(): ttl = 5; 87 ScopeDigestTTL(): ttl = 5;
64 ScopeDigestTTL.value(num this.ttl); 88 ScopeDigestTTL.value(this.ttl);
89 }
90
91 //TODO(misko): I don't think this should be in scope.
92 class ScopeLocals implements Map {
93 static wrapper(scope, Map<String, Object> locals) =>
94 new ScopeLocals(scope, locals);
95
96 Map _scope;
97 Map<String, Object> _locals;
98
99 ScopeLocals(this._scope, this._locals);
100
101 void operator []=(String name, value) {
102 _scope[name] = value;
103 }
104 dynamic operator [](String name) =>
105 (_locals.containsKey(name) ? _locals : _scope)[name];
106
107 bool get isEmpty => _scope.isEmpty && _locals.isEmpty;
108 bool get isNotEmpty => _scope.isNotEmpty || _locals.isNotEmpty;
109 List<String> get keys => _scope.keys;
110 List get values => _scope.values;
111 int get length => _scope.length;
112
113 void forEach(fn) {
114 _scope.forEach(fn);
115 }
116 dynamic remove(key) => _scope.remove(key);
117 void clear() {
118 _scope.clear;
119 }
120 bool containsKey(key) => _scope.containsKey(key);
121 bool containsValue(key) => _scope.containsValue(key);
122 void addAll(map) {
123 _scope.addAll(map);
124 }
125 dynamic putIfAbsent(key, fn) => _scope.putIfAbsent(key, fn);
65 } 126 }
66 127
67 /** 128 /**
68 * Scope has two responsibilities. 1) to keep track af watches and 2) 129 * [Scope] is represents a collection of [watch]es [observe]ers, and [context]
69 * to keep references to the model so that they are available for 130 * for the watchers, observers and [eval]uations. Scopes structure loosely
70 * data-binding. 131 * mimics the DOM structure. Scopes and [Block]s are bound to each other.
132 * As scopes are created and destroyed by [BlockFactory] they are responsible
133 * for change detection, change processing and memory management.
71 */ 134 */
72 @proxy 135 class Scope {
73 @NgInjectableService() 136
74 class Scope implements Map { 137 /**
138 * The default execution context for [watch]es [observe]ers, and [eval]uation.
139 */
140 final context;
141
142 /**
143 * The [RootScope] of the application.
144 */
145 final RootScope rootScope;
146
147 Scope _parentScope;
148
149 /**
150 * The parent [Scope].
151 */
152 Scope get parentScope => _parentScope;
153
154 /**
155 * Return `true` if the scope has been destroyed. Once scope is destroyed
156 * No operations are allowed on it.
157 */
158 bool get isDestroyed {
159 var scope = this;
160 while(scope != null) {
161 if (scope == rootScope) return false;
162 scope = scope._parentScope;
163 }
164 return true;
165 }
166
167 /**
168 * Returns true if the scope is still attached to the [RootScope].
169 */
170 bool get isAttached => !isDestroyed;
171
172 // TODO(misko): WatchGroup should be private.
173 // Instead we should expose performance stats about the watches
174 // such as # of watches, checks/1ms, field checks, function checks, etc
175 final WatchGroup _readWriteGroup;
176 final WatchGroup _readOnlyGroup;
177
178 Scope _childHead, _childTail, _next, _prev;
179 _Streams _streams;
180
181 /// Do not use. Exposes internal state for testing.
182 bool get hasOwnStreams => _streams != null && _streams._scope == this;
183
184 Scope(Object this.context, this.rootScope, this._parentScope,
185 this._readWriteGroup, this._readOnlyGroup);
186
187 /**
188 * A [watch] sets up a watch in the [digest] phase of the [apply] cycle.
189 *
190 * Use [watch] if the reaction function can cause updates to model. In your
191 * controller code you will most likely use [watch].
192 */
193 Watch watch(expression, ReactionFn reactionFn,
194 {context, FilterMap filters, bool readOnly: false}) {
195 assert(isAttached);
196 assert(expression != null);
197 AST ast;
198 Watch watch;
199 ReactionFn fn = reactionFn;
200 if (expression is AST) {
201 ast = expression;
202 } else if (expression is String) {
203 if (expression.startsWith('::')) {
204 expression = expression.substring(2);
205 fn = (value, last) {
206 if (value != null) {
207 watch.remove();
208 return reactionFn(value, last);
209 }
210 };
211 } else if (expression.startsWith(':')) {
212 expression = expression.substring(1);
213 fn = (value, last) => value == null ? null : reactionFn(value, last);
214 }
215 ast = rootScope._astParser(expression, context: context, filters: filters) ;
216 } else {
217 throw 'expressions must be String or AST got $expression.';
218 }
219 return watch = (readOnly ? _readOnlyGroup : _readWriteGroup).watch(ast, fn);
220 }
221
222 dynamic eval(expression, [Map locals]) {
223 assert(isAttached);
224 assert(expression == null ||
225 expression is String ||
226 expression is Function);
227 if (expression is String && expression.isNotEmpty) {
228 var obj = locals == null ? context : new ScopeLocals(context, locals);
229 return rootScope._parser(expression).eval(obj);
230 }
231
232 assert(locals == null);
233 if (expression is EvalFunction1) return expression(context);
234 if (expression is EvalFunction0) return expression();
235 return null;
236 }
237
238 dynamic applyInZone([expression, Map locals]) =>
239 rootScope._zone.run(() => apply(expression, locals));
240
241 dynamic apply([expression, Map locals]) {
242 _assertInternalStateConsistency();
243 rootScope._transitionState(null, RootScope.STATE_APPLY);
244 try {
245 return eval(expression, locals);
246 } catch (e, s) {
247 rootScope._exceptionHandler(e, s);
248 } finally {
249 rootScope
250 .._transitionState(RootScope.STATE_APPLY, null)
251 ..digest()
252 ..flush();
253 }
254 }
255
256 ScopeEvent emit(String name, [data]) {
257 assert(isAttached);
258 return _Streams.emit(this, name, data);
259 }
260 ScopeEvent broadcast(String name, [data]) {
261 assert(isAttached);
262 return _Streams.broadcast(this, name, data);
263 }
264 ScopeStream on(String name) {
265 assert(isAttached);
266 return _Streams.on(this, rootScope._exceptionHandler, name);
267 }
268
269 Scope createChild(Object childContext) {
270 assert(isAttached);
271 var child = new Scope(childContext, rootScope, this,
272 _readWriteGroup.newGroup(childContext),
273 _readOnlyGroup.newGroup(childContext));
274 var next = null;
275 var prev = _childTail;
276 child._next = next;
277 child._prev = prev;
278 if (prev == null) _childHead = child; else prev._next = child;
279 if (next == null) _childTail = child; else next._prev = child;
280 return child;
281 }
282
283 void destroy() {
284 assert(isAttached);
285 broadcast(ScopeEvent.DESTROY);
286 _Streams.destroy(this);
287
288 if (_prev == null) {
289 _parentScope._childHead = _next;
290 } else {
291 _prev._next = _next;
292 }
293 if (_next == null) {
294 _parentScope._childTail = _prev;
295 } else {
296 _next._prev = _prev;
297 }
298
299 _next = _prev = null;
300
301 _readWriteGroup.remove();
302 _readOnlyGroup.remove();
303 _parentScope = null;
304 _assertInternalStateConsistency();
305 }
306
307 _assertInternalStateConsistency() {
308 assert((() {
309 rootScope._verifyStreams(null, '', []);
310 return true;
311 })());
312 }
313
314 Map<bool,int> _verifyStreams(parentScope, prefix, log) {
315 assert(_parentScope == parentScope);
316 var counts = {};
317 var typeCounts = _streams == null ? {} : _streams._typeCounts;
318 var connection = _streams != null && _streams._scope == this ? '=' : '-';
319 log..add(prefix)..add(hashCode)..add(connection)..add(typeCounts)..add('\n') ;
320 if (_streams == null) {
321 } else if (_streams._scope == this) {
322 _streams._streams.forEach((k, ScopeStream stream){
323 if (stream.subscriptions.isNotEmpty) {
324 counts[k] = 1 + (counts.containsKey(k) ? counts[k] : 0);
325 }
326 });
327 }
328 var childScope = _childHead;
329 while(childScope != null) {
330 childScope._verifyStreams(this, ' $prefix', log).forEach((k, v) {
331 counts[k] = v + (counts.containsKey(k) ? counts[k] : 0);
332 });
333 childScope = childScope._next;
334 }
335 if (!_mapEqual(counts, typeCounts)) {
336 throw 'Streams actual: $counts != bookkeeping: $typeCounts\n'
337 'Offending scope: [scope: ${this.hashCode}]\n'
338 '${log.join('')}';
339 }
340 return counts;
341 }
342 }
343
344 _mapEqual(Map a, Map b) => a.length == b.length &&
345 a.keys.every((k) => b.containsKey(k) && a[k] == b[k]);
346
347 class ScopeStats {
348 bool report = true;
349 final nf = new NumberFormat.decimalPattern();
350
351 final digestFieldStopwatch = new AvgStopwatch();
352 final digestEvalStopwatch = new AvgStopwatch();
353 final digestProcessStopwatch = new AvgStopwatch();
354 int _digestLoopNo = 0;
355
356 final flushFieldStopwatch = new AvgStopwatch();
357 final flushEvalStopwatch = new AvgStopwatch();
358 final flushProcessStopwatch = new AvgStopwatch();
359
360 ScopeStats({this.report: false}) {
361 nf.maximumFractionDigits = 0;
362 }
363
364 void digestStart() {
365 _digestStopwatchReset();
366 _digestLoopNo = 0;
367 }
368
369 _digestStopwatchReset() {
370 digestFieldStopwatch.reset();
371 digestEvalStopwatch.reset();
372 digestProcessStopwatch.reset();
373 }
374
375 void digestLoop(int changeCount) {
376 _digestLoopNo++;
377 if (report) {
378 print(this);
379 }
380 _digestStopwatchReset();
381 }
382
383 String _stat(AvgStopwatch s) {
384 return '${nf.format(s.count)}'
385 ' / ${nf.format(s.elapsedMicroseconds)} us'
386 ' = ${nf.format(s.ratePerMs)} #/ms';
387 }
388
389 void digestEnd() {
390 }
391
392 toString() =>
393 'digest #$_digestLoopNo:'
394 'Field: ${_stat(digestFieldStopwatch)} '
395 'Eval: ${_stat(digestEvalStopwatch)} '
396 'Process: ${_stat(digestProcessStopwatch)}';
397 }
398
399
400 class RootScope extends Scope {
401 static final STATE_APPLY = 'apply';
402 static final STATE_DIGEST = 'digest';
403 static final STATE_FLUSH = 'digest';
404
75 final ExceptionHandler _exceptionHandler; 405 final ExceptionHandler _exceptionHandler;
406 final AstParser _astParser;
76 final Parser _parser; 407 final Parser _parser;
408 final ScopeDigestTTL _ttl;
409 final ExpressionVisitor visitor = new ExpressionVisitor(); // TODO(misko): del ete me
77 final NgZone _zone; 410 final NgZone _zone;
78 final num _ttl; 411
79 final Map<String, Object> _properties = {}; 412 _FunctionChain _runAsyncHead, _runAsyncTail;
80 final _WatchList _watchers = new _WatchList(); 413 _FunctionChain _domWriteHead, _domWriteTail;
81 final Map<String, List<Function>> _listeners = {}; 414 _FunctionChain _domReadHead, _domReadTail;
82 final bool _isolate; 415
83 final bool _lazy; 416 final ScopeStats _scopeStats;
84 final Profiler _perf; 417
85 418 String _state;
86 /** 419
87 * The direct parent scope that created this scope (this can also be the $root Scope) 420 RootScope(Object context, this._astParser, this._parser,
88 */ 421 GetterCache cacheGetter, FilterMap filterMap,
89 final Scope $parent; 422 this._exceptionHandler, this._ttl, this._zone,
90 423 this._scopeStats)
91 /** 424 : super(context, null, null,
92 * The auto-incremented ID of the scope 425 new RootWatchGroup(new DirtyCheckingChangeDetector(cacheGetter), con text),
93 */ 426 new RootWatchGroup(new DirtyCheckingChangeDetector(cacheGetter), con text))
94 String $id; 427 {
95 428 _zone.onTurnDone = apply;
96 /**
97 * The topmost scope of the application (same as $rootScope).
98 */
99 Scope $root;
100 num _nextId = 0;
101 String _phase;
102 List _innerAsyncQueue;
103 List _outerAsyncQueue;
104 Scope _nextSibling, _prevSibling, _childHead, _childTail;
105 bool _skipAutoDigest = false;
106 bool _disabled = false;
107
108 _set$Properties() {
109 _properties[r'this'] = this;
110 _properties[r'$id'] = this.$id;
111 _properties[r'$parent'] = this.$parent;
112 _properties[r'$root'] = this.$root;
113 }
114
115 Scope(this._exceptionHandler, this._parser, ScopeDigestTTL ttl,
116 this._zone, this._perf):
117 $parent = null, _isolate = false, _lazy = false, _ttl = ttl.ttl {
118 $root = this;
119 $id = '_${$root._nextId++}';
120 _innerAsyncQueue = [];
121 _outerAsyncQueue = [];
122
123 // Set up the zone to auto digest this scope.
124 _zone.onTurnDone = _autoDigestOnTurnDone;
125 _zone.onError = (e, s, ls) => _exceptionHandler(e, s); 429 _zone.onError = (e, s, ls) => _exceptionHandler(e, s);
126 _set$Properties(); 430 }
127 } 431
128 432 RootScope get rootScope => this;
129 Scope._child(Scope parent, bool this._isolate, bool this._lazy, Profiler this. _perf): 433 bool get isAttached => true;
130 $parent = parent, _ttl = parent._ttl, _parser = parent._parser, 434
131 _exceptionHandler = parent._exceptionHandler, _zone = parent._zone { 435 void digest() {
132 $root = $parent.$root; 436 _transitionState(null, STATE_DIGEST);
133 $id = '_${$root._nextId++}';
134 _innerAsyncQueue = $parent._innerAsyncQueue;
135 _outerAsyncQueue = $parent._outerAsyncQueue;
136
137 _prevSibling = $parent._childTail;
138 if ($parent._childHead != null) {
139 $parent._childTail._nextSibling = this;
140 $parent._childTail = this;
141 } else {
142 $parent._childHead = $parent._childTail = this;
143 }
144 _set$Properties();
145 }
146
147 _autoDigestOnTurnDone() {
148 if ($root._skipAutoDigest) {
149 $root._skipAutoDigest = false;
150 } else {
151 $digest();
152 }
153 }
154
155 _identical(a, b) =>
156 identical(a, b) ||
157 (a is String && b is String && a == b) ||
158 (a is num && b is num && a.isNaN && b.isNaN);
159
160 containsKey(String name) {
161 for (var scope = this; scope != null; scope = scope.$parent) {
162 if (scope._properties.containsKey(name)) {
163 return true;
164 } else if(scope._isolate) {
165 break;
166 }
167 }
168 return false;
169 }
170
171 remove(String name) => this._properties.remove(name);
172 operator []=(String name, value) => _properties[name] = value;
173 operator [](String name) {
174 for (var scope = this; scope != null; scope = scope.$parent) {
175 if (scope._properties.containsKey(name)) {
176 return scope._properties[name];
177 } else if(scope._isolate) {
178 break;
179 }
180 }
181 return null;
182 }
183
184 noSuchMethod(Invocation invocation) {
185 var name = MirrorSystem.getName(invocation.memberName);
186 if (invocation.isGetter) {
187 return this[name];
188 } else if (invocation.isSetter) {
189 var value = invocation.positionalArguments[0];
190 name = name.substring(0, name.length - 1);
191 this[name] = value;
192 return value;
193 } else {
194 if (this[name] is Function) {
195 return this[name]();
196 } else {
197 super.noSuchMethod(invocation);
198 }
199 }
200 }
201
202
203 /**
204 * Create a new child [Scope].
205 *
206 * * [isolate] - If set to true the child scope does not inherit properties fr om the parent scope.
207 * This in essence creates an independent (isolated) view for the users of t he scope.
208 * * [lazy] - If set to true the scope digest will only run if the scope is ma rked as [$dirty].
209 * This is usefull if we expect that the bindings in the scope are constant and there is no need
210 * to check them on each digest. The digest can be forced by marking it [$di rty].
211 */
212 $new({bool isolate: false, bool lazy: false}) =>
213 new Scope._child(this, isolate, lazy, _perf);
214
215 /**
216 * *EXPERIMENTAL:* This feature is experimental. We reserve the right to chang e or delete it.
217 *
218 * A dissabled scope will not be part of the [$digest] cycle until it is re-en abled.
219 */
220 set $disabled(value) => this._disabled = value;
221 get $disabled => this._disabled;
222
223 /**
224 * Registers a listener callback to be executed whenever the [watchExpression] changes.
225 *
226 * The watchExpression is called on every call to [$digest] and should return the value that
227 * will be watched. (Since [$digest] reruns when it detects changes the watchE xpression can
228 * execute multiple times per [$digest] and should be idempotent.)
229 *
230 * The listener is called only when the value from the current [watchExpressio n] and the
231 * previous call to [watchExpression] are not identical (with the exception of the initial run,
232 * see below).
233 *
234 * The watch listener may change the model, which may trigger other listeners to fire. This is
235 * achieved by rerunning the watchers until no changes are detected. The rerun iteration limit
236 * is 10 to prevent an infinite loop deadlock.
237 * If you want to be notified whenever [$digest] is called, you can register a [watchExpression]
238 * function with no listener. (Since [watchExpression] can execute multiple ti mes per [$digest]
239 * cycle when a change is detected, be prepared for multiple calls to your lis tener.)
240 *
241 * After a watcher is registered with the scope, the listener fn is called asy nchronously
242 * (via [$evalAsync]) to initialize the watcher. In rare cases, this is undesi rable because the
243 * listener is called when the result of [watchExpression] didn't change. To d etect this
244 * scenario within the listener fn, you can compare the newVal and oldVal. If these two values
245 * are identical then the listener was called due to initialization.
246 *
247 * * [watchExpression] - can be any one of these: a [Function] - `(Scope scope ) => ...;` or a
248 * [String] - `expression` which is compiled with [Parser] service into a f unction
249 * * [listener] - A [Function] `(currentValue, previousValue, Scope scope) => ...;`
250 * * [watchStr] - Used as a debbuging hint to easier identify which expression is associated with
251 * this watcher.
252 */
253 $watch(watchExpression, [Function listener, String watchStr]) {
254 if (watchStr == null) {
255 watchStr = watchExpression.toString();
256
257 // Keep prod fast
258 assert((() {
259 watchStr = _source(watchExpression);
260 return true;
261 })());
262 }
263 var watcher = new _Watch(_compileToFn(listener), _initWatchVal,
264 _compileToFn(watchExpression), watchStr);
265 _watchers.addLast(watcher);
266 return () => _watchers.remove(watcher);
267 }
268
269 /**
270 * A variant of [$watch] where it watches a collection of [watchExpressios]. I f any
271 * one expression in the collection changes the [listener] is executed.
272 *
273 * * [watcherExpressions] - `List<String|(Scope scope){}>`
274 * * [Listener] - `(List newValues, List previousValues, Scope scope)`
275 */
276 $watchSet(List watchExpressions, [Function listener, String watchStr]) {
277 if (watchExpressions.length == 0) return () => null;
278
279 var lastValues = new List(watchExpressions.length);
280 var currentValues = new List(watchExpressions.length);
281
282 if (watchExpressions.length == 1) {
283 // Special case size of one.
284 return $watch(watchExpressions[0], (value, oldValue, scope) {
285 currentValues[0] = value;
286 lastValues[0] = oldValue;
287 listener(currentValues, lastValues, scope);
288 });
289 }
290 var deregesterFns = [];
291 var changeCount = 0;
292 for(var i = 0, ii = watchExpressions.length; i < ii; i++) {
293 deregesterFns.add($watch(watchExpressions[i], (value, oldValue, __) {
294 currentValues[i] = value;
295 lastValues[i] = oldValue;
296 changeCount++;
297 }));
298 }
299 deregesterFns.add($watch((s) => changeCount, (c, o, scope) {
300 listener(currentValues, lastValues, scope);
301 }));
302 return () {
303 for(var i = 0, ii = deregesterFns.length; i < ii; i++) {
304 deregesterFns[i]();
305 }
306 };
307 }
308
309 /**
310 * Shallow watches the properties of an object and fires whenever any of the p roperties change
311 * (for arrays, this implies watching the array items; for object maps, this i mplies watching
312 * the properties). If a change is detected, the listener callback is fired.
313 *
314 * The obj collection is observed via standard [$watch] operation and is exam ined on every call
315 * to [$digest] to see if any items have been added, removed, or moved.
316 *
317 * The listener is called whenever anything within the obj has changed. Examp les include
318 * adding, removing, and moving items belonging to an object or array.
319 */
320 $watchCollection(obj, listener, [String expression, bool shallow=false]) {
321 var oldValue;
322 var newValue;
323 int changeDetected = 0;
324 Function objGetter = _compileToFn(obj);
325 List internalArray = [];
326 Map internalMap = {};
327 int oldLength = 0;
328 int newLength;
329 var key;
330 List keysToRemove = [];
331 Function detectNewKeys = (key, value) {
332 newLength++;
333 if (oldValue.containsKey(key)) {
334 if (!_identical(oldValue[key], value)) {
335 changeDetected++;
336 oldValue[key] = value;
337 }
338 } else {
339 oldLength++;
340 oldValue[key] = value;
341 changeDetected++;
342 }
343 };
344 Function findMissingKeys = (key, _) {
345 if (!newValue.containsKey(key)) {
346 oldLength--;
347 keysToRemove.add(key);
348 }
349 };
350
351 Function removeMissingKeys = (k) => oldValue.remove(k);
352
353 var $watchCollectionWatch;
354
355 if (shallow) {
356 $watchCollectionWatch = (_) {
357 newValue = objGetter(this);
358 newLength = newValue == null ? 0 : newValue.length;
359 if (newLength != oldLength) {
360 oldLength = newLength;
361 changeDetected++;
362 }
363 if (!identical(oldValue, newValue)) {
364 oldValue = newValue;
365 changeDetected++;
366 }
367 return changeDetected;
368 };
369 } else {
370 $watchCollectionWatch = (_) {
371 newValue = objGetter(this);
372
373 if (newValue is! Map && newValue is! List) {
374 if (!_identical(oldValue, newValue)) {
375 oldValue = newValue;
376 changeDetected++;
377 }
378 } else if (newValue is Iterable) {
379 if (!_identical(oldValue, internalArray)) {
380 // we are transitioning from something which was not an array into a rray.
381 oldValue = internalArray;
382 oldLength = oldValue.length = 0;
383 changeDetected++;
384 }
385
386 newLength = newValue.length;
387
388 if (oldLength != newLength) {
389 // if lengths do not match we need to trigger change notification
390 changeDetected++;
391 oldValue.length = oldLength = newLength;
392 }
393 // copy the items to oldValue and look for changes.
394 for (var i = 0; i < newLength; i++) {
395 if (!_identical(oldValue[i], newValue.elementAt(i))) {
396 changeDetected++;
397 oldValue[i] = newValue.elementAt(i);
398 }
399 }
400 } else { // Map
401 if (!_identical(oldValue, internalMap)) {
402 // we are transitioning from something which was not an object into object.
403 oldValue = internalMap = {};
404 oldLength = 0;
405 changeDetected++;
406 }
407 // copy the items to oldValue and look for changes.
408 newLength = 0;
409 newValue.forEach(detectNewKeys);
410 if (oldLength > newLength) {
411 // we used to have more keys, need to find them and destroy them.
412 changeDetected++;
413 oldValue.forEach(findMissingKeys);
414 keysToRemove.forEach(removeMissingKeys);
415 keysToRemove.clear();
416 }
417 }
418 return changeDetected;
419 };
420 }
421
422 var $watchCollectionAction = (_, __, ___) {
423 relaxFnApply(listener, [newValue, oldValue, this]);
424 };
425
426 return this.$watch($watchCollectionWatch,
427 $watchCollectionAction,
428 expression == null ? obj : expression);
429 }
430
431
432 /**
433 * Add this function to your code if you want to add a $digest
434 * and want to assert that the digest will be called on this turn.
435 * This method will be deleted when we are comfortable with
436 * auto-digesting scope.
437 */
438 $$verifyDigestWillRun() {
439 assert(!$root._skipAutoDigest);
440 _zone.assertInTurn();
441 }
442
443 /**
444 * *EXPERIMENTAL:* This feature is experimental. We reserve the right to chang e or delete it.
445 *
446 * Marks a scope as dirty. If the scope is lazy (see [$new]) then the scope wi ll be included
447 * in the next [$digest].
448 *
449 * NOTE: This has no effect for non-lazy scopes.
450 */
451 $dirty() {
452 this._disabled = false;
453 }
454
455 /**
456 * Processes all of the watchers of the current scope and its children.
457 * Because a watcher's listener can change the model, the `$digest()` operatio n keeps calling
458 * the watchers no further response data has changed. This means that it is po ssible to get
459 * into an infinite loop. This function will throw `'Maximum iteration limit e xceeded.'`
460 * if the number of iterations exceeds 10.
461 *
462 * There should really be no need to call $digest() in production code since e verything is
463 * handled behind the scenes with zones and object mutation events. However, i n testing
464 * both $digest and [$apply] are useful to control state and simulate the scop e life cycle in
465 * a step-by-step manner.
466 *
467 * Refer to [$watch], [$watchSet] or [$watchCollection] to see how to register watchers that
468 * are executed during the digest cycle.
469 */
470 $digest() {
471 try { 437 try {
472 _beginPhase('\$digest'); 438 var rootWatchGroup = (_readWriteGroup as RootWatchGroup);
473 _digestWhileDirtyLoop(); 439
474 } catch (e, s) { 440 int digestTTL = _ttl.ttl;
475 _exceptionHandler(e, s); 441 const int LOG_COUNT = 3;
476 } finally { 442 List log;
477 _clearPhase(); 443 List digestLog;
478 } 444 var count;
479 } 445 ChangeLog changeLog;
480 446 _scopeStats.digestStart();
481 447 do {
482 _digestWhileDirtyLoop() { 448 while(_runAsyncHead != null) {
483 _digestHandleQueue('ng.innerAsync', _innerAsyncQueue);
484
485 int timerId;
486 assert((timerId = _perf.startTimer('ng.dirty_check', 0)) != false);
487 _Watch lastDirtyWatch = _digestComputeLastDirty();
488 assert(_perf.stopTimer(timerId) != false);
489
490 if (lastDirtyWatch == null) {
491 _digestHandleQueue('ng.outerAsync', _outerAsyncQueue);
492 return;
493 }
494
495 List<List<String>> watchLog = [];
496 for (int iteration = 1, ttl = _ttl; iteration < ttl; iteration++) {
497 _Watch stopWatch = _digestHandleQueue('ng.innerAsync', _innerAsyncQueue)
498 ? null // Evaluating async work requires re-evaluating all watchers.
499 : lastDirtyWatch;
500 lastDirtyWatch = null;
501
502 List<String> expressionLog;
503 if (ttl - iteration <= 3) {
504 expressionLog = <String>[];
505 watchLog.add(expressionLog);
506 }
507
508 int timerId;
509 assert((timerId = _perf.startTimer('ng.dirty_check', iteration)) != false) ;
510 lastDirtyWatch = _digestComputeLastDirtyUntil(stopWatch, expressionLog);
511 assert(_perf.stopTimer(timerId) != false);
512
513 if (lastDirtyWatch == null) {
514 _digestComputePerfCounters();
515 _digestHandleQueue('ng.outerAsync', _outerAsyncQueue);
516 return;
517 }
518 }
519
520 // I've seen things you people wouldn't believe. Attack ships on fire
521 // off the shoulder of Orion. I've watched C-beams glitter in the dark
522 // near the Tannhauser Gate. All those moments will be lost in time,
523 // like tears in rain. Time to die.
524 throw '$_ttl \$digest() iterations reached. Aborting!\n'
525 'Watchers fired in the last ${watchLog.length} iterations: '
526 '${_toJson(watchLog)}';
527 }
528
529
530 bool _digestHandleQueue(String timerName, List queue) {
531 if (queue.isEmpty) {
532 return false;
533 }
534 do {
535 var timerId;
536 try {
537 var workFn = queue.removeAt(0);
538 assert((timerId = _perf.startTimer(timerName, _source(workFn))) != false );
539 $root.$eval(workFn);
540 } catch (e, s) {
541 _exceptionHandler(e, s);
542 } finally {
543 assert(_perf.stopTimer(timerId) != false);
544 }
545 } while (queue.isNotEmpty);
546 return true;
547 }
548
549
550 _Watch _digestComputeLastDirty() {
551 int watcherCount = 0;
552 int scopeCount = 0;
553 Scope scope = this;
554 do {
555 _WatchList watchers = scope._watchers;
556 watcherCount += watchers.length;
557 scopeCount++;
558 for (_Watch watch = watchers.head; watch != null; watch = watch.next) {
559 var last = watch.last;
560 var value = watch.get(scope);
561 if (!_identical(value, last)) {
562 return _digestHandleDirty(scope, watch, last, value, null);
563 }
564 }
565 } while ((scope = _digestComputeNextScope(scope)) != null);
566 _digestUpdatePerfCounters(watcherCount, scopeCount);
567 return null;
568 }
569
570
571 _Watch _digestComputeLastDirtyUntil(_Watch stopWatch, List<String> log) {
572 int watcherCount = 0;
573 int scopeCount = 0;
574 Scope scope = this;
575 do {
576 _WatchList watchers = scope._watchers;
577 watcherCount += watchers.length;
578 scopeCount++;
579 for (_Watch watch = watchers.head; watch != null; watch = watch.next) {
580 if (identical(stopWatch, watch)) return null;
581 var last = watch.last;
582 var value = watch.get(scope);
583 if (!_identical(value, last)) {
584 return _digestHandleDirty(scope, watch, last, value, log);
585 }
586 }
587 } while ((scope = _digestComputeNextScope(scope)) != null);
588 return null;
589 }
590
591
592 _Watch _digestHandleDirty(Scope scope, _Watch watch, last, value, List<String> log) {
593 _Watch lastDirtyWatch;
594 while (true) {
595 if (!_identical(value, last)) {
596 lastDirtyWatch = watch;
597 if (log != null) log.add(watch.exp == null ? '[unknown]' : watch.exp);
598 watch.last = value;
599 var fireTimer;
600 assert((fireTimer = _perf.startTimer('ng.fire', watch.exp)) != false);
601 watch.fn(value, identical(_initWatchVal, last) ? value : last, scope);
602 assert(_perf.stopTimer(fireTimer) != false);
603 }
604 watch = watch.next;
605 while (watch == null) {
606 scope = _digestComputeNextScope(scope);
607 if (scope == null) return lastDirtyWatch;
608 watch = scope._watchers.head;
609 }
610 last = watch.last;
611 value = watch.get(scope);
612 }
613 }
614
615
616 Scope _digestComputeNextScope(Scope scope) {
617 // Insanity Warning: scope depth-first traversal
618 // yes, this code is a bit crazy, but it works and we have tests to prove it !
619 // this piece should be kept in sync with the traversal in $broadcast
620 Scope target = this;
621 Scope childHead = scope._childHead;
622 while (childHead != null && childHead._disabled) {
623 childHead = childHead._nextSibling;
624 }
625 if (childHead == null) {
626 if (scope == target) {
627 return null;
628 } else {
629 Scope next = scope._nextSibling;
630 if (next == null) {
631 while (scope != target && (next = scope._nextSibling) == null) {
632 scope = scope.$parent;
633 }
634 }
635 return next;
636 }
637 } else {
638 if (childHead._lazy) childHead._disabled = true;
639 return childHead;
640 }
641 }
642
643
644 void _digestComputePerfCounters() {
645 int watcherCount = 0, scopeCount = 0;
646 Scope scope = this;
647 do {
648 scopeCount++;
649 watcherCount += scope._watchers.length;
650 } while ((scope = _digestComputeNextScope(scope)) != null);
651 _digestUpdatePerfCounters(watcherCount, scopeCount);
652 }
653
654
655 void _digestUpdatePerfCounters(int watcherCount, int scopeCount) {
656 _perf.counters['ng.scope.watchers'] = watcherCount;
657 _perf.counters['ng.scopes'] = scopeCount;
658 }
659
660
661 /**
662 * Removes the current scope (and all of its children) from the parent scope. Removal implies
663 * that calls to $digest() will no longer propagate to the current scope and i ts children.
664 * Removal also implies that the current scope is eligible for garbage collect ion.
665 *
666 * The `$destroy()` operation is usually used within directives that perform t ransclusion on
667 * multiple child elements (like ngRepeat) which create multiple child scopes.
668 *
669 * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope. This is
670 * a great way for child scopes (such as shared directives or controllers) to detect to and
671 * perform any necessary cleanup before the scope is removed from the applicat ion.
672 *
673 * Note that, in AngularDart, there is also a `$destroy` jQuery DOM event, whi ch can be used to
674 * clean up DOM bindings before an element is removed from the DOM.
675 */
676 $destroy() {
677 if ($root == this) return; // we can't remove the root node;
678
679 $broadcast(r'$destroy');
680
681 if ($parent._childHead == this) $parent._childHead = _nextSibling;
682 if ($parent._childTail == this) $parent._childTail = _prevSibling;
683 if (_prevSibling != null) _prevSibling._nextSibling = _nextSibling;
684 if (_nextSibling != null) _nextSibling._prevSibling = _prevSibling;
685 }
686
687
688 /**
689 * Evaluates the expression against the current scope and returns the result. Note that, the
690 * expression data is relative to the data within the scope. Therefore an expr ession such as
691 * `a + b` will deference variables `a` and `b` and return a result so long as `a` and `b`
692 * exist on the scope.
693 *
694 * * [expr] - The expression that will be evaluated. This can be both a Functi on or a String.
695 * * [locals] - An optional Map of key/value data that will override any match ing scope members
696 * for the purposes of the evaluation.
697 */
698 $eval(expr, [locals]) {
699 return relaxFnArgs(_compileToFn(expr))(locals == null ? this : new ScopeLoca ls(this, locals));
700 }
701
702
703 /**
704 * Evaluates the expression against the current scope at a later point in time . The $evalAsync
705 * operation may not get run right away (depending if an existing digest cycle is going on) and
706 * may therefore be issued later on (by a follow-up digest cycle). Note that a t least one digest
707 * cycle will be performed after the expression is evaluated. However, If trig gering an additional
708 * digest cycle is not desired then this can be avoided by placing `{outsideDi gest: true}` as
709 * the 2nd parameter to the function.
710 *
711 * * [expr] - The expression that will be evaluated. This can be both a Functi on or a String.
712 * * [outsideDigest] - Whether or not to trigger a follow-up digest after eval uation.
713 */
714 $evalAsync(expr, {outsideDigest: false}) {
715 if (outsideDigest) {
716 _outerAsyncQueue.add(expr);
717 } else {
718 _innerAsyncQueue.add(expr);
719 }
720 }
721
722
723 /**
724 * Skip running a $digest at the end of this turn.
725 * The primary use case is to skip the digest in the current VM turn because
726 * you just scheduled or are otherwise certain of an impending VM turn and the
727 * digest at the end of that turn is sufficient. You should be able to answer
728 * "No" to the question "Is there any other code that is aware that this VM
729 * turn occurred and therefore expected a digest?". If your answer is "Yes",
730 * then you run the risk that the very next VM turn is not for your event and
731 * now that other code runs in that turn and sees stale values.
732 *
733 * You might call this function, for instance, from an event listener where,
734 * though the event occurred, you need to wait for another event before you ca n
735 * perform something meaningful. You might schedule that other event,
736 * set a flag for the handler of the other event to recognize, etc. and then
737 * call this method to skip the digest this cycle. Note that you should call
738 * this function *after* you have successfully confirmed that the expected VM
739 * turn will occur (perhaps by scheduling it) to ensure that the digest
740 * actually does take place on that turn.
741 */
742 $skipAutoDigest() {
743 _zone.assertInTurn();
744 $root._skipAutoDigest = true;
745 }
746
747
748 /**
749 * Triggers a digest operation much like [$digest] does, however, also accepts an
750 * optional expression to evaluate alongside the digest operation. The result of that
751 * expression will be returned afterwards. Much like with $digest, $apply shou ld only be
752 * used within unit tests to simulate the life cycle of a scope. See [$digest] to learn
753 * more.
754 *
755 * * [expr] - optional expression which will be evaluated after the digest is performed. See [$eval]
756 * to learn more about expressions.
757 */
758 $apply([expr]) {
759 return _zone.run(() {
760 var timerId;
761 try {
762 assert((timerId = _perf.startTimer('ng.\$apply', _source(expr))) != fals e);
763 return $eval(expr);
764 } catch (e, s) {
765 _exceptionHandler(e, s);
766 } finally {
767 assert(_perf.stopTimer(timerId) != false);
768 }
769 });
770 }
771
772
773 /**
774 * Registers a scope-based event listener to intercept events triggered by
775 * [$broadcast] (from any parent scopes) or [$emit] (from child scopes) that
776 * match the given event name. $on accepts two arguments:
777 *
778 * * [name] - Refers to the event name that the scope will listen on.
779 * * [listener] - Refers to the callback function which is executed when the e vent
780 * is intercepted.
781 *
782 *
783 * When the listener function is executed, an instance of [ScopeEvent] will be passed
784 * as the first parameter to the function.
785 *
786 * Any additional parameters available within the listener callback function a re those that
787 * are set by the $broadcast or $emit scope methods (which are set by the orig in scope which
788 * is the scope that first triggered the scope event).
789 */
790 $on(name, listener) {
791 var namedListeners = _listeners[name];
792 if (!_listeners.containsKey(name)) {
793 _listeners[name] = namedListeners = [];
794 }
795 namedListeners.add(listener);
796
797 return () {
798 namedListeners.remove(listener);
799 };
800 }
801
802
803 /**
804 * Triggers a scope event referenced by the [name] parameters upwards towards the root of the
805 * scope tree. If intercepted, by a parent scope containing a matching scope e vent listener
806 * (which is registered via the [$on] scope method), then the event listener c allback function
807 * will be executed.
808 *
809 * * [name] - The scope event name that will be triggered.
810 * * [args] - An optional list of arguments that will be fed into the listener callback function
811 * for any event listeners that are registered via [$on].
812 */
813 $emit(name, [List args]) {
814 var empty = [],
815 namedListeners,
816 scope = this,
817 event = new ScopeEvent(name, this),
818 listenerArgs = [event],
819 i;
820
821 if (args != null) {
822 listenerArgs.addAll(args);
823 }
824
825 do {
826 namedListeners = scope._listeners[name];
827 if (namedListeners != null) {
828 event.currentScope = scope;
829 i = 0;
830 for (var length = namedListeners.length; i<length; i++) {
831 try { 449 try {
832 relaxFnApply(namedListeners[i], listenerArgs); 450 _runAsyncHead.fn();
833 if (event.propagationStopped) return event;
834 } catch (e, s) { 451 } catch (e, s) {
835 _exceptionHandler(e, s); 452 _exceptionHandler(e, s);
836 } 453 }
837 } 454 _runAsyncHead = _runAsyncHead._next;
838 } 455 }
839 //traverse upwards 456
840 scope = scope.$parent; 457 digestTTL--;
841 } while (scope != null); 458 count = rootWatchGroup.detectChanges(
842 459 exceptionHandler: _exceptionHandler,
843 return event; 460 changeLog: changeLog,
844 } 461 fieldStopwatch: _scopeStats.digestFieldStopwatch,
845 462 evalStopwatch: _scopeStats.digestEvalStopwatch,
846 463 processStopwatch: _scopeStats.digestProcessStopwatch);
847 /** 464
848 * Triggers a scope event referenced by the [name] parameters dowards towards the leaf nodes of the 465 if (digestTTL <= LOG_COUNT) {
849 * scope tree. If intercepted, by a child scope containing a matching scope ev ent listener 466 if (changeLog == null) {
850 * (which is registered via the [$on] scope method), then the event listener c allback function 467 log = [];
851 * will be executed. 468 digestLog = [];
852 * 469 changeLog = (e, c, p) => digestLog.add('$e: $c <= $p');
853 * * [name] - The scope event name that will be triggered. 470 } else {
854 * * [listenerArgs] - An optional list of arguments that will be fed into the listener callback function 471 log.add(digestLog.join(', '));
855 * for any event listeners that are registered via [$on]. 472 digestLog.clear();
856 */ 473 }
857 $broadcast(String name, [List listenerArgs]) { 474 }
858 var target = this, 475 if (digestTTL == 0) {
859 current = target, 476 throw 'Model did not stabilize in ${_ttl.ttl} digests. '
860 next = target, 477 'Last $LOG_COUNT iterations:\n${log.join('\n')}';
861 event = new ScopeEvent(name, this); 478 }
862 479 _scopeStats.digestLoop(count);
863 //down while you can, then up and next sibling or up and next sibling until back at root 480 } while (count > 0);
864 if (listenerArgs == null) { 481 } finally {
865 listenerArgs = []; 482 _scopeStats.digestEnd();
866 } 483 _transitionState(STATE_DIGEST, null);
867 listenerArgs.insert(0, event); 484 }
868 do { 485 }
869 current = next; 486
870 event.currentScope = current; 487 void flush() {
871 if (current._listeners.containsKey(name)) { 488 _transitionState(null, STATE_FLUSH);
872 current._listeners[name].forEach((listener) { 489 var observeGroup = this._readOnlyGroup as RootWatchGroup;
490 bool runObservers = true;
491 try {
492 do {
493 while(_domWriteHead != null) {
873 try { 494 try {
874 relaxFnApply(listener, listenerArgs); 495 _domWriteHead.fn();
875 } catch(e, s) { 496 } catch (e, s) {
876 _exceptionHandler(e, s); 497 _exceptionHandler(e, s);
877 } 498 }
878 }); 499 _domWriteHead = _domWriteHead._next;
500 }
501 if (runObservers) {
502 runObservers = false;
503 observeGroup.detectChanges(exceptionHandler:_exceptionHandler);
504 }
505 while(_domReadHead != null) {
506 try {
507 _domReadHead.fn();
508 } catch (e, s) {
509 _exceptionHandler(e, s);
510 }
511 _domReadHead = _domReadHead._next;
512 }
513 } while (_domWriteHead != null || _domReadHead != null);
514 assert((() {
515 var watchLog = [];
516 var observeLog = [];
517 (_readWriteGroup as RootWatchGroup).detectChanges(
518 changeLog: (s, c, p) => watchLog.add('$s: $c <= $p'));
519 (observeGroup as RootWatchGroup).detectChanges(
520 changeLog: (s, c, p) => watchLog.add('$s: $c <= $p'));
521 if (watchLog.isNotEmpty || observeLog.isNotEmpty) {
522 throw 'Observer reaction functions should not change model. \n'
523 'These watch changes were detected: ${watchLog.join('; ')}\n'
524 'These observe changes were detected: ${observeLog.join('; ')}';
525 }
526 return true;
527 })());
528 } finally {
529 _transitionState(STATE_FLUSH, null);
530 }
531
532 }
533
534 // QUEUES
535 void runAsync(fn()) {
536 var chain = new _FunctionChain(fn);
537 if (_runAsyncHead == null) {
538 _runAsyncHead = _runAsyncTail = chain;
539 } else {
540 _runAsyncTail = _runAsyncTail._next = chain;
541 }
542 }
543
544 void domWrite(fn()) {
545 var chain = new _FunctionChain(fn);
546 if (_domWriteHead == null) {
547 _domWriteHead = _domWriteTail = chain;
548 } else {
549 _domWriteTail = _domWriteTail._next = chain;
550 }
551 }
552
553 void domRead(fn()) {
554 var chain = new _FunctionChain(fn);
555 if (_domReadHead == null) {
556 _domReadHead = _domReadTail = chain;
557 } else {
558 _domReadTail = _domReadTail._next = chain;
559 }
560 }
561
562 void destroy() {}
563
564 void _transitionState(String from, String to) {
565 assert(isAttached);
566 if (_state != from) throw "$_state already in progress can not enter $to.";
567 _state = to;
568 }
569 }
570
571 /**
572 * Keeps track of Streams for each Scope. When emitting events
573 * we would need to walk the whole tree. Its faster if we can prune
574 * the Scopes we have to visit.
575 *
576 * Scope with no [_ScopeStreams] has no events registered on itself or children
577 *
578 * We keep track of [Stream]s, and also child scope [Stream]s. To save
579 * memory we use the same stream object on all of our parents if they don't
580 * have one. But that means that we have to keep track if the stream belongs
581 * to the node.
582 *
583 * Scope with [_ScopeStreams] but who's [_scope] does not match the scope
584 * is only inherited
585 *
586 * Only [Scope] with [_ScopeStreams] who's [_scope] matches the [Scope]
587 * instance is the actual scope.
588 *
589 * Once the [Stream] is created it can not be removed even if all listeners
590 * are canceled. That is because we don't know if someone still has reference
591 * to it.
592 */
593 class _Streams {
594 final ExceptionHandler _exceptionHandler;
595 /// Scope we belong to.
596 final Scope _scope;
597 /// [Stream]s for [_scope] only
598 final _streams = new Map<String, ScopeStream>();
599 /// Child [Scope] event counts.
600 final Map<String, int> _typeCounts;
601
602 _Streams(this._scope, this._exceptionHandler, _Streams inheritStreams)
603 : _typeCounts = inheritStreams == null
604 ? <String, int>{}
605 : new Map.from(inheritStreams._typeCounts);
606
607 static ScopeEvent emit(Scope scope, String name, data) {
608 var event = new ScopeEvent(name, scope, data);
609 var scopeCursor = scope;
610 while(scopeCursor != null) {
611 if (scopeCursor._streams != null &&
612 scopeCursor._streams._scope == scopeCursor) {
613 ScopeStream stream = scopeCursor._streams._streams[name];
614 if (stream != null) {
615 event._currentScope = scopeCursor;
616 stream._fire(event);
617 if (event.propagationStopped) return event;
618 }
879 } 619 }
880 620 scopeCursor = scopeCursor._parentScope;
881 // Insanity Warning: scope depth-first traversal 621 }
882 // yes, this code is a bit crazy, but it works and we have tests to prove it! 622 return event;
883 // this piece should be kept in sync with the traversal in $broadcast 623 }
884 if (current._childHead == null) { 624
885 if (current == target) { 625 static ScopeEvent broadcast(Scope scope, String name, data) {
886 next = null; 626 _Streams scopeStreams = scope._streams;
627 var event = new ScopeEvent(name, scope, data);
628 if (scopeStreams != null && scopeStreams._typeCounts.containsKey(name)) {
629 var queue = new Queue()..addFirst(scopeStreams._scope);
630 while (queue.isNotEmpty) {
631 scope = queue.removeFirst();
632 scopeStreams = scope._streams;
633 assert(scopeStreams._scope == scope);
634 if (scopeStreams._streams.containsKey(name)) {
635 var stream = scopeStreams._streams[name];
636 event._currentScope = scope;
637 stream._fire(event);
638 }
639 // Reverse traversal so that when the queue is read it is correct order.
640 var childScope = scope._childTail;
641 while(childScope != null) {
642 scopeStreams = childScope._streams;
643 if (scopeStreams != null &&
644 scopeStreams._typeCounts.containsKey(name)) {
645 queue.addFirst(scopeStreams._scope);
646 }
647 childScope = childScope._prev;
648 }
649 }
650 }
651 return event;
652 }
653
654 static ScopeStream on(Scope scope,
655 ExceptionHandler _exceptionHandler,
656 String name) {
657 _forceNewScopeStream(scope, _exceptionHandler);
658 return scope._streams._get(scope, name);
659 }
660
661 static void _forceNewScopeStream(scope, _exceptionHandler) {
662 _Streams streams = scope._streams;
663 Scope scopeCursor = scope;
664 bool splitMode = false;
665 while(scopeCursor != null) {
666 _Streams cursorStreams = scopeCursor._streams;
667 var hasStream = cursorStreams != null;
668 var hasOwnStream = hasStream && cursorStreams._scope == scopeCursor;
669 if (hasOwnStream) return;
670
671 if (!splitMode && (streams == null || (hasStream && !hasOwnStream))) {
672 if (hasStream && !hasOwnStream) {
673 splitMode = true;
674 }
675 streams = new _Streams(scopeCursor, _exceptionHandler, cursorStreams);
676 }
677 scopeCursor._streams = streams;
678 scopeCursor = scopeCursor._parentScope;
679 }
680 }
681
682 static void destroy(Scope scope) {
683 var toBeDeletedStreams = scope._streams;
684 if (toBeDeletedStreams == null) return; // no streams to clean up
685 var parentScope = scope._parentScope; // skip current scope as not to delete listeners
686 // find the parent-most scope which still has our stream to be deleted.
687 while (parentScope != null && parentScope._streams == toBeDeletedStreams) {
688 parentScope._streams = null;
689 parentScope = parentScope._parentScope;
690 }
691 // At this point scope is the parent-most scope which has its own typeCounts
692 if (parentScope == null) return;
693 var parentStreams = parentScope._streams;
694 assert(parentStreams != toBeDeletedStreams);
695 // remove typeCounts from the scope to be destroyed from the parent
696 // typeCounts
697 toBeDeletedStreams._typeCounts.forEach(
698 (name, count) => parentStreams._addCount(name, -count));
699 }
700
701 async.Stream _get(Scope scope, String name) {
702 assert(scope._streams == this);
703 assert(scope._streams._scope == scope);
704 assert(_exceptionHandler != null);
705 return _streams.putIfAbsent(name, () =>
706 new ScopeStream(this, _exceptionHandler, name));
707 }
708
709 void _addCount(String name, int amount) {
710 // decrement the counters on all parent scopes
711 _Streams lastStreams = null;
712 var scope = _scope;
713 while (scope != null) {
714 if (lastStreams != scope._streams) {
715 // we have a transition, need to decrement it
716 lastStreams = scope._streams;
717 int count = lastStreams._typeCounts[name];
718 count = count == null ? amount : count + amount;
719 assert(count >= 0);
720 if (count == 0) {
721 lastStreams._typeCounts.remove(name);
722 if (_scope == scope) _streams.remove(name);
887 } else { 723 } else {
888 next = current._nextSibling; 724 lastStreams._typeCounts[name] = count;
889 if (next == null) { 725 }
890 while(current != target && (next = current._nextSibling) == null) {
891 current = current.$parent;
892 }
893 }
894 }
895 } else {
896 next = current._childHead;
897 } 726 }
898 } while ((current = next) != null); 727 scope = scope._parentScope;
899 728 }
900 return event; 729 }
901 } 730 }
902 731
903 _beginPhase(phase) { 732 class ScopeStream extends async.Stream<ScopeEvent> {
904 if ($root._phase != null) { 733 final ExceptionHandler _exceptionHandler;
905 // TODO(deboer): Remove the []s when dartbug.com/11999 is fixed. 734 final _Streams _streams;
906 throw ['${$root._phase} already in progress']; 735 final String _name;
907 } 736 final subscriptions = <ScopeStreamSubscription>[];
908 assert(_perf.startTimer('ng.phase.${phase}') != false); 737
909 738 ScopeStream(this._streams, this._exceptionHandler, this._name);
910 $root._phase = phase; 739
911 } 740 ScopeStreamSubscription listen(void onData(ScopeEvent event),
912 741 { Function onError,
913 _clearPhase() { 742 void onDone(),
914 assert(_perf.stopTimer('ng.phase.${$root._phase}') != false); 743 bool cancelOnError }) {
915 $root._phase = null; 744 if (subscriptions.isEmpty) _streams._addCount(_name, 1);
916 } 745 var subscription = new ScopeStreamSubscription(this, onData);
917 746 subscriptions.add(subscription);
918 Function _compileToFn(exp) { 747 return subscription;
919 if (exp == null) { 748 }
920 return () => null; 749
921 } else if (exp is String) { 750 void _fire(ScopeEvent event) {
922 Expression expression = _parser(exp); 751 for (ScopeStreamSubscription subscription in subscriptions) {
923 return expression.eval; 752 try {
924 } else if (exp is Function) { 753 subscription._onData(event);
925 return exp; 754 } catch (e, s) {
755 _exceptionHandler(e, s);
756 }
757 }
758 }
759
760 void _remove(ScopeStreamSubscription subscription) {
761 assert(subscription._scopeStream == this);
762 if (subscriptions.remove(subscription)) {
763 if (subscriptions.isEmpty) _streams._addCount(_name, -1);
926 } else { 764 } else {
927 throw 'Expecting String or Function'; 765 throw new StateError('AlreadyCanceled');
928 } 766 }
929 } 767 }
930 } 768 }
931 769
932 @proxy 770 class ScopeStreamSubscription implements async.StreamSubscription<ScopeEvent> {
933 class ScopeLocals implements Scope, Map { 771 final ScopeStream _scopeStream;
934 static wrapper(dynamic scope, Map<String, Object> locals) => new ScopeLocals(s cope, locals); 772 final Function _onData;
935 773 ScopeStreamSubscription(this._scopeStream, this._onData);
936 dynamic _scope; 774
937 Map<String, Object> _locals; 775 // TODO(vbe) should return a Future
938 776 cancel() => _scopeStream._remove(this);
939 ScopeLocals(this._scope, this._locals); 777
940 778 void onData(void handleData(ScopeEvent data)) => NOT_IMPLEMENTED();
941 operator []=(String name, value) => _scope[name] = value; 779 void onError(Function handleError) => NOT_IMPLEMENTED();
942 operator [](String name) => (_locals.containsKey(name) ? _locals : _scope)[nam e]; 780 void onDone(void handleDone()) => NOT_IMPLEMENTED();
943 781 void pause([async.Future resumeSignal]) => NOT_IMPLEMENTED();
944 noSuchMethod(Invocation invocation) => mirror.reflect(_scope).delegate(invocat ion); 782 void resume() => NOT_IMPLEMENTED();
945 } 783 bool get isPaused => NOT_IMPLEMENTED();
946 784 async.Future asFuture([var futureValue]) => NOT_IMPLEMENTED();
947 class _InitWatchVal { const _InitWatchVal(); } 785 }
948 const _initWatchVal = const _InitWatchVal(); 786
949 787 class _FunctionChain {
950 class _Watch {
951 final Function fn; 788 final Function fn;
952 final Function get; 789 _FunctionChain _next;
953 final String exp; 790
954 var last; 791 _FunctionChain(fn())
955 792 : fn = fn
956 _Watch previous; 793 {
957 _Watch next; 794 assert(fn != null);
958 795 }
959 _Watch(fn, this.last, getFn, this.exp) 796 }
960 : this.fn = relaxFnArgs3(fn) 797
961 , this.get = relaxFnArgs1(getFn); 798 class AstParser {
962 } 799 final Parser _parser;
963 800 int _id = 0;
964 class _WatchList { 801 ExpressionVisitor _visitor = new ExpressionVisitor();
965 int length = 0; 802
966 _Watch head; 803 AstParser(this._parser);
967 _Watch tail; 804
968 805 AST call(String exp, { FilterMap filters,
969 void addLast(_Watch watch) { 806 bool collection:false,
970 assert(watch.previous == null); 807 Object context:null }) {
971 assert(watch.next == null); 808 _visitor.filters = filters;
972 if (tail == null) { 809 AST contextRef = _visitor.contextRef;
973 tail = head = watch; 810 try {
974 } else { 811 if (context != null) {
975 watch.previous = tail; 812 _visitor.contextRef = new ConstantAST(context, '#${_id++}');
976 tail.next = watch;
977 tail = watch;
978 }
979 length++;
980 }
981
982 void remove(_Watch watch) {
983 if (watch == head) {
984 _Watch next = watch.next;
985 if (next == null) tail = null;
986 else next.previous = null;
987 head = next;
988 } else if (watch == tail) {
989 _Watch previous = watch.previous;
990 previous.next = null;
991 tail = previous;
992 } else {
993 _Watch next = watch.next;
994 _Watch previous = watch.previous;
995 previous.next = next;
996 next.previous = previous;
997 }
998 length--;
999 }
1000 }
1001
1002 _toJson(obj) {
1003 try {
1004 return JSON.encode(obj);
1005 } catch(e) {
1006 var ret = "NOT-JSONABLE";
1007 // Keep prod fast.
1008 assert((() {
1009 var mirror = reflect(obj);
1010 if (mirror is ClosureMirror) {
1011 // work-around dartbug.com/14130
1012 try {
1013 ret = mirror.function.source;
1014 } on NoSuchMethodError catch (e) {
1015 } on UnimplementedError catch (e) {
1016 }
1017 } 813 }
1018 return true; 814 var ast = _parser(exp);
1019 })()); 815 return collection ? _visitor.visitCollection(ast) : _visitor.visit(ast);
1020 return ret; 816 } finally {
1021 } 817 _visitor.contextRef = contextRef;
1022 } 818 _visitor.filters = null;
1023 819 }
1024 String _source(obj) { 820 }
1025 if (obj is Function) { 821 }
1026 var m = reflect(obj); 822
1027 if (m is ClosureMirror) { 823 class ExpressionVisitor implements Visitor {
1028 // work-around dartbug.com/14130 824 static final ContextReferenceAST scopeContextRef = new ContextReferenceAST();
1029 try { 825 AST contextRef = scopeContextRef;
1030 return "FN: ${m.function.source}"; 826
1031 } on NoSuchMethodError catch (e) { 827 AST ast;
1032 } on UnimplementedError catch (e) { 828 FilterMap filters;
829
830 AST visit(Expression exp) {
831 exp.accept(this);
832 assert(this.ast != null);
833 try {
834 return ast;
835 } finally {
836 ast = null;
837 }
838 }
839
840 AST visitCollection(Expression exp) => new CollectionAST(visit(exp));
841 AST _mapToAst(Expression expression) => visit(expression);
842
843 List<AST> _toAst(List<Expression> expressions) =>
844 expressions.map(_mapToAst).toList();
845
846 void visitCallScope(CallScope exp) {
847 ast = new MethodAST(contextRef, exp.name, _toAst(exp.arguments));
848 }
849 void visitCallMember(CallMember exp) {
850 ast = new MethodAST(visit(exp.object), exp.name, _toAst(exp.arguments));
851 }
852 visitAccessScope(AccessScope exp) {
853 ast = new FieldReadAST(contextRef, exp.name);
854 }
855 visitAccessMember(AccessMember exp) {
856 ast = new FieldReadAST(visit(exp.object), exp.name);
857 }
858 visitBinary(Binary exp) {
859 ast = new PureFunctionAST(exp.operation,
860 _operationToFunction(exp.operation),
861 [visit(exp.left), visit(exp.right)]);
862 }
863 void visitPrefix(Prefix exp) {
864 ast = new PureFunctionAST(exp.operation,
865 _operationToFunction(exp.operation),
866 [visit(exp.expression)]);
867 }
868 void visitConditional(Conditional exp) {
869 ast = new PureFunctionAST('?:', _operation_ternary,
870 [visit(exp.condition), visit(exp.yes),
871 visit(exp.no)]);
872 }
873 void visitAccessKeyed(AccessKeyed exp) {
874 ast = new PureFunctionAST('[]', _operation_bracket,
875 [visit(exp.object), visit(exp.key)]);
876 }
877 void visitLiteralPrimitive(LiteralPrimitive exp) {
878 ast = new ConstantAST(exp.value);
879 }
880 void visitLiteralString(LiteralString exp) {
881 ast = new ConstantAST(exp.value);
882 }
883 void visitLiteralArray(LiteralArray exp) {
884 List<AST> items = _toAst(exp.elements);
885 ast = new PureFunctionAST('[${items.join(', ')}]', new ArrayFn(), items);
886 }
887
888 void visitLiteralObject(LiteralObject exp) {
889 List<String> keys = exp.keys;
890 List<AST> values = _toAst(exp.values);
891 assert(keys.length == values.length);
892 var kv = <String>[];
893 for (var i = 0; i < keys.length; i++) {
894 kv.add('${keys[i]}: ${values[i]}');
895 }
896 ast = new PureFunctionAST('{${kv.join(', ')}}', new MapFn(keys), values);
897 }
898
899 void visitFilter(Filter exp) {
900 Function filterFunction = filters(exp.name);
901 List<AST> args = [visitCollection(exp.expression)];
902 args.addAll(_toAst(exp.arguments).map((ast) => new CollectionAST(ast)));
903 ast = new PureFunctionAST('|${exp.name}',
904 new _FilterWrapper(filterFunction, args.length), args);
905 }
906
907 // TODO(misko): this is a corner case. Choosing not to implement for now.
908 void visitCallFunction(CallFunction exp) {
909 _notSupported("function's returing functions");
910 }
911 void visitAssign(Assign exp) {
912 _notSupported('assignement');
913 }
914 void visitLiteral(Literal exp) {
915 _notSupported('literal');
916 }
917 void visitExpression(Expression exp) {
918 _notSupported('?');
919 }
920 void visitChain(Chain exp) {
921 _notSupported(';');
922 }
923
924 void _notSupported(String name) {
925 throw new StateError("Can not watch expression containing '$name'.");
926 }
927 }
928
929 Function _operationToFunction(String operation) {
930 switch(operation) {
931 case '!' : return _operation_negate;
932 case '+' : return _operation_add;
933 case '-' : return _operation_subtract;
934 case '*' : return _operation_multiply;
935 case '/' : return _operation_divide;
936 case '~/' : return _operation_divide_int;
937 case '%' : return _operation_remainder;
938 case '==' : return _operation_equals;
939 case '!=' : return _operation_not_equals;
940 case '<' : return _operation_less_then;
941 case '>' : return _operation_greater_then;
942 case '<=' : return _operation_less_or_equals_then;
943 case '>=' : return _operation_greater_or_equals_then;
944 case '^' : return _operation_power;
945 case '&' : return _operation_bitwise_and;
946 case '&&' : return _operation_logical_and;
947 case '||' : return _operation_logical_or;
948 default: throw new StateError(operation);
949 }
950 }
951
952 _operation_negate(value) => !toBool(value);
953 _operation_add(left, right) => autoConvertAdd(left, right);
954 _operation_subtract(left, right) => left - right;
955 _operation_multiply(left, right) => left * right;
956 _operation_divide(left, right) => left / right;
957 _operation_divide_int(left, right) => left ~/ right;
958 _operation_remainder(left, right) => left % right;
959 _operation_equals(left, right) => left == right;
960 _operation_not_equals(left, right) => left != right;
961 _operation_less_then(left, right) => left < right;
962 _operation_greater_then(left, right) => (left == null || right == null ) ? false : left > right;
963 _operation_less_or_equals_then(left, right) => left <= right;
964 _operation_greater_or_equals_then(left, right) => left >= right;
965 _operation_power(left, right) => left ^ right;
966 _operation_bitwise_and(left, right) => left & right;
967 // TODO(misko): these should short circuit the evaluation.
968 _operation_logical_and(left, right) => toBool(left) && toBool(right);
969 _operation_logical_or(left, right) => toBool(left) || toBool(right);
970
971 _operation_ternary(condition, yes, no) => toBool(condition) ? yes : no;
972 _operation_bracket(obj, key) => obj == null ? null : obj[key];
973
974 class ArrayFn extends FunctionApply {
975 // TODO(misko): figure out why do we need to make a copy?
976 apply(List args) => new List.from(args);
977 }
978
979 class MapFn extends FunctionApply {
980 final List<String> keys;
981
982 MapFn(this.keys);
983
984 apply(List values) {
985 // TODO(misko): figure out why do we need to make a copy instead of reusing instance?
986 assert(values.length == keys.length);
987 return new Map.fromIterables(keys, values);
988 }
989 }
990
991 class _FilterWrapper extends FunctionApply {
992 final Function filterFn;
993 final List args;
994 final List<Watch> argsWatches;
995 _FilterWrapper(this.filterFn, length):
996 args = new List(length),
997 argsWatches = new List(length);
998
999 apply(List values) {
1000 for (var i=0; i < values.length; i++) {
1001 var value = values[i];
1002 var lastValue = args[i];
1003 if (!identical(value, lastValue)) {
1004 if (value is CollectionChangeRecord) {
1005 args[i] = (value as CollectionChangeRecord).iterable;
1006 } else {
1007 args[i] = value;
1008 }
1033 } 1009 }
1034 } 1010 }
1035 } 1011 var value = Function.apply(filterFn, args);
1036 return '$obj'; 1012 if (value is Iterable) {
1037 } 1013 // Since filters are pure we can guarantee that this well never change.
1014 // By wrapping in UnmodifiableListView we can hint to the dirty checker
1015 // and short circuit the iterator.
1016 value = new UnmodifiableListView(value);
1017 }
1018 return value;
1019 }
1020 }
OLDNEW
« no previous file with comments | « third_party/pkg/angular/lib/core/registry.dart ('k') | third_party/pkg/angular/lib/core/zone.dart » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698