icon.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. /*!
  2. * (C) Ionic http://ionicframework.com - MIT License
  3. */
  4. import { getAssetPath, proxyCustomElement, HTMLElement, Build, h, Host } from '@stencil/core/internal/client';
  5. let CACHED_MAP;
  6. const getIconMap = () => {
  7. if (typeof window === 'undefined') {
  8. return new Map();
  9. }
  10. else {
  11. if (!CACHED_MAP) {
  12. const win = window;
  13. win.Ionicons = win.Ionicons || {};
  14. CACHED_MAP = win.Ionicons.map = win.Ionicons.map || new Map();
  15. }
  16. return CACHED_MAP;
  17. }
  18. };
  19. const getUrl = (i) => {
  20. let url = getSrc(i.src);
  21. if (url) {
  22. return url;
  23. }
  24. url = getName(i.name, i.icon, i.mode, i.ios, i.md);
  25. if (url) {
  26. return getNamedUrl(url, i);
  27. }
  28. if (i.icon) {
  29. url = getSrc(i.icon);
  30. if (url) {
  31. return url;
  32. }
  33. url = getSrc(i.icon[i.mode]);
  34. if (url) {
  35. return url;
  36. }
  37. }
  38. return null;
  39. };
  40. const getNamedUrl = (iconName, iconEl) => {
  41. const url = getIconMap().get(iconName);
  42. if (url) {
  43. return url;
  44. }
  45. try {
  46. return getAssetPath(`svg/${iconName}.svg`);
  47. }
  48. catch (e) {
  49. /**
  50. * In the custom elements build version of ionicons, referencing an icon
  51. * by name will throw an invalid URL error because the asset path is not defined.
  52. * This catches that error and logs something that is more developer-friendly.
  53. * We also include a reference to the ion-icon element so developers can
  54. * figure out which instance of ion-icon needs to be updated.
  55. */
  56. console.warn(`[Ionicons Warning]: Could not load icon with name "${iconName}". Ensure that the icon is registered using addIcons or that the icon SVG data is passed directly to the icon component.`, iconEl);
  57. }
  58. };
  59. const getName = (iconName, icon, mode, ios, md) => {
  60. // default to "md" if somehow the mode wasn't set
  61. mode = (mode && toLower(mode)) === 'ios' ? 'ios' : 'md';
  62. // if an icon was passed in using the ios or md attributes
  63. // set the iconName to whatever was passed in
  64. if (ios && mode === 'ios') {
  65. iconName = toLower(ios);
  66. }
  67. else if (md && mode === 'md') {
  68. iconName = toLower(md);
  69. }
  70. else {
  71. if (!iconName && icon && !isSrc(icon)) {
  72. iconName = icon;
  73. }
  74. if (isStr(iconName)) {
  75. iconName = toLower(iconName);
  76. }
  77. }
  78. if (!isStr(iconName) || iconName.trim() === '') {
  79. return null;
  80. }
  81. // only allow alpha characters and dash
  82. const invalidChars = iconName.replace(/[a-z]|-|\d/gi, '');
  83. if (invalidChars !== '') {
  84. return null;
  85. }
  86. return iconName;
  87. };
  88. const getSrc = (src) => {
  89. if (isStr(src)) {
  90. src = src.trim();
  91. if (isSrc(src)) {
  92. return src;
  93. }
  94. }
  95. return null;
  96. };
  97. const isSrc = (str) => str.length > 0 && /(\/|\.)/.test(str);
  98. const isStr = (val) => typeof val === 'string';
  99. const toLower = (val) => val.toLowerCase();
  100. /**
  101. * Elements inside of web components sometimes need to inherit global attributes
  102. * set on the host. For example, the inner input in `ion-input` should inherit
  103. * the `title` attribute that developers set directly on `ion-input`. This
  104. * helper function should be called in componentWillLoad and assigned to a variable
  105. * that is later used in the render function.
  106. *
  107. * This does not need to be reactive as changing attributes on the host element
  108. * does not trigger a re-render.
  109. */
  110. const inheritAttributes = (el, attributes = []) => {
  111. const attributeObject = {};
  112. attributes.forEach(attr => {
  113. if (el.hasAttribute(attr)) {
  114. const value = el.getAttribute(attr);
  115. if (value !== null) {
  116. attributeObject[attr] = el.getAttribute(attr);
  117. }
  118. el.removeAttribute(attr);
  119. }
  120. });
  121. return attributeObject;
  122. };
  123. /**
  124. * Returns `true` if the document or host element
  125. * has a `dir` set to `rtl`. The host value will always
  126. * take priority over the root document value.
  127. */
  128. const isRTL = (hostEl) => {
  129. if (hostEl) {
  130. if (hostEl.dir !== '') {
  131. return hostEl.dir.toLowerCase() === 'rtl';
  132. }
  133. }
  134. return (document === null || document === void 0 ? void 0 : document.dir.toLowerCase()) === 'rtl';
  135. };
  136. const validateContent = (svgContent) => {
  137. const div = document.createElement('div');
  138. div.innerHTML = svgContent;
  139. // setup this way to ensure it works on our buddy IE
  140. for (let i = div.childNodes.length - 1; i >= 0; i--) {
  141. if (div.childNodes[i].nodeName.toLowerCase() !== 'svg') {
  142. div.removeChild(div.childNodes[i]);
  143. }
  144. }
  145. // must only have 1 root element
  146. const svgElm = div.firstElementChild;
  147. if (svgElm && svgElm.nodeName.toLowerCase() === 'svg') {
  148. const svgClass = svgElm.getAttribute('class') || '';
  149. svgElm.setAttribute('class', (svgClass + ' s-ion-icon').trim());
  150. // root element must be an svg
  151. // lets double check we've got valid elements
  152. // do not allow scripts
  153. if (isValid(svgElm)) {
  154. return div.innerHTML;
  155. }
  156. }
  157. return '';
  158. };
  159. const isValid = (elm) => {
  160. if (elm.nodeType === 1) {
  161. if (elm.nodeName.toLowerCase() === 'script') {
  162. return false;
  163. }
  164. for (let i = 0; i < elm.attributes.length; i++) {
  165. const name = elm.attributes[i].name;
  166. if (isStr(name) && name.toLowerCase().indexOf('on') === 0) {
  167. return false;
  168. }
  169. }
  170. for (let i = 0; i < elm.childNodes.length; i++) {
  171. if (!isValid(elm.childNodes[i])) {
  172. return false;
  173. }
  174. }
  175. }
  176. return true;
  177. };
  178. const isSvgDataUrl = (url) => url.startsWith('data:image/svg+xml');
  179. const isEncodedDataUrl = (url) => url.indexOf(';utf8,') !== -1;
  180. const ioniconContent = new Map();
  181. const requests = new Map();
  182. let parser;
  183. const getSvgContent = (url, sanitize) => {
  184. // see if we already have a request for this url
  185. let req = requests.get(url);
  186. if (!req) {
  187. if (typeof fetch !== 'undefined' && typeof document !== 'undefined') {
  188. /**
  189. * If the url is a data url of an svg, then try to parse it
  190. * with the DOMParser. This works with content security policies enabled.
  191. */
  192. if (isSvgDataUrl(url) && isEncodedDataUrl(url)) {
  193. if (!parser) {
  194. /**
  195. * Create an instance of the DOM parser. This creates a single
  196. * parser instance for the entire app, which is more efficient.
  197. */
  198. parser = new DOMParser();
  199. }
  200. const doc = parser.parseFromString(url, 'text/html');
  201. const svg = doc.querySelector('svg');
  202. if (svg) {
  203. ioniconContent.set(url, svg.outerHTML);
  204. }
  205. return Promise.resolve();
  206. }
  207. else {
  208. // we don't already have a request
  209. req = fetch(url).then((rsp) => {
  210. if (rsp.ok) {
  211. return rsp.text().then((svgContent) => {
  212. if (svgContent && sanitize !== false) {
  213. svgContent = validateContent(svgContent);
  214. }
  215. ioniconContent.set(url, svgContent || '');
  216. });
  217. }
  218. ioniconContent.set(url, '');
  219. });
  220. // cache for the same requests
  221. requests.set(url, req);
  222. }
  223. }
  224. else {
  225. // set to empty for ssr scenarios and resolve promise
  226. ioniconContent.set(url, '');
  227. return Promise.resolve();
  228. }
  229. }
  230. return req;
  231. };
  232. const iconCss = ":host{display:inline-block;width:1em;height:1em;contain:strict;fill:currentColor;-webkit-box-sizing:content-box !important;box-sizing:content-box !important}:host .ionicon{stroke:currentColor}.ionicon-fill-none{fill:none}.ionicon-stroke-width{stroke-width:32px;stroke-width:var(--ionicon-stroke-width, 32px)}.icon-inner,.ionicon,svg{display:block;height:100%;width:100%}@supports (background: -webkit-named-image(i)){:host(.icon-rtl) .icon-inner{-webkit-transform:scaleX(-1);transform:scaleX(-1)}}@supports not selector(:dir(rtl)) and selector(:host-context([dir='rtl'])){:host(.icon-rtl) .icon-inner{-webkit-transform:scaleX(-1);transform:scaleX(-1)}}:host(.flip-rtl):host-context([dir='rtl']) .icon-inner{-webkit-transform:scaleX(-1);transform:scaleX(-1)}@supports selector(:dir(rtl)){:host(.flip-rtl:dir(rtl)) .icon-inner{-webkit-transform:scaleX(-1);transform:scaleX(-1)}:host(.flip-rtl:dir(ltr)) .icon-inner{-webkit-transform:scaleX(1);transform:scaleX(1)}}:host(.icon-small){font-size:1.125rem !important}:host(.icon-large){font-size:2rem !important}:host(.ion-color){color:var(--ion-color-base) !important}:host(.ion-color-primary){--ion-color-base:var(--ion-color-primary, #3880ff)}:host(.ion-color-secondary){--ion-color-base:var(--ion-color-secondary, #0cd1e8)}:host(.ion-color-tertiary){--ion-color-base:var(--ion-color-tertiary, #f4a942)}:host(.ion-color-success){--ion-color-base:var(--ion-color-success, #10dc60)}:host(.ion-color-warning){--ion-color-base:var(--ion-color-warning, #ffce00)}:host(.ion-color-danger){--ion-color-base:var(--ion-color-danger, #f14141)}:host(.ion-color-light){--ion-color-base:var(--ion-color-light, #f4f5f8)}:host(.ion-color-medium){--ion-color-base:var(--ion-color-medium, #989aa2)}:host(.ion-color-dark){--ion-color-base:var(--ion-color-dark, #222428)}";
  233. const IonIconStyle0 = iconCss;
  234. const Icon = /*@__PURE__*/ proxyCustomElement(class Icon extends HTMLElement {
  235. constructor() {
  236. super();
  237. this.__registerHost();
  238. this.__attachShadow();
  239. this.iconName = null;
  240. this.inheritedAttributes = {};
  241. this.didLoadIcon = false;
  242. this.svgContent = undefined;
  243. this.isVisible = false;
  244. this.mode = getIonMode();
  245. this.color = undefined;
  246. this.ios = undefined;
  247. this.md = undefined;
  248. this.flipRtl = undefined;
  249. this.name = undefined;
  250. this.src = undefined;
  251. this.icon = undefined;
  252. this.size = undefined;
  253. this.lazy = false;
  254. this.sanitize = true;
  255. }
  256. componentWillLoad() {
  257. this.inheritedAttributes = inheritAttributes(this.el, ['aria-label']);
  258. }
  259. connectedCallback() {
  260. // purposely do not return the promise here because loading
  261. // the svg file should not hold up loading the app
  262. // only load the svg if it's visible
  263. this.waitUntilVisible(this.el, '50px', () => {
  264. this.isVisible = true;
  265. this.loadIcon();
  266. });
  267. }
  268. componentDidLoad() {
  269. /**
  270. * Addresses an Angular issue where property values are assigned after the 'connectedCallback' but prior to the registration of watchers.
  271. * This enhancement ensures the loading of an icon when the component has finished rendering and the icon has yet to apply the SVG data.
  272. * This modification pertains to the usage of Angular's binding syntax:
  273. * `<ion-icon [name]="myIconName"></ion-icon>`
  274. */
  275. if (!this.didLoadIcon) {
  276. this.loadIcon();
  277. }
  278. }
  279. disconnectedCallback() {
  280. if (this.io) {
  281. this.io.disconnect();
  282. this.io = undefined;
  283. }
  284. }
  285. waitUntilVisible(el, rootMargin, cb) {
  286. if (Build.isBrowser && this.lazy && typeof window !== 'undefined' && window.IntersectionObserver) {
  287. const io = (this.io = new window.IntersectionObserver((data) => {
  288. if (data[0].isIntersecting) {
  289. io.disconnect();
  290. this.io = undefined;
  291. cb();
  292. }
  293. }, { rootMargin }));
  294. io.observe(el);
  295. }
  296. else {
  297. // browser doesn't support IntersectionObserver
  298. // so just fallback to always show it
  299. cb();
  300. }
  301. }
  302. loadIcon() {
  303. if (Build.isBrowser && this.isVisible) {
  304. const url = getUrl(this);
  305. if (url) {
  306. if (ioniconContent.has(url)) {
  307. // sync if it's already loaded
  308. this.svgContent = ioniconContent.get(url);
  309. }
  310. else {
  311. // async if it hasn't been loaded
  312. getSvgContent(url, this.sanitize).then(() => (this.svgContent = ioniconContent.get(url)));
  313. }
  314. this.didLoadIcon = true;
  315. }
  316. }
  317. this.iconName = getName(this.name, this.icon, this.mode, this.ios, this.md);
  318. }
  319. render() {
  320. const { flipRtl, iconName, inheritedAttributes, el } = this;
  321. const mode = this.mode || 'md';
  322. // we have designated that arrows & chevrons should automatically flip (unless flip-rtl is set to false) because "back" is left in ltr and right in rtl, and "forward" is the opposite
  323. const shouldAutoFlip = iconName
  324. ? (iconName.includes('arrow') || iconName.includes('chevron')) && flipRtl !== false
  325. : false;
  326. // if shouldBeFlippable is true, the icon should change direction when `dir` changes
  327. const shouldBeFlippable = flipRtl || shouldAutoFlip;
  328. return (h(Host, Object.assign({ role: "img", class: Object.assign(Object.assign({ [mode]: true }, createColorClasses(this.color)), { [`icon-${this.size}`]: !!this.size, 'flip-rtl': shouldBeFlippable, 'icon-rtl': shouldBeFlippable && isRTL(el) }) }, inheritedAttributes), Build.isBrowser && this.svgContent ? (h("div", { class: "icon-inner", innerHTML: this.svgContent })) : (h("div", { class: "icon-inner" }))));
  329. }
  330. static get assetsDirs() { return ["svg"]; }
  331. get el() { return this; }
  332. static get watchers() { return {
  333. "name": ["loadIcon"],
  334. "src": ["loadIcon"],
  335. "icon": ["loadIcon"],
  336. "ios": ["loadIcon"],
  337. "md": ["loadIcon"]
  338. }; }
  339. static get style() { return IonIconStyle0; }
  340. }, [1, "ion-icon", {
  341. "mode": [1025],
  342. "color": [1],
  343. "ios": [1],
  344. "md": [1],
  345. "flipRtl": [4, "flip-rtl"],
  346. "name": [513],
  347. "src": [1],
  348. "icon": [8],
  349. "size": [1],
  350. "lazy": [4],
  351. "sanitize": [4],
  352. "svgContent": [32],
  353. "isVisible": [32]
  354. }, undefined, {
  355. "name": ["loadIcon"],
  356. "src": ["loadIcon"],
  357. "icon": ["loadIcon"],
  358. "ios": ["loadIcon"],
  359. "md": ["loadIcon"]
  360. }]);
  361. const getIonMode = () => (Build.isBrowser && typeof document !== 'undefined' && document.documentElement.getAttribute('mode')) || 'md';
  362. const createColorClasses = (color) => {
  363. return color
  364. ? {
  365. 'ion-color': true,
  366. [`ion-color-${color}`]: true,
  367. }
  368. : null;
  369. };
  370. function defineCustomElement() {
  371. if (typeof customElements === "undefined") {
  372. return;
  373. }
  374. const components = ["ion-icon"];
  375. components.forEach(tagName => { switch (tagName) {
  376. case "ion-icon":
  377. if (!customElements.get(tagName)) {
  378. customElements.define(tagName, Icon);
  379. }
  380. break;
  381. } });
  382. }
  383. export { Icon as I, defineCustomElement as d };