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

Side by Side Diff: observatory_pub_packages/polymer/src/declaration.dart

Issue 816693004: Add observatory_pub_packages snapshot to third_party (Closed) Base URL: http://dart.googlecode.com/svn/third_party/
Patch Set: Created 6 years 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 polymer;
6
7 /// *Warning* this class is experimental and subject to change.
8 ///
9 /// The data associated with a polymer-element declaration, if it is backed
10 /// by a Dart class instead of a JavaScript prototype.
11 class PolymerDeclaration {
12 /// The one syntax to rule them all.
13 static final BindingDelegate _polymerSyntax = new PolymerExpressions();
14
15 /// The polymer-element for this declaration.
16 final HtmlElement element;
17
18 /// The Dart type corresponding to this custom element declaration.
19 final Type type;
20
21 /// If we extend another custom element, this points to the super declaration.
22 final PolymerDeclaration superDeclaration;
23
24 /// The name of the custom element.
25 final String name;
26
27 /// Map of publish properties. Can be a field or a property getter, but if
28 /// this map contains a getter, is because it also has a corresponding setter.
29 ///
30 /// Note: technically these are always single properties, so we could use a
31 /// Symbol instead of a PropertyPath. However there are lookups between this
32 /// map and [_observe] so it is easier to just track paths.
33 Map<PropertyPath, smoke.Declaration> _publish;
34
35 /// The names of published properties for this polymer-element.
36 Iterable<String> get publishedProperties =>
37 _publish != null ? _publish.keys.map((p) => '$p') : const [];
38
39 /// Same as [_publish] but with lower case names.
40 Map<String, smoke.Declaration> _publishLC;
41
42 Map<PropertyPath, List<Symbol>> _observe;
43
44 /// Name and expression for each computed property.
45 Map<Symbol, String> _computed = {};
46
47 Map<String, Object> _instanceAttributes;
48
49 /// A set of properties that should be automatically reflected to attributes.
50 /// Typically this is used for CSS styling. If none, this variable will be
51 /// left as null.
52 Set<String> _reflect;
53
54 List<Element> _sheets;
55 List<Element> get sheets => _sheets;
56
57 List<Element> _styles;
58 List<Element> get styles => _styles;
59
60 // The default syntax for polymer-elements.
61 PolymerExpressions syntax = _polymerSyntax;
62
63 DocumentFragment get templateContent {
64 final template = fetchTemplate();
65 return template != null ? templateBind(template).content : null;
66 }
67
68 /// Maps event names and their associated method in the element class.
69 final Map<String, String> _eventDelegates = {};
70
71 /// Expected events per element node.
72 // TODO(sigmund): investigate whether we need more than 1 set of local events
73 // per element (why does the js implementation stores 1 per template node?)
74 Expando<Set<String>> _templateDelegates;
75
76 String get extendee => superDeclaration != null ?
77 superDeclaration.name : null;
78
79 /// The root URI for assets.
80 Uri _rootUri;
81
82 /// List of properties to ignore for observation.
83 static Set<Symbol> _OBSERVATION_BLACKLIST =
84 new HashSet.from(const [#attribute]);
85
86 static bool _canObserveProperty(Symbol property) =>
87 !_OBSERVATION_BLACKLIST.contains(property);
88
89 /// This list contains some property names that people commonly want to use,
90 /// but won't work because of Chrome/Safari bugs. It isn't an exhaustive
91 /// list. In particular it doesn't contain any property names found on
92 /// subtypes of HTMLElement (e.g. name, value). Rather it attempts to catch
93 /// some common cases.
94 ///
95 /// Dart Note: `class` is left out since its an invalid symbol in dart. This
96 /// means that nobody could make a property by this name anyways though.
97 /// Dart Note: We have added `classes` to this list, which is the dart:html
98 /// equivalent of `classList` but more likely to have conflicts.
99 static Set<Symbol> _PROPERTY_NAME_BLACKLIST = new HashSet.from([
100 const Symbol('children'), const Symbol('id'), const Symbol('hidden'),
101 const Symbol('style'), const Symbol('title'), const Symbol('classes')]);
102
103 bool _checkPropertyBlacklist(Symbol name) {
104 if (_PROPERTY_NAME_BLACKLIST.contains(name)) {
105 print('Cannot define property "$name" for element "${this.name}" '
106 'because it has the same name as an HTMLElement property, and not '
107 'all browsers support overriding that. Consider giving it a '
108 'different name. ');
109 return true;
110 }
111 return false;
112 }
113
114 // Dart note: since polymer-element is handled in JS now, we have a simplified
115 // flow for registering. We don't need to wait for the supertype or the code
116 // to be noticed.
117 PolymerDeclaration(this.element, this.name, this.type, this.superDeclaration);
118
119 void register() {
120 // more declarative features
121 desugar();
122 // register our custom element
123 registerType(name);
124
125 // NOTE: skip in Dart because we don't have mutable global scope.
126 // reference constructor in a global named by 'constructor' attribute
127 // publishConstructor();
128 }
129
130 /// Implement various declarative features.
131 // Dart note: this merges "buildPrototype" "desugarBeforeChaining" and
132 // "desugarAfterChaining", because we don't have prototypes.
133 void desugar() {
134
135 // back reference declaration element
136 _declarations[name] = this;
137
138 // transcribe `attributes` declarations onto own prototype's `publish`
139 publishAttributes(superDeclaration);
140
141 publishProperties();
142
143 inferObservers();
144
145 // desugar compound observer syntax, e.g. @ObserveProperty('a b c')
146 explodeObservers();
147
148 createPropertyAccessors();
149 // install mdv delegate on template
150 installBindingDelegate(fetchTemplate());
151 // install external stylesheets as if they are inline
152 installSheets();
153 // adjust any paths in dom from imports
154 resolveElementPaths(element);
155 // compile list of attributes to copy to instances
156 accumulateInstanceAttributes();
157 // parse on-* delegates declared on `this` element
158 parseHostEvents();
159 // install a helper method this.resolvePath to aid in
160 // setting resource urls. e.g.
161 // this.$.image.src = this.resolvePath('images/foo.png')
162 initResolvePath();
163 // under ShadowDOMPolyfill, transforms to approximate missing CSS features
164 _shimShadowDomStyling(templateContent, name, extendee);
165
166 // TODO(jmesserly): this feels unnatrual in Dart. Since we have convenient
167 // lazy static initialization, can we get by without it?
168 if (smoke.hasStaticMethod(type, #registerCallback)) {
169 smoke.invoke(type, #registerCallback, [this]);
170 }
171 }
172
173 void registerType(String name) {
174 var baseTag;
175 var decl = this;
176 while (decl != null) {
177 baseTag = decl.element.attributes['extends'];
178 decl = decl.superDeclaration;
179 }
180 document.registerElement(name, type, extendsTag: baseTag);
181 }
182
183 // from declaration/mdv.js
184 Element fetchTemplate() => element.querySelector('template');
185
186 void installBindingDelegate(Element template) {
187 if (template != null) {
188 templateBind(template).bindingDelegate = this.syntax;
189 }
190 }
191
192 // from declaration/path.js
193 void resolveElementPaths(Node node) {
194 if (_Polymer == null) return;
195 _Polymer['urlResolver'].callMethod('resolveDom', [node]);
196 }
197
198 // Dart note: renamed from "addResolvePathApi".
199 void initResolvePath() {
200 // let assetpath attribute modify the resolve path
201 var assetPath = element.attributes['assetpath'];
202 if (assetPath == null) assetPath = '';
203 var base = Uri.parse(element.ownerDocument.baseUri);
204 _rootUri = base.resolve(assetPath);
205 }
206
207 String resolvePath(String urlPath, [baseUrlOrString]) {
208 Uri base;
209 if (baseUrlOrString == null) {
210 // Dart note: this enforces the same invariant as JS, where you need to
211 // call addResolvePathApi first.
212 if (_rootUri == null) {
213 throw new StateError('call initResolvePath before calling resolvePath');
214 }
215 base = _rootUri;
216 } else if (baseUrlOrString is Uri) {
217 base = baseUrlOrString;
218 } else {
219 base = Uri.parse(baseUrlOrString);
220 }
221 return base.resolve(urlPath).toString();
222 }
223
224 void publishAttributes(PolymerDeclaration superDecl) {
225 // get properties to publish
226 if (superDecl != null) {
227 // Dart note: even though we walk the type hierarchy in
228 // _getPublishedProperties, this will additionally include any names
229 // published via the `attributes` attribute.
230 if (superDecl._publish != null) {
231 _publish = new Map.from(superDecl._publish);
232 }
233 if (superDecl._reflect != null) {
234 _reflect = new Set.from(superDecl._reflect);
235 }
236 }
237
238 _getPublishedProperties(type);
239
240 // merge names from 'attributes' attribute into the '_publish' object
241 var attrs = element.attributes['attributes'];
242 if (attrs != null) {
243 // names='a b c' or names='a,b,c'
244 // record each name for publishing
245 for (var attr in attrs.split(_ATTRIBUTES_REGEX)) {
246 // remove excess ws
247 attr = attr.trim();
248
249 // if the user hasn't specified a value, we want to use the
250 // default, unless a superclass has already chosen one
251 if (attr == '') continue;
252
253 var decl, path;
254 var property = smoke.nameToSymbol(attr);
255 if (property != null) {
256 path = new PropertyPath([property]);
257 if (_publish != null && _publish.containsKey(path)) {
258 continue;
259 }
260 decl = smoke.getDeclaration(type, property);
261 }
262
263 if (property == null || decl == null || decl.isMethod || decl.isFinal) {
264 window.console.warn('property for attribute $attr of polymer-element '
265 'name=$name not found.');
266 continue;
267 }
268 if (_publish == null) _publish = {};
269 _publish[path] = decl;
270 }
271 }
272
273 // NOTE: the following is not possible in Dart; fields must be declared.
274 // install 'attributes' as properties on the prototype,
275 // but don't override
276 }
277
278 void _getPublishedProperties(Type type) {
279 var options = const smoke.QueryOptions(includeInherited: true,
280 includeUpTo: HtmlElement, withAnnotations: const [PublishedProperty]);
281 for (var decl in smoke.query(type, options)) {
282 if (decl.isFinal) continue;
283 if (_checkPropertyBlacklist(decl.name)) continue;
284 if (_publish == null) _publish = {};
285 _publish[new PropertyPath([decl.name])] = decl;
286
287 // Should we reflect the property value to the attribute automatically?
288 if (decl.annotations
289 .where((a) => a is PublishedProperty)
290 .any((a) => a.reflect)) {
291
292 if (_reflect == null) _reflect = new Set();
293 _reflect.add(smoke.symbolToName(decl.name));
294 }
295 }
296 }
297
298
299 void accumulateInstanceAttributes() {
300 // inherit instance attributes
301 _instanceAttributes = new Map<String, Object>();
302 if (superDeclaration != null) {
303 _instanceAttributes.addAll(superDeclaration._instanceAttributes);
304 }
305
306 // merge attributes from element
307 element.attributes.forEach((name, value) {
308 if (isInstanceAttribute(name)) {
309 _instanceAttributes[name] = value;
310 }
311 });
312 }
313
314 static bool isInstanceAttribute(name) {
315 // do not clone these attributes onto instances
316 final blackList = const {
317 'name': 1,
318 'extends': 1,
319 'constructor': 1,
320 'noscript': 1,
321 'assetpath': 1,
322 'cache-csstext': 1,
323 // add ATTRIBUTES_ATTRIBUTE to the blacklist
324 'attributes': 1,
325 };
326
327 return !blackList.containsKey(name) && !name.startsWith('on-');
328 }
329
330 /// Extracts events from the element tag attributes.
331 void parseHostEvents() {
332 addAttributeDelegates(_eventDelegates);
333 }
334
335 void addAttributeDelegates(Map<String, String> delegates) {
336 element.attributes.forEach((name, value) {
337 if (_hasEventPrefix(name)) {
338 var start = value.indexOf('{{');
339 var end = value.lastIndexOf('}}');
340 if (start >= 0 && end >= 0) {
341 delegates[_removeEventPrefix(name)] =
342 value.substring(start + 2, end).trim();
343 }
344 }
345 });
346 }
347
348 String urlToPath(String url) {
349 if (url == null) return '';
350 return (url.split('/')..removeLast()..add('')).join('/');
351 }
352
353 // Dart note: loadStyles, convertSheetsToStyles, copySheetAttribute and
354 // findLoadableStyles are not ported because they're handled by Polymer JS
355 // before we get into [register].
356
357 /// Install external stylesheets loaded in <element> elements into the
358 /// element's template.
359 void installSheets() {
360 cacheSheets();
361 cacheStyles();
362 installLocalSheets();
363 installGlobalStyles();
364 }
365
366 void cacheSheets() {
367 _sheets = findNodes(_SHEET_SELECTOR);
368 for (var s in sheets) s.remove();
369 }
370
371 void cacheStyles() {
372 _styles = findNodes('$_STYLE_SELECTOR[$_SCOPE_ATTR]');
373 for (var s in styles) s.remove();
374 }
375
376 /// Takes external stylesheets loaded in an `<element>` element and moves
377 /// their content into a style element inside the `<element>`'s template.
378 /// The sheet is then removed from the `<element>`. This is done only so
379 /// that if the element is loaded in the main document, the sheet does
380 /// not become active.
381 /// Note, ignores sheets with the attribute 'polymer-scope'.
382 void installLocalSheets() {
383 var sheets = this.sheets.where(
384 (s) => !s.attributes.containsKey(_SCOPE_ATTR));
385 var content = templateContent;
386 if (content != null) {
387 var cssText = new StringBuffer();
388 for (var sheet in sheets) {
389 cssText..write(_cssTextFromSheet(sheet))..write('\n');
390 }
391 if (cssText.length > 0) {
392 var style = element.ownerDocument.createElement('style')
393 ..text = '$cssText';
394
395 content.insertBefore(style, content.firstChild);
396 }
397 }
398 }
399
400 List<Element> findNodes(String selector, [bool matcher(Element e)]) {
401 var nodes = element.querySelectorAll(selector).toList();
402 var content = templateContent;
403 if (content != null) {
404 nodes = nodes..addAll(content.querySelectorAll(selector));
405 }
406 if (matcher != null) return nodes.where(matcher).toList();
407 return nodes;
408 }
409
410 /// Promotes external stylesheets and style elements with the attribute
411 /// polymer-scope='global' into global scope.
412 /// This is particularly useful for defining @keyframe rules which
413 /// currently do not function in scoped or shadow style elements.
414 /// (See wkb.ug/72462)
415 // TODO(sorvell): remove when wkb.ug/72462 is addressed.
416 void installGlobalStyles() {
417 var style = styleForScope(_STYLE_GLOBAL_SCOPE);
418 Polymer.applyStyleToScope(style, document.head);
419 }
420
421 String cssTextForScope(String scopeDescriptor) {
422 var cssText = new StringBuffer();
423 // handle stylesheets
424 var selector = '[$_SCOPE_ATTR=$scopeDescriptor]';
425 matcher(s) => s.matches(selector);
426
427 for (var sheet in sheets.where(matcher)) {
428 cssText..write(_cssTextFromSheet(sheet))..write('\n\n');
429 }
430 // handle cached style elements
431 for (var style in styles.where(matcher)) {
432 cssText..write(style.text)..write('\n\n');
433 }
434 return cssText.toString();
435 }
436
437 StyleElement styleForScope(String scopeDescriptor) {
438 var cssText = cssTextForScope(scopeDescriptor);
439 return cssTextToScopeStyle(cssText, scopeDescriptor);
440 }
441
442 StyleElement cssTextToScopeStyle(String cssText, String scopeDescriptor) {
443 if (cssText == '') return null;
444
445 return new StyleElement()
446 ..text = cssText
447 ..attributes[_STYLE_SCOPE_ATTRIBUTE] = '$name-$scopeDescriptor';
448 }
449
450 /// Fetch a list of all *Changed methods so we can observe the associated
451 /// properties.
452 void inferObservers() {
453 for (var decl in smoke.query(type, _changedMethodQueryOptions)) {
454 // TODO(jmesserly): now that we have a better system, should we
455 // deprecate *Changed methods?
456 if (_observe == null) _observe = new HashMap();
457 var name = smoke.symbolToName(decl.name);
458 name = name.substring(0, name.length - 7);
459 if (!_canObserveProperty(decl.name)) continue;
460 _observe[new PropertyPath(name)] = [decl.name];
461 }
462 }
463
464 /// Fetch a list of all methods annotated with [ObserveProperty] so we can
465 /// observe the associated properties.
466 void explodeObservers() {
467 var options = const smoke.QueryOptions(includeFields: false,
468 includeProperties: false, includeMethods: true, includeInherited: true,
469 includeUpTo: HtmlElement, withAnnotations: const [ObserveProperty]);
470 for (var decl in smoke.query(type, options)) {
471 for (var meta in decl.annotations) {
472 if (meta is! ObserveProperty) continue;
473 if (_observe == null) _observe = new HashMap();
474 for (String name in meta.names) {
475 _observe.putIfAbsent(new PropertyPath(name), () => []).add(decl.name);
476 }
477 }
478 }
479 }
480
481 void publishProperties() {
482 // Dart note: _publish was already populated by publishAttributes
483 if (_publish != null) _publishLC = _lowerCaseMap(_publish);
484 }
485
486 Map<String, dynamic> _lowerCaseMap(Map<PropertyPath, dynamic> properties) {
487 final map = new Map<String, dynamic>();
488 properties.forEach((PropertyPath path, value) {
489 map['$path'.toLowerCase()] = value;
490 });
491 return map;
492 }
493
494 void createPropertyAccessors() {
495 // Dart note: since we don't have a prototype in Dart, most of the work of
496 // createPolymerAccessors is done lazily on the first access of properties.
497 // Here we just extract the information from annotations and store it as
498 // properties on the declaration.
499
500 // Dart Note: The js side makes computed properties read only, and does
501 // special logic right here for them. For us they are automatically read
502 // only unless you define a setter for them, so we left that out.
503 var options = const smoke.QueryOptions(includeInherited: true,
504 includeUpTo: HtmlElement, withAnnotations: const [ComputedProperty]);
505 var existing = {};
506 for (var decl in smoke.query(type, options)) {
507 var name = decl.name;
508 if (_checkPropertyBlacklist(name)) continue;
509 var meta = decl.annotations.firstWhere((e) => e is ComputedProperty);
510 var prev = existing[name];
511 // The definition of a child class takes priority.
512 if (prev == null || smoke.isSubclassOf(decl.type, prev.type)) {
513 _computed[name] = meta.expression;
514 existing[name] = decl;
515 }
516 }
517 }
518 }
519
520 /// maps tag names to prototypes
521 final Map _typesByName = new Map<String, Type>();
522
523 Type _getRegisteredType(String name) => _typesByName[name];
524
525 /// Dart Note: instanceOfType not implemented for dart, its not needed.
526
527 /// track document.register'ed tag names and their declarations
528 final Map _declarations = new Map<String, PolymerDeclaration>();
529
530 bool _isRegistered(String name) => _declarations.containsKey(name);
531 PolymerDeclaration _getDeclaration(String name) => _declarations[name];
532
533 /// Using Polymer's web_components/src/ShadowCSS.js passing the style tag's
534 /// content.
535 void _shimShadowDomStyling(DocumentFragment template, String name,
536 String extendee) {
537 if (_ShadowCss == null ||!_hasShadowDomPolyfill) return;
538
539 _ShadowCss.callMethod('shimStyling', [template, name, extendee]);
540 }
541
542 final bool _hasShadowDomPolyfill = js.context.hasProperty('ShadowDOMPolyfill');
543 final JsObject _ShadowCss =
544 _WebComponents != null ? _WebComponents['ShadowCSS'] : null;
545
546 const _STYLE_SELECTOR = 'style';
547 const _SHEET_SELECTOR = 'link[rel=stylesheet]';
548 const _STYLE_GLOBAL_SCOPE = 'global';
549 const _SCOPE_ATTR = 'polymer-scope';
550 const _STYLE_SCOPE_ATTRIBUTE = 'element';
551 const _STYLE_CONTROLLER_SCOPE = 'controller';
552
553 String _cssTextFromSheet(LinkElement sheet) {
554 if (sheet == null) return '';
555
556 // In deploy mode we should never do a sync XHR; link rel=stylesheet will
557 // be inlined into a <style> tag by ImportInliner.
558 if (loader.deployMode) return '';
559
560 // TODO(jmesserly): sometimes the href property is wrong after deployment.
561 var href = sheet.href;
562 if (href == '') href = sheet.attributes["href"];
563
564 // TODO(jmesserly): it seems like polymer-js is always polyfilling
565 // HTMLImports, because their code depends on "__resource" to work, so I
566 // don't see how it can work with native HTML Imports. We use a sync-XHR
567 // under the assumption that the file is likely to have been already
568 // downloaded and cached by HTML Imports.
569 try {
570 return (new HttpRequest()
571 ..open('GET', href, async: false)
572 ..send())
573 .responseText;
574 } on DomException catch (e, t) {
575 _sheetLog.fine('failed to XHR stylesheet text href="$href" error: '
576 '$e, trace: $t');
577 return '';
578 }
579 }
580
581 final Logger _sheetLog = new Logger('polymer.stylesheet');
582
583
584 final smoke.QueryOptions _changedMethodQueryOptions = new smoke.QueryOptions(
585 includeFields: false, includeProperties: false, includeMethods: true,
586 includeInherited: true, includeUpTo: HtmlElement,
587 matches: _isObserverMethod);
588
589 bool _isObserverMethod(Symbol symbol) {
590 String name = smoke.symbolToName(symbol);
591 if (name == null) return false;
592 return name.endsWith('Changed') && name != 'attributeChanged';
593 }
594
595
596 final _ATTRIBUTES_REGEX = new RegExp(r'\s|,');
597
598 final JsObject _WebComponents = js.context['WebComponents'];
599 final JsObject _Polymer = js.context['Polymer'];
OLDNEW
« no previous file with comments | « observatory_pub_packages/polymer/src/build/utils.dart ('k') | observatory_pub_packages/polymer/src/events.dart » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698