| OLD | NEW |
| (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(onListen: _observe, onCancel: _unobserve); |
| 76 |
| 77 if (_isValid) { |
| 78 var segments = []; |
| 79 for (var segment in path.trim().split('.')) { |
| 80 if (segment == '') continue; |
| 81 var index = int.parse(segment, onError: (_) {}); |
| 82 segments.add(index != null ? index : new Symbol(segment)); |
| 83 } |
| 84 |
| 85 // Create the property observer linked list. |
| 86 // Note that the structure of a path can't change after it is initially |
| 87 // constructed, even though the objects along the path can change. |
| 88 for (int i = segments.length - 1; i >= 0; i--) { |
| 89 _observer = new _PropertyObserver(this, segments[i], _observer); |
| 90 if (_lastObserver == null) _lastObserver = _observer; |
| 91 } |
| 92 } |
| 93 } |
| 94 |
| 95 // TODO(jmesserly): we could try adding the first value to the stream, but |
| 96 // that delivers the first record async. |
| 97 /** |
| 98 * Listens to the stream, and invokes the [callback] immediately with the |
| 99 * current [value]. This is useful for bindings, which want to be up-to-date |
| 100 * immediately. |
| 101 */ |
| 102 StreamSubscription bindSync(void callback(value)) { |
| 103 var result = values.listen(callback); |
| 104 callback(value); |
| 105 return result; |
| 106 } |
| 107 |
| 108 // TODO(jmesserly): should this be a change record with the old value? |
| 109 // TODO(jmesserly): should this be a broadcast stream? We only need |
| 110 // single-subscription in the bindings system, so single sub saves overhead. |
| 111 /** |
| 112 * Gets the stream of values that were observed at this path. |
| 113 * This returns a single-subscription stream. |
| 114 */ |
| 115 Stream get values => _values.stream; |
| 116 |
| 117 /** Force synchronous delivery of [values]. */ |
| 118 void _deliverValues() { |
| 119 _scheduled = false; |
| 120 |
| 121 var newValue = value; |
| 122 if (!identical(_lastValue, newValue)) { |
| 123 _values.add(newValue); |
| 124 _lastValue = newValue; |
| 125 } |
| 126 } |
| 127 |
| 128 void _observe() { |
| 129 if (_observer != null) { |
| 130 _lastValue = value; |
| 131 _observer.observe(); |
| 132 } |
| 133 } |
| 134 |
| 135 void _unobserve() { |
| 136 if (_observer != null) _observer.unobserve(); |
| 137 } |
| 138 |
| 139 void _notifyChange() { |
| 140 if (_scheduled) return; |
| 141 _scheduled = true; |
| 142 |
| 143 // TODO(jmesserly): should we have a guarenteed order with respect to other |
| 144 // paths? If so, we could implement this fairly easily by sorting instances |
| 145 // of this class by birth order before delivery. |
| 146 queueChangeRecords(_deliverValues); |
| 147 } |
| 148 |
| 149 /** Gets the last reported value at this path. */ |
| 150 get value { |
| 151 if (!_isValid) return null; |
| 152 if (_observer == null) return object; |
| 153 _observer.ensureValue(object); |
| 154 return _lastObserver.value; |
| 155 } |
| 156 |
| 157 /** Sets the value at this path. */ |
| 158 void set value(Object value) { |
| 159 // TODO(jmesserly): throw if property cannot be set? |
| 160 // MDV seems tolerant of these error. |
| 161 if (_observer == null || !_isValid) return; |
| 162 _observer.ensureValue(object); |
| 163 var last = _lastObserver; |
| 164 if (_setObjectProperty(last._object, last._property, value)) { |
| 165 // Technically, this would get updated asynchronously via a change record. |
| 166 // However, it is nice if calling the getter will yield the same value |
| 167 // that was just set. So we use this opportunity to update our cache. |
| 168 last.value = value; |
| 169 } |
| 170 } |
| 171 } |
| 172 |
| 173 // TODO(jmesserly): these should go away in favor of mirrors! |
| 174 _getObjectProperty(object, property) { |
| 175 if (object is List && property is int) { |
| 176 if (property >= 0 && property < object.length) { |
| 177 return object[property]; |
| 178 } else { |
| 179 return null; |
| 180 } |
| 181 } |
| 182 |
| 183 // TODO(jmesserly): what about length? |
| 184 if (object is Map) return object[property]; |
| 185 |
| 186 if (object is Observable) return object.getValueWorkaround(property); |
| 187 |
| 188 return null; |
| 189 } |
| 190 |
| 191 bool _setObjectProperty(object, property, value) { |
| 192 if (object is List && property is int) { |
| 193 object[property] = value; |
| 194 } else if (object is Map) { |
| 195 object[property] = value; |
| 196 } else if (object is Observable) { |
| 197 (object as Observable).setValueWorkaround(property, value); |
| 198 } else { |
| 199 return false; |
| 200 } |
| 201 return true; |
| 202 } |
| 203 |
| 204 |
| 205 class _PropertyObserver { |
| 206 final PathObserver _path; |
| 207 final _property; |
| 208 final _PropertyObserver _next; |
| 209 |
| 210 // TODO(jmesserly): would be nice not to store both of these. |
| 211 Object _object; |
| 212 Object _value; |
| 213 StreamSubscription _sub; |
| 214 |
| 215 _PropertyObserver(this._path, this._property, this._next); |
| 216 |
| 217 get value => _value; |
| 218 |
| 219 void set value(Object newValue) { |
| 220 _value = newValue; |
| 221 if (_next != null) { |
| 222 if (_sub != null) _next.unobserve(); |
| 223 _next.ensureValue(_value); |
| 224 if (_sub != null) _next.observe(); |
| 225 } |
| 226 } |
| 227 |
| 228 void ensureValue(object) { |
| 229 // If we're observing, values should be up to date already. |
| 230 if (_sub != null) return; |
| 231 |
| 232 _object = object; |
| 233 value = _getObjectProperty(object, _property); |
| 234 } |
| 235 |
| 236 void observe() { |
| 237 if (_object is Observable) { |
| 238 assert(_sub == null); |
| 239 _sub = (_object as Observable).changes.listen(_onChange); |
| 240 } |
| 241 if (_next != null) _next.observe(); |
| 242 } |
| 243 |
| 244 void unobserve() { |
| 245 if (_sub == null) return; |
| 246 |
| 247 _sub.cancel(); |
| 248 _sub = null; |
| 249 if (_next != null) _next.unobserve(); |
| 250 } |
| 251 |
| 252 void _onChange(List<ChangeRecord> changes) { |
| 253 for (var change in changes) { |
| 254 // TODO(jmesserly): what to do about "new Symbol" here? |
| 255 // Ideally this would only preserve names if the user has opted in to |
| 256 // them being preserved. |
| 257 // TODO(jmesserly): should we drop observable maps with String keys? |
| 258 // If so then we only need one check here. |
| 259 if (change.changes(_property)) { |
| 260 value = _getObjectProperty(_object, _property); |
| 261 _path._notifyChange(); |
| 262 return; |
| 263 } |
| 264 } |
| 265 } |
| 266 } |
| 267 |
| 268 // From: https://github.com/rafaelw/ChangeSummary/blob/master/change_summary.js |
| 269 |
| 270 const _pathIndentPart = r'[$a-z0-9_]+[$a-z0-9_\d]*'; |
| 271 final _pathRegExp = new RegExp('^' |
| 272 '(?:#?' + _pathIndentPart + ')?' |
| 273 '(?:' |
| 274 '(?:\\.' + _pathIndentPart + ')' |
| 275 ')*' |
| 276 r'$', caseSensitive: false); |
| 277 |
| 278 final _spacesRegExp = new RegExp(r'\s'); |
| 279 |
| 280 bool _isPathValid(String s) { |
| 281 s = s.replaceAll(_spacesRegExp, ''); |
| 282 |
| 283 if (s == '') return true; |
| 284 if (s[0] == '.') return false; |
| 285 return _pathRegExp.hasMatch(s); |
| 286 } |
| OLD | NEW |