icon-registry-B2IMBfNA.mjs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. import { DOCUMENT } from '@angular/common';
  2. import * as i1 from '@angular/common/http';
  3. import { HttpClient } from '@angular/common/http';
  4. import * as i0 from '@angular/core';
  5. import { SecurityContext, Injectable, Optional, Inject, SkipSelf, ErrorHandler } from '@angular/core';
  6. import * as i2 from '@angular/platform-browser';
  7. import { DomSanitizer } from '@angular/platform-browser';
  8. import { of, throwError, forkJoin } from 'rxjs';
  9. import { tap, map, catchError, finalize, share } from 'rxjs/operators';
  10. /**
  11. * The Trusted Types policy, or null if Trusted Types are not
  12. * enabled/supported, or undefined if the policy has not been created yet.
  13. */
  14. let policy;
  15. /**
  16. * Returns the Trusted Types policy, or null if Trusted Types are not
  17. * enabled/supported. The first call to this function will create the policy.
  18. */
  19. function getPolicy() {
  20. if (policy === undefined) {
  21. policy = null;
  22. if (typeof window !== 'undefined') {
  23. const ttWindow = window;
  24. if (ttWindow.trustedTypes !== undefined) {
  25. policy = ttWindow.trustedTypes.createPolicy('angular#components', {
  26. createHTML: (s) => s,
  27. });
  28. }
  29. }
  30. }
  31. return policy;
  32. }
  33. /**
  34. * Unsafely promote a string to a TrustedHTML, falling back to strings when
  35. * Trusted Types are not available.
  36. * @security This is a security-sensitive function; any use of this function
  37. * must go through security review. In particular, it must be assured that the
  38. * provided string will never cause an XSS vulnerability if used in a context
  39. * that will be interpreted as HTML by a browser, e.g. when assigning to
  40. * element.innerHTML.
  41. */
  42. function trustedHTMLFromString(html) {
  43. return getPolicy()?.createHTML(html) || html;
  44. }
  45. /**
  46. * Returns an exception to be thrown in the case when attempting to
  47. * load an icon with a name that cannot be found.
  48. * @docs-private
  49. */
  50. function getMatIconNameNotFoundError(iconName) {
  51. return Error(`Unable to find icon with the name "${iconName}"`);
  52. }
  53. /**
  54. * Returns an exception to be thrown when the consumer attempts to use
  55. * `<mat-icon>` without including @angular/common/http.
  56. * @docs-private
  57. */
  58. function getMatIconNoHttpProviderError() {
  59. return Error('Could not find HttpClient for use with Angular Material icons. ' +
  60. 'Please add provideHttpClient() to your providers.');
  61. }
  62. /**
  63. * Returns an exception to be thrown when a URL couldn't be sanitized.
  64. * @param url URL that was attempted to be sanitized.
  65. * @docs-private
  66. */
  67. function getMatIconFailedToSanitizeUrlError(url) {
  68. return Error(`The URL provided to MatIconRegistry was not trusted as a resource URL ` +
  69. `via Angular's DomSanitizer. Attempted URL was "${url}".`);
  70. }
  71. /**
  72. * Returns an exception to be thrown when a HTML string couldn't be sanitized.
  73. * @param literal HTML that was attempted to be sanitized.
  74. * @docs-private
  75. */
  76. function getMatIconFailedToSanitizeLiteralError(literal) {
  77. return Error(`The literal provided to MatIconRegistry was not trusted as safe HTML by ` +
  78. `Angular's DomSanitizer. Attempted literal was "${literal}".`);
  79. }
  80. /**
  81. * Configuration for an icon, including the URL and possibly the cached SVG element.
  82. * @docs-private
  83. */
  84. class SvgIconConfig {
  85. url;
  86. svgText;
  87. options;
  88. svgElement;
  89. constructor(url, svgText, options) {
  90. this.url = url;
  91. this.svgText = svgText;
  92. this.options = options;
  93. }
  94. }
  95. /**
  96. * Service to register and display icons used by the `<mat-icon>` component.
  97. * - Registers icon URLs by namespace and name.
  98. * - Registers icon set URLs by namespace.
  99. * - Registers aliases for CSS classes, for use with icon fonts.
  100. * - Loads icons from URLs and extracts individual icons from icon sets.
  101. */
  102. class MatIconRegistry {
  103. _httpClient;
  104. _sanitizer;
  105. _errorHandler;
  106. _document;
  107. /**
  108. * URLs and cached SVG elements for individual icons. Keys are of the format "[namespace]:[icon]".
  109. */
  110. _svgIconConfigs = new Map();
  111. /**
  112. * SvgIconConfig objects and cached SVG elements for icon sets, keyed by namespace.
  113. * Multiple icon sets can be registered under the same namespace.
  114. */
  115. _iconSetConfigs = new Map();
  116. /** Cache for icons loaded by direct URLs. */
  117. _cachedIconsByUrl = new Map();
  118. /** In-progress icon fetches. Used to coalesce multiple requests to the same URL. */
  119. _inProgressUrlFetches = new Map();
  120. /** Map from font identifiers to their CSS class names. Used for icon fonts. */
  121. _fontCssClassesByAlias = new Map();
  122. /** Registered icon resolver functions. */
  123. _resolvers = [];
  124. /**
  125. * The CSS classes to apply when an `<mat-icon>` component has no icon name, url, or font
  126. * specified. The default 'material-icons' value assumes that the material icon font has been
  127. * loaded as described at https://google.github.io/material-design-icons/#icon-font-for-the-web
  128. */
  129. _defaultFontSetClass = ['material-icons', 'mat-ligature-font'];
  130. constructor(_httpClient, _sanitizer, document, _errorHandler) {
  131. this._httpClient = _httpClient;
  132. this._sanitizer = _sanitizer;
  133. this._errorHandler = _errorHandler;
  134. this._document = document;
  135. }
  136. /**
  137. * Registers an icon by URL in the default namespace.
  138. * @param iconName Name under which the icon should be registered.
  139. * @param url
  140. */
  141. addSvgIcon(iconName, url, options) {
  142. return this.addSvgIconInNamespace('', iconName, url, options);
  143. }
  144. /**
  145. * Registers an icon using an HTML string in the default namespace.
  146. * @param iconName Name under which the icon should be registered.
  147. * @param literal SVG source of the icon.
  148. */
  149. addSvgIconLiteral(iconName, literal, options) {
  150. return this.addSvgIconLiteralInNamespace('', iconName, literal, options);
  151. }
  152. /**
  153. * Registers an icon by URL in the specified namespace.
  154. * @param namespace Namespace in which the icon should be registered.
  155. * @param iconName Name under which the icon should be registered.
  156. * @param url
  157. */
  158. addSvgIconInNamespace(namespace, iconName, url, options) {
  159. return this._addSvgIconConfig(namespace, iconName, new SvgIconConfig(url, null, options));
  160. }
  161. /**
  162. * Registers an icon resolver function with the registry. The function will be invoked with the
  163. * name and namespace of an icon when the registry tries to resolve the URL from which to fetch
  164. * the icon. The resolver is expected to return a `SafeResourceUrl` that points to the icon,
  165. * an object with the icon URL and icon options, or `null` if the icon is not supported. Resolvers
  166. * will be invoked in the order in which they have been registered.
  167. * @param resolver Resolver function to be registered.
  168. */
  169. addSvgIconResolver(resolver) {
  170. this._resolvers.push(resolver);
  171. return this;
  172. }
  173. /**
  174. * Registers an icon using an HTML string in the specified namespace.
  175. * @param namespace Namespace in which the icon should be registered.
  176. * @param iconName Name under which the icon should be registered.
  177. * @param literal SVG source of the icon.
  178. */
  179. addSvgIconLiteralInNamespace(namespace, iconName, literal, options) {
  180. const cleanLiteral = this._sanitizer.sanitize(SecurityContext.HTML, literal);
  181. // TODO: add an ngDevMode check
  182. if (!cleanLiteral) {
  183. throw getMatIconFailedToSanitizeLiteralError(literal);
  184. }
  185. // Security: The literal is passed in as SafeHtml, and is thus trusted.
  186. const trustedLiteral = trustedHTMLFromString(cleanLiteral);
  187. return this._addSvgIconConfig(namespace, iconName, new SvgIconConfig('', trustedLiteral, options));
  188. }
  189. /**
  190. * Registers an icon set by URL in the default namespace.
  191. * @param url
  192. */
  193. addSvgIconSet(url, options) {
  194. return this.addSvgIconSetInNamespace('', url, options);
  195. }
  196. /**
  197. * Registers an icon set using an HTML string in the default namespace.
  198. * @param literal SVG source of the icon set.
  199. */
  200. addSvgIconSetLiteral(literal, options) {
  201. return this.addSvgIconSetLiteralInNamespace('', literal, options);
  202. }
  203. /**
  204. * Registers an icon set by URL in the specified namespace.
  205. * @param namespace Namespace in which to register the icon set.
  206. * @param url
  207. */
  208. addSvgIconSetInNamespace(namespace, url, options) {
  209. return this._addSvgIconSetConfig(namespace, new SvgIconConfig(url, null, options));
  210. }
  211. /**
  212. * Registers an icon set using an HTML string in the specified namespace.
  213. * @param namespace Namespace in which to register the icon set.
  214. * @param literal SVG source of the icon set.
  215. */
  216. addSvgIconSetLiteralInNamespace(namespace, literal, options) {
  217. const cleanLiteral = this._sanitizer.sanitize(SecurityContext.HTML, literal);
  218. if (!cleanLiteral) {
  219. throw getMatIconFailedToSanitizeLiteralError(literal);
  220. }
  221. // Security: The literal is passed in as SafeHtml, and is thus trusted.
  222. const trustedLiteral = trustedHTMLFromString(cleanLiteral);
  223. return this._addSvgIconSetConfig(namespace, new SvgIconConfig('', trustedLiteral, options));
  224. }
  225. /**
  226. * Defines an alias for CSS class names to be used for icon fonts. Creating an matIcon
  227. * component with the alias as the fontSet input will cause the class name to be applied
  228. * to the `<mat-icon>` element.
  229. *
  230. * If the registered font is a ligature font, then don't forget to also include the special
  231. * class `mat-ligature-font` to allow the usage via attribute. So register like this:
  232. *
  233. * ```ts
  234. * iconRegistry.registerFontClassAlias('f1', 'font1 mat-ligature-font');
  235. * ```
  236. *
  237. * And use like this:
  238. *
  239. * ```html
  240. * <mat-icon fontSet="f1" fontIcon="home"></mat-icon>
  241. * ```
  242. *
  243. * @param alias Alias for the font.
  244. * @param classNames Class names override to be used instead of the alias.
  245. */
  246. registerFontClassAlias(alias, classNames = alias) {
  247. this._fontCssClassesByAlias.set(alias, classNames);
  248. return this;
  249. }
  250. /**
  251. * Returns the CSS class name associated with the alias by a previous call to
  252. * registerFontClassAlias. If no CSS class has been associated, returns the alias unmodified.
  253. */
  254. classNameForFontAlias(alias) {
  255. return this._fontCssClassesByAlias.get(alias) || alias;
  256. }
  257. /**
  258. * Sets the CSS classes to be used for icon fonts when an `<mat-icon>` component does not
  259. * have a fontSet input value, and is not loading an icon by name or URL.
  260. */
  261. setDefaultFontSetClass(...classNames) {
  262. this._defaultFontSetClass = classNames;
  263. return this;
  264. }
  265. /**
  266. * Returns the CSS classes to be used for icon fonts when an `<mat-icon>` component does not
  267. * have a fontSet input value, and is not loading an icon by name or URL.
  268. */
  269. getDefaultFontSetClass() {
  270. return this._defaultFontSetClass;
  271. }
  272. /**
  273. * Returns an Observable that produces the icon (as an `<svg>` DOM element) from the given URL.
  274. * The response from the URL may be cached so this will not always cause an HTTP request, but
  275. * the produced element will always be a new copy of the originally fetched icon. (That is,
  276. * it will not contain any modifications made to elements previously returned).
  277. *
  278. * @param safeUrl URL from which to fetch the SVG icon.
  279. */
  280. getSvgIconFromUrl(safeUrl) {
  281. const url = this._sanitizer.sanitize(SecurityContext.RESOURCE_URL, safeUrl);
  282. if (!url) {
  283. throw getMatIconFailedToSanitizeUrlError(safeUrl);
  284. }
  285. const cachedIcon = this._cachedIconsByUrl.get(url);
  286. if (cachedIcon) {
  287. return of(cloneSvg(cachedIcon));
  288. }
  289. return this._loadSvgIconFromConfig(new SvgIconConfig(safeUrl, null)).pipe(tap(svg => this._cachedIconsByUrl.set(url, svg)), map(svg => cloneSvg(svg)));
  290. }
  291. /**
  292. * Returns an Observable that produces the icon (as an `<svg>` DOM element) with the given name
  293. * and namespace. The icon must have been previously registered with addIcon or addIconSet;
  294. * if not, the Observable will throw an error.
  295. *
  296. * @param name Name of the icon to be retrieved.
  297. * @param namespace Namespace in which to look for the icon.
  298. */
  299. getNamedSvgIcon(name, namespace = '') {
  300. const key = iconKey(namespace, name);
  301. let config = this._svgIconConfigs.get(key);
  302. // Return (copy of) cached icon if possible.
  303. if (config) {
  304. return this._getSvgFromConfig(config);
  305. }
  306. // Otherwise try to resolve the config from one of the resolver functions.
  307. config = this._getIconConfigFromResolvers(namespace, name);
  308. if (config) {
  309. this._svgIconConfigs.set(key, config);
  310. return this._getSvgFromConfig(config);
  311. }
  312. // See if we have any icon sets registered for the namespace.
  313. const iconSetConfigs = this._iconSetConfigs.get(namespace);
  314. if (iconSetConfigs) {
  315. return this._getSvgFromIconSetConfigs(name, iconSetConfigs);
  316. }
  317. return throwError(getMatIconNameNotFoundError(key));
  318. }
  319. ngOnDestroy() {
  320. this._resolvers = [];
  321. this._svgIconConfigs.clear();
  322. this._iconSetConfigs.clear();
  323. this._cachedIconsByUrl.clear();
  324. }
  325. /**
  326. * Returns the cached icon for a SvgIconConfig if available, or fetches it from its URL if not.
  327. */
  328. _getSvgFromConfig(config) {
  329. if (config.svgText) {
  330. // We already have the SVG element for this icon, return a copy.
  331. return of(cloneSvg(this._svgElementFromConfig(config)));
  332. }
  333. else {
  334. // Fetch the icon from the config's URL, cache it, and return a copy.
  335. return this._loadSvgIconFromConfig(config).pipe(map(svg => cloneSvg(svg)));
  336. }
  337. }
  338. /**
  339. * Attempts to find an icon with the specified name in any of the SVG icon sets.
  340. * First searches the available cached icons for a nested element with a matching name, and
  341. * if found copies the element to a new `<svg>` element. If not found, fetches all icon sets
  342. * that have not been cached, and searches again after all fetches are completed.
  343. * The returned Observable produces the SVG element if possible, and throws
  344. * an error if no icon with the specified name can be found.
  345. */
  346. _getSvgFromIconSetConfigs(name, iconSetConfigs) {
  347. // For all the icon set SVG elements we've fetched, see if any contain an icon with the
  348. // requested name.
  349. const namedIcon = this._extractIconWithNameFromAnySet(name, iconSetConfigs);
  350. if (namedIcon) {
  351. // We could cache namedIcon in _svgIconConfigs, but since we have to make a copy every
  352. // time anyway, there's probably not much advantage compared to just always extracting
  353. // it from the icon set.
  354. return of(namedIcon);
  355. }
  356. // Not found in any cached icon sets. If there are icon sets with URLs that we haven't
  357. // fetched, fetch them now and look for iconName in the results.
  358. const iconSetFetchRequests = iconSetConfigs
  359. .filter(iconSetConfig => !iconSetConfig.svgText)
  360. .map(iconSetConfig => {
  361. return this._loadSvgIconSetFromConfig(iconSetConfig).pipe(catchError((err) => {
  362. const url = this._sanitizer.sanitize(SecurityContext.RESOURCE_URL, iconSetConfig.url);
  363. // Swallow errors fetching individual URLs so the
  364. // combined Observable won't necessarily fail.
  365. const errorMessage = `Loading icon set URL: ${url} failed: ${err.message}`;
  366. this._errorHandler.handleError(new Error(errorMessage));
  367. return of(null);
  368. }));
  369. });
  370. // Fetch all the icon set URLs. When the requests complete, every IconSet should have a
  371. // cached SVG element (unless the request failed), and we can check again for the icon.
  372. return forkJoin(iconSetFetchRequests).pipe(map(() => {
  373. const foundIcon = this._extractIconWithNameFromAnySet(name, iconSetConfigs);
  374. // TODO: add an ngDevMode check
  375. if (!foundIcon) {
  376. throw getMatIconNameNotFoundError(name);
  377. }
  378. return foundIcon;
  379. }));
  380. }
  381. /**
  382. * Searches the cached SVG elements for the given icon sets for a nested icon element whose "id"
  383. * tag matches the specified name. If found, copies the nested element to a new SVG element and
  384. * returns it. Returns null if no matching element is found.
  385. */
  386. _extractIconWithNameFromAnySet(iconName, iconSetConfigs) {
  387. // Iterate backwards, so icon sets added later have precedence.
  388. for (let i = iconSetConfigs.length - 1; i >= 0; i--) {
  389. const config = iconSetConfigs[i];
  390. // Parsing the icon set's text into an SVG element can be expensive. We can avoid some of
  391. // the parsing by doing a quick check using `indexOf` to see if there's any chance for the
  392. // icon to be in the set. This won't be 100% accurate, but it should help us avoid at least
  393. // some of the parsing.
  394. if (config.svgText && config.svgText.toString().indexOf(iconName) > -1) {
  395. const svg = this._svgElementFromConfig(config);
  396. const foundIcon = this._extractSvgIconFromSet(svg, iconName, config.options);
  397. if (foundIcon) {
  398. return foundIcon;
  399. }
  400. }
  401. }
  402. return null;
  403. }
  404. /**
  405. * Loads the content of the icon URL specified in the SvgIconConfig and creates an SVG element
  406. * from it.
  407. */
  408. _loadSvgIconFromConfig(config) {
  409. return this._fetchIcon(config).pipe(tap(svgText => (config.svgText = svgText)), map(() => this._svgElementFromConfig(config)));
  410. }
  411. /**
  412. * Loads the content of the icon set URL specified in the
  413. * SvgIconConfig and attaches it to the config.
  414. */
  415. _loadSvgIconSetFromConfig(config) {
  416. if (config.svgText) {
  417. return of(null);
  418. }
  419. return this._fetchIcon(config).pipe(tap(svgText => (config.svgText = svgText)));
  420. }
  421. /**
  422. * Searches the cached element of the given SvgIconConfig for a nested icon element whose "id"
  423. * tag matches the specified name. If found, copies the nested element to a new SVG element and
  424. * returns it. Returns null if no matching element is found.
  425. */
  426. _extractSvgIconFromSet(iconSet, iconName, options) {
  427. // Use the `id="iconName"` syntax in order to escape special
  428. // characters in the ID (versus using the #iconName syntax).
  429. const iconSource = iconSet.querySelector(`[id="${iconName}"]`);
  430. if (!iconSource) {
  431. return null;
  432. }
  433. // Clone the element and remove the ID to prevent multiple elements from being added
  434. // to the page with the same ID.
  435. const iconElement = iconSource.cloneNode(true);
  436. iconElement.removeAttribute('id');
  437. // If the icon node is itself an <svg> node, clone and return it directly. If not, set it as
  438. // the content of a new <svg> node.
  439. if (iconElement.nodeName.toLowerCase() === 'svg') {
  440. return this._setSvgAttributes(iconElement, options);
  441. }
  442. // If the node is a <symbol>, it won't be rendered so we have to convert it into <svg>. Note
  443. // that the same could be achieved by referring to it via <use href="#id">, however the <use>
  444. // tag is problematic on Firefox, because it needs to include the current page path.
  445. if (iconElement.nodeName.toLowerCase() === 'symbol') {
  446. return this._setSvgAttributes(this._toSvgElement(iconElement), options);
  447. }
  448. // createElement('SVG') doesn't work as expected; the DOM ends up with
  449. // the correct nodes, but the SVG content doesn't render. Instead we
  450. // have to create an empty SVG node using innerHTML and append its content.
  451. // Elements created using DOMParser.parseFromString have the same problem.
  452. // http://stackoverflow.com/questions/23003278/svg-innerhtml-in-firefox-can-not-display
  453. const svg = this._svgElementFromString(trustedHTMLFromString('<svg></svg>'));
  454. // Clone the node so we don't remove it from the parent icon set element.
  455. svg.appendChild(iconElement);
  456. return this._setSvgAttributes(svg, options);
  457. }
  458. /**
  459. * Creates a DOM element from the given SVG string.
  460. */
  461. _svgElementFromString(str) {
  462. const div = this._document.createElement('DIV');
  463. div.innerHTML = str;
  464. const svg = div.querySelector('svg');
  465. // TODO: add an ngDevMode check
  466. if (!svg) {
  467. throw Error('<svg> tag not found');
  468. }
  469. return svg;
  470. }
  471. /**
  472. * Converts an element into an SVG node by cloning all of its children.
  473. */
  474. _toSvgElement(element) {
  475. const svg = this._svgElementFromString(trustedHTMLFromString('<svg></svg>'));
  476. const attributes = element.attributes;
  477. // Copy over all the attributes from the `symbol` to the new SVG, except the id.
  478. for (let i = 0; i < attributes.length; i++) {
  479. const { name, value } = attributes[i];
  480. if (name !== 'id') {
  481. svg.setAttribute(name, value);
  482. }
  483. }
  484. for (let i = 0; i < element.childNodes.length; i++) {
  485. if (element.childNodes[i].nodeType === this._document.ELEMENT_NODE) {
  486. svg.appendChild(element.childNodes[i].cloneNode(true));
  487. }
  488. }
  489. return svg;
  490. }
  491. /**
  492. * Sets the default attributes for an SVG element to be used as an icon.
  493. */
  494. _setSvgAttributes(svg, options) {
  495. svg.setAttribute('fit', '');
  496. svg.setAttribute('height', '100%');
  497. svg.setAttribute('width', '100%');
  498. svg.setAttribute('preserveAspectRatio', 'xMidYMid meet');
  499. svg.setAttribute('focusable', 'false'); // Disable IE11 default behavior to make SVGs focusable.
  500. if (options && options.viewBox) {
  501. svg.setAttribute('viewBox', options.viewBox);
  502. }
  503. return svg;
  504. }
  505. /**
  506. * Returns an Observable which produces the string contents of the given icon. Results may be
  507. * cached, so future calls with the same URL may not cause another HTTP request.
  508. */
  509. _fetchIcon(iconConfig) {
  510. const { url: safeUrl, options } = iconConfig;
  511. const withCredentials = options?.withCredentials ?? false;
  512. if (!this._httpClient) {
  513. throw getMatIconNoHttpProviderError();
  514. }
  515. // TODO: add an ngDevMode check
  516. if (safeUrl == null) {
  517. throw Error(`Cannot fetch icon from URL "${safeUrl}".`);
  518. }
  519. const url = this._sanitizer.sanitize(SecurityContext.RESOURCE_URL, safeUrl);
  520. // TODO: add an ngDevMode check
  521. if (!url) {
  522. throw getMatIconFailedToSanitizeUrlError(safeUrl);
  523. }
  524. // Store in-progress fetches to avoid sending a duplicate request for a URL when there is
  525. // already a request in progress for that URL. It's necessary to call share() on the
  526. // Observable returned by http.get() so that multiple subscribers don't cause multiple XHRs.
  527. const inProgressFetch = this._inProgressUrlFetches.get(url);
  528. if (inProgressFetch) {
  529. return inProgressFetch;
  530. }
  531. const req = this._httpClient.get(url, { responseType: 'text', withCredentials }).pipe(map(svg => {
  532. // Security: This SVG is fetched from a SafeResourceUrl, and is thus
  533. // trusted HTML.
  534. return trustedHTMLFromString(svg);
  535. }), finalize(() => this._inProgressUrlFetches.delete(url)), share());
  536. this._inProgressUrlFetches.set(url, req);
  537. return req;
  538. }
  539. /**
  540. * Registers an icon config by name in the specified namespace.
  541. * @param namespace Namespace in which to register the icon config.
  542. * @param iconName Name under which to register the config.
  543. * @param config Config to be registered.
  544. */
  545. _addSvgIconConfig(namespace, iconName, config) {
  546. this._svgIconConfigs.set(iconKey(namespace, iconName), config);
  547. return this;
  548. }
  549. /**
  550. * Registers an icon set config in the specified namespace.
  551. * @param namespace Namespace in which to register the icon config.
  552. * @param config Config to be registered.
  553. */
  554. _addSvgIconSetConfig(namespace, config) {
  555. const configNamespace = this._iconSetConfigs.get(namespace);
  556. if (configNamespace) {
  557. configNamespace.push(config);
  558. }
  559. else {
  560. this._iconSetConfigs.set(namespace, [config]);
  561. }
  562. return this;
  563. }
  564. /** Parses a config's text into an SVG element. */
  565. _svgElementFromConfig(config) {
  566. if (!config.svgElement) {
  567. const svg = this._svgElementFromString(config.svgText);
  568. this._setSvgAttributes(svg, config.options);
  569. config.svgElement = svg;
  570. }
  571. return config.svgElement;
  572. }
  573. /** Tries to create an icon config through the registered resolver functions. */
  574. _getIconConfigFromResolvers(namespace, name) {
  575. for (let i = 0; i < this._resolvers.length; i++) {
  576. const result = this._resolvers[i](name, namespace);
  577. if (result) {
  578. return isSafeUrlWithOptions(result)
  579. ? new SvgIconConfig(result.url, null, result.options)
  580. : new SvgIconConfig(result, null);
  581. }
  582. }
  583. return undefined;
  584. }
  585. static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.6", ngImport: i0, type: MatIconRegistry, deps: [{ token: i1.HttpClient, optional: true }, { token: i2.DomSanitizer }, { token: DOCUMENT, optional: true }, { token: i0.ErrorHandler }], target: i0.ɵɵFactoryTarget.Injectable });
  586. static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.6", ngImport: i0, type: MatIconRegistry, providedIn: 'root' });
  587. }
  588. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.6", ngImport: i0, type: MatIconRegistry, decorators: [{
  589. type: Injectable,
  590. args: [{ providedIn: 'root' }]
  591. }], ctorParameters: () => [{ type: i1.HttpClient, decorators: [{
  592. type: Optional
  593. }] }, { type: i2.DomSanitizer }, { type: undefined, decorators: [{
  594. type: Optional
  595. }, {
  596. type: Inject,
  597. args: [DOCUMENT]
  598. }] }, { type: i0.ErrorHandler }] });
  599. /**
  600. * @docs-private
  601. * @deprecated No longer used, will be removed.
  602. * @breaking-change 21.0.0
  603. */
  604. function ICON_REGISTRY_PROVIDER_FACTORY(parentRegistry, httpClient, sanitizer, errorHandler, document) {
  605. return parentRegistry || new MatIconRegistry(httpClient, sanitizer, document, errorHandler);
  606. }
  607. /**
  608. * @docs-private
  609. * @deprecated No longer used, will be removed.
  610. * @breaking-change 21.0.0
  611. */
  612. const ICON_REGISTRY_PROVIDER = {
  613. // If there is already an MatIconRegistry available, use that. Otherwise, provide a new one.
  614. provide: MatIconRegistry,
  615. deps: [
  616. [new Optional(), new SkipSelf(), MatIconRegistry],
  617. [new Optional(), HttpClient],
  618. DomSanitizer,
  619. ErrorHandler,
  620. [new Optional(), DOCUMENT],
  621. ],
  622. useFactory: ICON_REGISTRY_PROVIDER_FACTORY,
  623. };
  624. /** Clones an SVGElement while preserving type information. */
  625. function cloneSvg(svg) {
  626. return svg.cloneNode(true);
  627. }
  628. /** Returns the cache key to use for an icon namespace and name. */
  629. function iconKey(namespace, name) {
  630. return namespace + ':' + name;
  631. }
  632. function isSafeUrlWithOptions(value) {
  633. return !!(value.url && value.options);
  634. }
  635. export { ICON_REGISTRY_PROVIDER_FACTORY as I, MatIconRegistry as M, getMatIconNoHttpProviderError as a, getMatIconFailedToSanitizeUrlError as b, getMatIconFailedToSanitizeLiteralError as c, ICON_REGISTRY_PROVIDER as d, getMatIconNameNotFoundError as g };
  636. //# sourceMappingURL=icon-registry-B2IMBfNA.mjs.map