2 * Angular Material Design
3 * https://github.com/angular/material
7 goog.provide('ng.material.components.icon');
8 goog.require('ng.material.core');
11 * @name material.components.icon
15 angular.module('material.components.icon', [
18 .directive('mdIcon', mdIconDirective);
23 * @module material.components.icon
28 * The `<md-icon>` directive is an markup element useful for showing an icon based on a font-icon
29 * or a SVG. Icons are view-only elements that should not be used directly as buttons; instead nest a `<md-icon>`
30 * inside a `md-button` to add hover and click features.
32 * When using SVGs, both external SVGs (via URLs) or sets of SVGs [from icon sets] can be
33 * easily loaded and used.When use font-icons, developers must following three (3) simple steps:
36 * <li>Load the font library. e.g.<br/>
37 * <link href="https://fonts.googleapis.com/icon?family=Material+Icons"
38 * rel="stylesheet">
40 * <li> Use either (a) font-icon class names or (b) font ligatures to render the font glyph by using its textual name</li>
41 * <li> Use <md-icon md-font-icon="classname" /> or <br/>
42 * use <md-icon md-font-set="font library classname or alias"> textual_name </md-icon> or <br/>
43 * use <md-icon md-font-set="font library classname or alias"> numerical_character_reference </md-icon>
47 * Full details for these steps can be found:
50 * <li>http://google.github.io/material-design-icons/</li>
51 * <li>http://google.github.io/material-design-icons/#icon-font-for-the-web</li>
54 * The Material Design icon style <code>.material-icons</code> and the icon font references are published in
55 * Material Design Icons:
58 * <li>http://www.google.com/design/icons/</li>
59 * <li>https://www.google.com/design/icons/#ic_accessibility</li>
62 * <h2 id="material_design_icons">Material Design Icons</h2>
63 * Using the Material Design Icon-Selector, developers can easily and quickly search for a Material Design font-icon and
64 * determine its textual name and character reference code. Click on any icon to see the slide-up information
65 * panel with details regarding a SVG download or information on the font-icon usage.
67 * <a href="https://www.google.com/design/icons/#ic_accessibility" target="_blank" style="border-bottom:none;">
68 * <img src="https://cloud.githubusercontent.com/assets/210413/7902490/fe8dd14c-0780-11e5-98fb-c821cc6475e6.png"
69 * aria-label="Material Design Icon-Selector" style="max-width:75%;padding-left:10%">
72 * <span class="image_caption">
73 * Click on the image above to link to the
74 * <a href="https://www.google.com/design/icons/#ic_accessibility" target="_blank">Material Design Icon-Selector</a>.
77 * @param {string} md-font-icon Name of CSS icon associated with the font-face will be used
78 * to render the icon. Requires the fonts and the named CSS styles to be preloaded.
79 * @param {string} md-font-set CSS style name associated with the font library; which will be assigned as
80 * the class for the font-icon ligature. This value may also be an alias that is used to lookup the classname;
81 * internally use `$mdIconProvider.fontSet(<alias>)` to determine the style name.
82 * @param {string} md-svg-src URL [or expression ] used to load, cache, and display an external SVG.
83 * @param {string} md-svg-icon Name used for lookup of the icon from the internal cache; interpolated strings or
84 * expressions may also be used. Specific set names can be used with the syntax `<set name>:<icon name>`.<br/><br/>
85 * To use icon sets, developers are required to pre-register the sets using the `$mdIconProvider` service.
86 * @param {string=} aria-label Labels icon for accessibility. If an empty string is provided, icon
87 * will be hidden from accessibility layer with `aria-hidden="true"`. If there's no aria-label on the icon
88 * nor a label on the parent element, a warning will be logged to the console.
94 * <!-- Icon ID; may contain optional icon set prefix; icons must registered using $mdIconProvider -->
95 * <md-icon md-svg-icon="social:android" aria-label="android " ></md-icon>
97 * <!-- Icon urls; may be preloaded in templateCache -->
98 * <md-icon md-svg-src="/android.svg" aria-label="android " ></md-icon>
99 * <md-icon md-svg-src="{{ getAndroid() }}" aria-label="android " ></md-icon>
103 * Use the <code>$mdIconProvider</code> to configure your application with
107 * angular.module('appSvgIconSets', ['ngMaterial'])
108 * .controller('DemoCtrl', function($scope) {})
109 * .config(function($mdIconProvider) {
111 * .iconSet('social', 'img/icons/sets/social-icons.svg', 24)
112 * .defaultIconSet('img/icons/sets/core-icons.svg', 24);
117 * When using Font Icons with classnames:
120 * <md-icon md-font-icon="android" aria-label="android" ></md-icon>
121 * <md-icon class="icon_home" aria-label="Home" ></md-icon>
125 * When using Material Font Icons with ligatures:
127 * <!-- For Material Design Icons -->
128 * <!-- The class '.material-icons' is auto-added. -->
129 * <md-icon> face </md-icon>
130 * <md-icon class="md-light md-48"> face </md-icon>
131 * <md-icon md-font-set="material-icons"> face </md-icon>
132 * <md-icon> #xE87C; </md-icon>
135 * When using other Font-Icon libraries:
138 * // Specify a font-icon style alias
139 * angular.config(function($mdIconProvider) {
140 * $mdIconProvider.fontSet('fa', 'fontawesome');
145 * <md-icon md-font-set="fa">email</md-icon>
149 function mdIconDirective($mdIcon, $mdTheming, $mdAria, $interpolate ) {
153 fontSet : '@mdFontSet',
154 fontIcon: '@mdFontIcon',
155 svgIcon : '@mdSvgIcon',
160 template: getTemplate,
164 function getTemplate(element, attr) {
165 var isEmptyAttr = function(key) { return angular.isDefined(attr[key]) ? attr[key].length == 0 : false },
166 hasAttrValue = function(key) { return attr[key] && attr[key].length > 0; },
167 attrValue = function(key) { return hasAttrValue(key) ? attr[key] : '' };
169 // If using the deprecated md-font-icon API
170 // If using ligature-based font-icons, transclude the ligature or NRCs
172 var tmplFontIcon = '<span class="md-font {{classNames}}" ng-class="fontIcon"></span>';
173 var tmplFontSet = '<span class="{{classNames}}" ng-transclude></span>';
175 var tmpl = hasAttrValue('mdSvgIcon') ? '' :
176 hasAttrValue('mdSvgSrc') ? '' :
177 isEmptyAttr('mdFontIcon') ? '' :
178 hasAttrValue('mdFontIcon') ? tmplFontIcon : tmplFontSet;
180 // If available, lookup the fontSet style and add to the list of classnames
181 // NOTE: Material Icons expects classnames like `.material-icons.md-48` instead of `.material-icons .md-48`
183 var names = (tmpl == tmplFontSet) ? $mdIcon.fontSet(attrValue('mdFontSet')) + ' ' : '';
184 names = (names + attrValue('class')).trim();
186 return $interpolate( tmpl )({ classNames: names });
192 * Supports embedded SVGs, font-icons, & external SVGs
194 function postLink(scope, element, attr) {
197 // If using a font-icon, then the textual name of the icon itself
198 // provides the aria-label.
200 var label = attr.alt || scope.fontIcon || scope.svgIcon || element.text();
201 var attrName = attr.$normalize(attr.$attr.mdSvgIcon || attr.$attr.mdSvgSrc || '');
203 if ( !attr['aria-label'] ) {
205 if (label != '' && !parentsHaveText() ) {
207 $mdAria.expect(element, 'aria-label', label);
208 $mdAria.expect(element, 'role', 'img');
210 } else if ( !element.text() ) {
211 // If not a font-icon with ligature, then
212 // hide from the accessibility layer.
214 $mdAria.expect(element, 'aria-hidden', 'true');
219 // Use either pre-configured SVG or URL source, respectively.
220 attr.$observe(attrName, function(attrVal) {
224 $mdIcon(attrVal).then(function(svg) {
231 function parentsHaveText() {
232 var parent = element.parent();
233 if (parent.attr('aria-label') || parent.text()) {
236 else if(parent.parent().attr('aria-label') || parent.parent().text()) {
243 mdIconDirective.$inject = ["$mdIcon", "$mdTheming", "$mdAria", "$interpolate"];
246 .module('material.components.icon' )
247 .provider('$mdIcon', MdIconProvider);
251 * @name $mdIconProvider
252 * @module material.components.icon
255 * `$mdIconProvider` is used only to register icon IDs with URLs. These configuration features allow
256 * icons and icon sets to be pre-registered and associated with source URLs **before** the `<md-icon />`
257 * directives are compiled.
259 * If using font-icons, the developer is repsonsible for loading the fonts.
261 * If using SVGs, loading of the actual svg files are deferred to on-demand requests and are loaded
262 * internally by the `$mdIcon` service using the `$http` service. When an SVG is requested by name/ID,
263 * the `$mdIcon` service searches its registry for the associated source URL;
264 * that URL is used to on-demand load and parse the SVG dynamically.
268 * app.config(function($mdIconProvider) {
270 * // Configure URLs for icons specified by [set:]id.
273 * .defaultFontSet( 'fontawesome' )
274 * .defaultIconSet('my/app/icons.svg') // Register a default set of SVG icons
275 * .iconSet('social', 'my/app/social.svg') // Register a named icon set of SVGs
276 * .icon('android', 'my/app/android.svg') // Register a specific icon (by name)
277 * .icon('work:chair', 'my/app/chair.svg'); // Register icon in a specific set
281 * SVG icons and icon sets can be easily pre-loaded and cached using either (a) a build process or (b) a runtime
282 * **startup** process (shown below):
285 * app.config(function($mdIconProvider) {
287 * // Register a default set of SVG icon definitions
288 * $mdIconProvider.defaultIconSet('my/app/icons.svg')
291 * .run(function($http, $templateCache){
293 * // Pre-fetch icons sources by URL and cache in the $templateCache...
294 * // subsequent $http calls will look there first.
296 * var urls = [ 'imy/app/icons.svg', 'img/icons/android.svg'];
298 * angular.forEach(urls, function(url) {
299 * $http.get(url, {cache: $templateCache});
306 * NOTE: the loaded SVG data is subsequently cached internally for future requests.
312 * @name $mdIconProvider#icon
315 * Register a source URL for a specific icon name; the name may include optional 'icon set' name prefix.
316 * These icons will later be retrieved from the cache using `$mdIcon( <icon name> )`
318 * @param {string} id Icon name/id used to register the icon
319 * @param {string} url specifies the external location for the data file. Used internally by `$http` to load the
320 * data or as part of the lookup in `$templateCache` if pre-loading was configured.
321 * @param {string=} iconSize Number indicating the width and height of the icons in the set. All icons
322 * in the icon set must be the same size. Default size is 24.
324 * @returns {obj} an `$mdIconProvider` reference; used to support method call chains for the API
328 * app.config(function($mdIconProvider) {
330 * // Configure URLs for icons specified by [set:]id.
333 * .icon('android', 'my/app/android.svg') // Register a specific icon (by name)
334 * .icon('work:chair', 'my/app/chair.svg'); // Register icon in a specific set
341 * @name $mdIconProvider#iconSet
344 * Register a source URL for a 'named' set of icons; group of SVG definitions where each definition
345 * has an icon id. Individual icons can be subsequently retrieved from this cached set using
346 * `$mdIcon(<icon set name>:<icon name>)`
348 * @param {string} id Icon name/id used to register the iconset
349 * @param {string} url specifies the external location for the data file. Used internally by `$http` to load the
350 * data or as part of the lookup in `$templateCache` if pre-loading was configured.
351 * @param {string=} iconSize Number indicating the width and height of the icons in the set. All icons
352 * in the icon set must be the same size. Default size is 24.
354 * @returns {obj} an `$mdIconProvider` reference; used to support method call chains for the API
359 * app.config(function($mdIconProvider) {
361 * // Configure URLs for icons specified by [set:]id.
364 * .iconSet('social', 'my/app/social.svg') // Register a named icon set
371 * @name $mdIconProvider#defaultIconSet
374 * Register a source URL for the default 'named' set of icons. Unless explicitly registered,
375 * subsequent lookups of icons will failover to search this 'default' icon set.
376 * Icon can be retrieved from this cached, default set using `$mdIcon(<name>)`
378 * @param {string} url specifies the external location for the data file. Used internally by `$http` to load the
379 * data or as part of the lookup in `$templateCache` if pre-loading was configured.
380 * @param {string=} iconSize Number indicating the width and height of the icons in the set. All icons
381 * in the icon set must be the same size. Default size is 24.
383 * @returns {obj} an `$mdIconProvider` reference; used to support method call chains for the API
387 * app.config(function($mdIconProvider) {
389 * // Configure URLs for icons specified by [set:]id.
392 * .defaultIconSet( 'my/app/social.svg' ) // Register a default icon set
399 * @name $mdIconProvider#defaultFontSet
402 * When using Font-Icons, Angular Material assumes the the Material Design icons will be used and automatically
403 * configures the default font-set == 'material-icons'. Note that the font-set references the font-icon library
404 * class style that should be applied to the `<md-icon>`.
406 * Configuring the default means that the attributes
407 * `md-font-set="material-icons"` or `class="material-icons"` do not need to be explicitly declared on the
408 * `<md-icon>` markup. For example:
410 * `<md-icon> face </md-icon>`
412 * `<span class="material-icons"> face </span>`, and
414 * `<md-icon md-font-set="fa"> face </md-icon>`
416 * `<span class="fa"> face </span>`
418 * @param {string} name of the font-library style that should be applied to the md-icon DOM element
422 * app.config(function($mdIconProvider) {
423 * $mdIconProvider.defaultFontSet( 'fontawesome' );
431 * @name $mdIconProvider#defaultIconSize
434 * While `<md-icon />` markup can also be style with sizing CSS, this method configures
435 * the default width **and** height used for all icons; unless overridden by specific CSS.
436 * The default sizing is (24px, 24px).
438 * @param {string} iconSize Number indicating the width and height of the icons in the set. All icons
439 * in the icon set must be the same size. Default size is 24.
441 * @returns {obj} an `$mdIconProvider` reference; used to support method call chains for the API
445 * app.config(function($mdIconProvider) {
447 * // Configure URLs for icons specified by [set:]id.
450 * .defaultIconSize(36) // Register a default icon size (width == height)
458 defaultFontSet: 'material-icons',
462 function MdIconProvider() { }
464 MdIconProvider.prototype = {
466 icon : function icon(id, url, iconSize) {
467 if ( id.indexOf(':') == -1 ) id = '$default:' + id;
469 config[id] = new ConfigurationItem(url, iconSize );
472 iconSet : function iconSet(id, url, iconSize) {
473 config[id] = new ConfigurationItem(url, iconSize );
476 defaultIconSet : function defaultIconSet(url, iconSize) {
477 var setName = '$default';
479 if ( !config[setName] ) {
480 config[setName] = new ConfigurationItem(url, iconSize );
483 config[setName].iconSize = iconSize || config.defaultIconSize;
488 * Register an alias name associated with a font-icon library style ;
490 fontSet : function fontSet(alias, className) {
491 config.fontSets.push({
493 fontSet : className || alias
498 * Specify a default style name associated with a font-icon library
499 * fallback to Material Icons.
502 defaultFontSet : function defaultFontSet(className) {
503 config.defaultFontSet = !className ? '' : className;
507 defaultIconSize : function defaultIconSize(iconSize) {
508 config.defaultIconSize = iconSize;
512 preloadIcons: function ($templateCache) {
513 var iconProvider = this;
516 id : 'md-tabs-arrow',
517 url: 'md-tabs-arrow.svg',
518 svg: '<svg version="1.1" x="0px" y="0px" viewBox="0 0 24 24"><g><polygon points="15.4,7.4 14,6 8,12 14,18 15.4,16.6 10.8,12 "/></g></svg>'
523 svg: '<svg version="1.1" x="0px" y="0px" viewBox="0 0 24 24"><g><path d="M19 6.41l-1.41-1.41-5.59 5.59-5.59-5.59-1.41 1.41 5.59 5.59-5.59 5.59 1.41 1.41 5.59-5.59 5.59 5.59 1.41-1.41-5.59-5.59z"/></g></svg>'
527 url: 'md-cancel.svg',
528 svg: '<svg version="1.1" x="0px" y="0px" viewBox="0 0 24 24"><g><path d="M12 2c-5.53 0-10 4.47-10 10s4.47 10 10 10 10-4.47 10-10-4.47-10-10-10zm5 13.59l-1.41 1.41-3.59-3.59-3.59 3.59-1.41-1.41 3.59-3.59-3.59-3.59 1.41-1.41 3.59 3.59 3.59-3.59 1.41 1.41-3.59 3.59 3.59 3.59z"/></g></svg>'
533 svg: '<svg version="1.1" x="0px" y="0px" viewBox="0 0 100 100"><path d="M 50 0 L 100 14 L 92 80 L 50 100 L 8 80 L 0 14 Z" fill="#b2b2b2"></path><path d="M 50 5 L 6 18 L 13.5 77 L 50 94 Z" fill="#E42939"></path><path d="M 50 5 L 94 18 L 86.5 77 L 50 94 Z" fill="#B72833"></path><path d="M 50 7 L 83 75 L 72 75 L 65 59 L 50 59 L 50 50 L 61 50 L 50 26 Z" fill="#b2b2b2"></path><path d="M 50 7 L 17 75 L 28 75 L 35 59 L 50 59 L 50 50 L 39 50 L 50 26 Z" fill="#fff"></path></svg>'
536 id: 'md-toggle-arrow',
537 url: 'md-toggle-arrow-svg',
538 svg: '<svg version="1.1" x="0px" y="0px" viewBox="0 0 48 48"><path d="M24 16l-12 12 2.83 2.83 9.17-9.17 9.17 9.17 2.83-2.83z"/><path d="M0 0h48v48h-48z" fill="none"/></svg>'
542 svgRegistry.forEach(function(asset){
543 iconProvider.icon(asset.id, asset.url);
544 $templateCache.put(asset.url, asset.svg);
549 $get : ['$http', '$q', '$log', '$templateCache', function($http, $q, $log, $templateCache) {
550 this.preloadIcons($templateCache);
551 return MdIconService(config, $http, $q, $log, $templateCache);
556 * Configuration item stored in the Icon registry; used for lookups
557 * to load if not already cached in the `loaded` cache
559 function ConfigurationItem(url, iconSize) {
561 this.iconSize = iconSize || config.defaultIconSize;
567 * @module material.components.icon
570 * The `$mdIcon` service is a function used to lookup SVG icons.
572 * @param {string} id Query value for a unique Id or URL. If the argument is a URL, then the service will retrieve the icon element
573 * from its internal cache or load the icon and cache it first. If the value is not a URL-type string, then an ID lookup is
574 * performed. The Id may be a unique icon ID or may include an iconSet ID prefix.
576 * For the **id** query to work properly, this means that all id-to-URL mappings must have been previously configured
577 * using the `$mdIconProvider`.
579 * @returns {obj} Clone of the initial SVG DOM element; which was created from the SVG markup in the SVG data file.
583 * function SomeDirective($mdIcon) {
585 * // See if the icon has already been loaded, if not
586 * // then lookup the icon from the registry cache, load and cache
587 * // it for future requests.
588 * // NOTE: ID queries require configuration with $mdIconProvider
590 * $mdIcon('android').then(function(iconEl) { element.append(iconEl); });
591 * $mdIcon('work:chair').then(function(iconEl) { element.append(iconEl); });
593 * // Load and cache the external SVG using a URL
595 * $mdIcon('img/icons/android.svg').then(function(iconEl) {
596 * element.append(iconEl);
601 * NOTE: The `<md-icon /> ` directive internally uses the `$mdIcon` service to query, loaded, and instantiate
604 function MdIconService(config, $http, $q, $log, $templateCache) {
606 var urlRegex = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/i;
608 Icon.prototype = { clone : cloneSVG, prepare: prepareAndStyle };
609 getIcon.fontSet = findRegisteredFontSet;
611 // Publish service...
615 * Actual $mdIcon service is essentially a lookup function
617 function getIcon(id) {
620 // If already loaded and cached, use a clone of the cached icon.
621 // Otherwise either load by URL, or lookup in the registry and then load by URL, and cache.
623 if ( iconCache[id] ) return $q.when( iconCache[id].clone() );
624 if ( urlRegex.test(id) ) return loadByURL(id).then( cacheIcon(id) );
625 if ( id.indexOf(':') == -1 ) id = '$default:' + id;
628 .catch(loadFromIconSet)
629 .catch(announceIdNotFound)
630 .catch(announceNotFound)
631 .then( cacheIcon(id) );
635 * Lookup registered fontSet style using its alias...
638 function findRegisteredFontSet(alias) {
639 var useDefault = angular.isUndefined(alias) || !(alias && alias.length);
640 if ( useDefault ) return config.defaultFontSet;
643 angular.forEach(config.fontSets, function(it){
644 if ( it.alias == alias ) result = it.fontSet || result;
651 * Prepare and cache the loaded icon for the specified `id`
653 function cacheIcon( id ) {
655 return function updateCache( icon ) {
656 iconCache[id] = isIcon(icon) ? icon : new Icon(icon, config[id]);
658 return iconCache[id].clone();
663 * Lookup the configuration in the registry, if !registered throw an error
664 * otherwise load the icon [on-demand] using the registered URL.
667 function loadByID(id) {
668 var iconConfig = config[id];
670 return !iconConfig ? $q.reject(id) : loadByURL(iconConfig.url).then(function(icon) {
671 return new Icon(icon, iconConfig);
676 * Loads the file as XML and uses querySelector( <id> ) to find
677 * the desired node...
679 function loadFromIconSet(id) {
680 var setName = id.substring(0, id.lastIndexOf(':')) || '$default';
681 var iconSetConfig = config[setName];
683 return !iconSetConfig ? $q.reject(id) : loadByURL(iconSetConfig.url).then(extractFromSet);
685 function extractFromSet(set) {
686 var iconName = id.slice(id.lastIndexOf(':') + 1);
687 var icon = set.querySelector('#' + iconName);
688 return !icon ? $q.reject(id) : new Icon(icon, iconSetConfig);
693 * Load the icon by URL (may use the $templateCache).
694 * Extract the data for later conversion to Icon
696 function loadByURL(url) {
698 .get(url, { cache: $templateCache })
699 .then(function(response) {
700 return angular.element('<div>').append(response.data).find('svg')[0];
705 * User did not specify a URL and the ID has not been registered with the $mdIcon
708 function announceIdNotFound(id) {
711 if (angular.isString(id)) {
712 msg = 'icon ' + id + ' not found';
716 return $q.reject(msg || id);
720 * Catch HTTP or generic errors not related to incorrect icon IDs.
722 function announceNotFound(err) {
723 var msg = angular.isString(err) ? err : (err.message || err.data || err.statusText);
726 return $q.reject(msg);
730 * Check target signature to see if it is an Icon instance.
732 function isIcon(target) {
733 return angular.isDefined(target.element) && angular.isDefined(target.config);
737 * Define the Icon class
739 function Icon(el, config) {
740 if (el.tagName != 'svg') {
741 el = angular.element('<svg xmlns="http://www.w3.org/2000/svg">').append(el)[0];
744 // Inject the namespace if not available...
745 if ( !el.getAttribute('xmlns') ) {
746 el.setAttribute('xmlns', "http://www.w3.org/2000/svg");
750 this.config = config;
755 * Prepare the DOM element that will be cached in the
756 * loaded iconCache store.
758 function prepareAndStyle() {
759 var iconSize = this.config ? this.config.iconSize : config.defaultIconSize;
764 'preserveAspectRatio': 'xMidYMid meet',
765 'viewBox' : this.element.getAttribute('viewBox') || ('0 0 ' + iconSize + ' ' + iconSize)
766 }, function(val, attr) {
767 this.element.setAttribute(attr, val);
771 'pointer-events' : 'none',
773 }, function(val, style) {
774 this.element.style[style] = val;
779 * Clone the Icon DOM element.
782 return this.element.cloneNode(true);
787 ng.material.components.icon = angular.module("material.components.icon");