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

Side by Side Diff: tools/dom/src/PathObserver.dart

Issue 17434008: Move PathObserver to mdv_observe package (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: Created 7 years, 6 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
(Empty)
1 // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
2 // for details. All rights reserved. Use of this source code is governed by a
3 // BSD-style license that can be found in the LICENSE file.
4
5 part of html;
6
7 // This code is inspired by ChangeSummary:
8 // https://github.com/rafaelw/ChangeSummary/blob/master/change_summary.js
9 // ...which underlies MDV. Since we don't need the functionality of
10 // ChangeSummary, we just implement what we need for data bindings.
11 // This allows our implementation to be much simpler.
12
13 // TODO(jmesserly): should we make these types stronger, and require
14 // Observable objects? Currently, it is fine to say something like:
15 // var path = new PathObserver(123, '');
16 // print(path.value); // "123"
17 //
18 // Furthermore this degenerate case is allowed:
19 // var path = new PathObserver(123, 'foo.bar.baz.qux');
20 // print(path.value); // "null"
21 //
22 // Here we see that any invalid (i.e. not Observable) value will break the
23 // path chain without producing an error or exception.
24 //
25 // Now the real question: should we do this? For the former case, the behavior
26 // is correct but we could chose to handle it in the dart:html bindings layer.
27 // For the latter case, it might be better to throw an error so users can find
28 // the problem.
29
30
31 /**
32 * A data-bound path starting from a view-model or model object, for example
33 * `foo.bar.baz`.
34 *
35 * When the [values] stream is being listened to, this will observe changes to
36 * the object and any intermediate object along the path, and send [values]
37 * accordingly. When all listeners are unregistered it will stop observing
38 * the objects.
39 *
40 * This class is used to implement [Node.bind] and similar functionality.
41 */
42 // TODO(jmesserly): find a better home for this type.
43 @Experimental
44 class PathObserver {
45 /** The object being observed. */
46 final object;
47
48 /** The path string. */
49 final String path;
50
51 /** True if the path is valid, otherwise false. */
52 final bool _isValid;
53
54 // TODO(jmesserly): same issue here as ObservableMixin: is there an easier
55 // way to get a broadcast stream?
56 StreamController _values;
57 Stream _valueStream;
58
59 _PropertyObserver _observer, _lastObserver;
60
61 Object _lastValue;
62 bool _scheduled = false;
63
64 /**
65 * Observes [path] on [object] for changes. This returns an object that can be
66 * used to get the changes and get/set the value at this path.
67 * See [PathObserver.values] and [PathObserver.value].
68 */
69 PathObserver(this.object, String path)
70 : path = path, _isValid = _isPathValid(path) {
71
72 // TODO(jmesserly): if the path is empty, or the object is! Observable, we
73 // can optimize the PathObserver to be more lightweight.
74
75 _values = new StreamController.broadcast(sync: true,
76 onListen: _observe,
77 onCancel: _unobserve);
78
79 if (_isValid) {
80 var segments = [];
81 for (var segment in path.trim().split('.')) {
82 if (segment == '') continue;
83 var index = int.parse(segment, onError: (_) {});
84 segments.add(index != null ? index : new Symbol(segment));
85 }
86
87 // Create the property observer linked list.
88 // Note that the structure of a path can't change after it is initially
89 // constructed, even though the objects along the path can change.
90 for (int i = segments.length - 1; i >= 0; i--) {
91 _observer = new _PropertyObserver(this, segments[i], _observer);
92 if (_lastObserver == null) _lastObserver = _observer;
93 }
94 }
95 }
96
97 // TODO(jmesserly): we could try adding the first value to the stream, but
98 // that delivers the first record async.
99 /**
100 * Listens to the stream, and invokes the [callback] immediately with the
101 * current [value]. This is useful for bindings, which want to be up-to-date
102 * immediately.
103 */
104 StreamSubscription bindSync(void callback(value)) {
105 var result = values.listen(callback);
106 callback(value);
107 return result;
108 }
109
110 // TODO(jmesserly): should this be a change record with the old value?
111 // TODO(jmesserly): should this be a broadcast stream? We only need
112 // single-subscription in the bindings system, so single sub saves overhead.
113 /**
114 * Gets the stream of values that were observed at this path.
115 * This returns a single-subscription stream.
116 */
117 Stream get values => _values.stream;
118
119 /** Force synchronous delivery of [values]. */
120 void _deliverValues() {
121 _scheduled = false;
122
123 var newValue = value;
124 if (!identical(_lastValue, newValue)) {
125 _values.add(newValue);
126 _lastValue = newValue;
127 }
128 }
129
130 void _observe() {
131 if (_observer != null) {
132 _lastValue = value;
133 _observer.observe();
134 }
135 }
136
137 void _unobserve() {
138 if (_observer != null) _observer.unobserve();
139 }
140
141 void _notifyChange() {
142 if (_scheduled) return;
143 _scheduled = true;
144
145 // TODO(jmesserly): should we have a guarenteed order with respect to other
146 // paths? If so, we could implement this fairly easily by sorting instances
147 // of this class by birth order before delivery.
148 queueChangeRecords(_deliverValues);
149 }
150
151 /** Gets the last reported value at this path. */
152 get value {
153 if (!_isValid) return null;
154 if (_observer == null) return object;
155 _observer.ensureValue(object);
156 return _lastObserver.value;
157 }
158
159 /** Sets the value at this path. */
160 void set value(Object value) {
161 // TODO(jmesserly): throw if property cannot be set?
162 // MDV seems tolerant of these error.
163 if (_observer == null || !_isValid) return;
164 _observer.ensureValue(object);
165 var last = _lastObserver;
166 if (_setObjectProperty(last._object, last._property, value)) {
167 // Technically, this would get updated asynchronously via a change record.
168 // However, it is nice if calling the getter will yield the same value
169 // that was just set. So we use this opportunity to update our cache.
170 last.value = value;
171 }
172 }
173 }
174
175 // TODO(jmesserly): these should go away in favor of mirrors!
176 _getObjectProperty(object, property) {
177 if (object is List && property is int) {
178 if (property >= 0 && property < object.length) {
179 return object[property];
180 } else {
181 return null;
182 }
183 }
184
185 // TODO(jmesserly): what about length?
186 if (object is Map) return object[property];
187
188 if (object is Observable) return object.getValueWorkaround(property);
189
190 return null;
191 }
192
193 bool _setObjectProperty(object, property, value) {
194 if (object is List && property is int) {
195 object[property] = value;
196 } else if (object is Map) {
197 object[property] = value;
198 } else if (object is Observable) {
199 (object as Observable).setValueWorkaround(property, value);
200 } else {
201 return false;
202 }
203 return true;
204 }
205
206
207 class _PropertyObserver {
208 final PathObserver _path;
209 final _property;
210 final _PropertyObserver _next;
211
212 // TODO(jmesserly): would be nice not to store both of these.
213 Object _object;
214 Object _value;
215 StreamSubscription _sub;
216
217 _PropertyObserver(this._path, this._property, this._next);
218
219 get value => _value;
220
221 void set value(Object newValue) {
222 _value = newValue;
223 if (_next != null) {
224 if (_sub != null) _next.unobserve();
225 _next.ensureValue(_value);
226 if (_sub != null) _next.observe();
227 }
228 }
229
230 void ensureValue(object) {
231 // If we're observing, values should be up to date already.
232 if (_sub != null) return;
233
234 _object = object;
235 value = _getObjectProperty(object, _property);
236 }
237
238 void observe() {
239 if (_object is Observable) {
240 assert(_sub == null);
241 _sub = (_object as Observable).changes.listen(_onChange);
242 }
243 if (_next != null) _next.observe();
244 }
245
246 void unobserve() {
247 if (_sub == null) return;
248
249 _sub.cancel();
250 _sub = null;
251 if (_next != null) _next.unobserve();
252 }
253
254 void _onChange(List<ChangeRecord> changes) {
255 for (var change in changes) {
256 // TODO(jmesserly): what to do about "new Symbol" here?
257 // Ideally this would only preserve names if the user has opted in to
258 // them being preserved.
259 // TODO(jmesserly): should we drop observable maps with String keys?
260 // If so then we only need one check here.
261 if (change.changes(_property)) {
262 value = _getObjectProperty(_object, _property);
263 _path._notifyChange();
264 return;
265 }
266 }
267 }
268 }
269
270 // From: https://github.com/rafaelw/ChangeSummary/blob/master/change_summary.js
271
272 const _pathIndentPart = r'[$a-z0-9_]+[$a-z0-9_\d]*';
273 final _pathRegExp = new RegExp('^'
274 '(?:#?' + _pathIndentPart + ')?'
275 '(?:'
276 '(?:\\.' + _pathIndentPart + ')'
277 ')*'
278 r'$', caseSensitive: false);
279
280 final _spacesRegExp = new RegExp(r'\s');
281
282 bool _isPathValid(String s) {
283 s = s.replaceAll(_spacesRegExp, '');
284
285 if (s == '') return true;
286 if (s[0] == '.') return false;
287 return _pathRegExp.hasMatch(s);
288 }
OLDNEW
« no previous file with comments | « tests/html/path_observer_test.dart ('k') | tools/dom/templates/html/dart2js/html_dart2js.darttemplate » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698