1 2 3 Polymer('core-iconset-svg', { 4 5 6 /** 7 * The size of an individual icon. Note that icons must be square. 8 * 9 * @attribute iconSize 10 * @type number 11 * @default 24 12 */ 13 iconSize: 24, 14 type: 'iconset', 15 16 created: function() { 17 this._icons = {}; 18 }, 19 20 ready: function() { 21 this.super(); 22 this.updateIcons(); 23 }, 24 25 iconById: function(id) { 26 return this._icons[id] || (this._icons[id] = this.querySelector('#' + id)); 27 }, 28 29 cloneIcon: function(id) { 30 var icon = this.iconById(id); 31 if (icon) { 32 var content = icon.cloneNode(true); 33 content.removeAttribute('id'); 34 var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); 35 svg.setAttribute('viewBox', '0 0 ' + this.iconSize + ' ' + 36 this.iconSize); 37 // NOTE(dfreedm): work around https://crbug.com/370136 38 svg.style.pointerEvents = 'none'; 39 svg.appendChild(content); 40 return svg; 41 } 42 }, 43 44 get iconNames() { 45 if (!this._iconNames) { 46 this._iconNames = this.findIconNames(); 47 } 48 return this._iconNames; 49 }, 50 51 findIconNames: function() { 52 var icons = this.querySelectorAll('[id]').array(); 53 if (icons.length) { 54 return icons.map(function(n){ return n.id }); 55 } 56 }, 57 58 /** 59 * Applies an icon to the given element. The svg icon is added to the 60 * element's shadowRoot if one exists or directly to itself. 61 * 62 * @method applyIcon 63 * @param {Element} element The element to which the icon is 64 * applied. 65 * @param {String|Number} icon The name the icon to apply. 66 * @return {Element} The icon element 67 */ 68 applyIcon: function(element, icon) { 69 var root = element; 70 // remove old 71 var old = root.querySelector('svg'); 72 if (old) { 73 old.remove(); 74 } 75 // install new 76 var svg = this.cloneIcon(icon); 77 if (!svg) { 78 return; 79 } 80 svg.setAttribute('height', '100%'); 81 svg.setAttribute('width', '100%'); 82 svg.setAttribute('preserveAspectRatio', 'xMidYMid meet'); 83 svg.style.display = 'block'; 84 root.insertBefore(svg, root.firstElementChild); 85 return svg; 86 }, 87 88 /** 89 * Tell users of the iconset, that the set has loaded. 90 * This finds all elements matching the selector argument and calls 91 * the method argument on them. 92 * @method updateIcons 93 * @param selector {string} css selector to identify iconset users, 94 * defaults to '[icon]' 95 * @param method {string} method to call on found elements, 96 * defaults to 'updateIcon' 97 */ 98 updateIcons: function(selector, method) { 99 selector = selector || '[icon]'; 100 method = method || 'updateIcon'; 101 var deep = window.ShadowDOMPolyfill ? '' : 'html /deep/ '; 102 var i$ = document.querySelectorAll(deep + selector); 103 for (var i=0, e; e=i$[i]; i++) { 104 if (e[method]) { 105 e[method].call(e); 106 } 107 } 108 } 109 110 111 }); 112 113