ionicons
Version:
Premium icons for Ionic.
361 lines (354 loc) • 15 kB
JavaScript
'use strict';
var index$1 = require('./index-4_Berl5e.js');
var index = require('./index-tkr2PTVD.js');
/**
* Calls `onRejected` only when an `<svg>` was found and failed validation,
* not when there's no `<svg>` at all (like an HTML 404 page).
*/
const validateContent = (svgContent, onRejected) => {
/**
* Parse into a template so nothing loads or runs yet. Parsing into a live
* element would fire handlers like `<img onerror>` before validation.
*/
const template = document.createElement('template');
template.innerHTML = svgContent;
const content = template.content;
for (let i = content.childNodes.length - 1; i >= 0; i--) {
if (content.childNodes[i].nodeName.toLowerCase() !== 'svg') {
content.removeChild(content.childNodes[i]);
}
}
const svgElm = content.firstElementChild;
if (svgElm && svgElm.nodeName.toLowerCase() === 'svg') {
const svgClass = svgElm.getAttribute('class') || '';
svgElm.setAttribute('class', (svgClass + ' s-ion-icon').trim());
/**
* Illustrator exports keep editor data in a `<foreignObject>` next to the
* artwork, so remove it instead of rejecting the icon.
*/
removeForeignObjects(svgElm);
// every root is serialized, so a second <svg> would skip validation
if (content.children.length === 1 && isValid(svgElm)) {
return template.innerHTML;
}
onRejected === null || onRejected === void 0 ? void 0 : onRejected();
}
return '';
};
const removeForeignObjects = (elm) => {
for (let i = elm.children.length - 1; i >= 0; i--) {
const child = elm.children[i];
if (child.nodeName.toLowerCase() === 'foreignobject') {
child.remove();
}
else {
removeForeignObjects(child);
}
}
};
/**
* Elements that can run script or load a document without an `on*` attribute.
*/
const disallowedElements = new Set(['script', 'foreignobject', 'iframe', 'embed', 'object']);
/**
* Browsers ignore whitespace and control characters in a URL scheme, so strip
* them first. Checking the whole value also catches lists like
* `<animate values="a;javascript:...">`.
*/
const hasJavascriptUrl = (value) => value
.replace(/[\u0000-\u0020]/g, '')
.toLowerCase()
.includes('javascript:');
const SVG_NS = 'http://www.w3.org/2000/svg';
const isValid = (elm) => {
if (elm.nodeType === 1) {
/**
* HTML inside `<desc>` or `<title>` (like `<noscript>`) can parse
* differently when it renders than it did here, so only allow SVG elements.
*/
if (elm.namespaceURI !== SVG_NS || disallowedElements.has(elm.nodeName.toLowerCase())) {
return false;
}
for (let i = 0; i < elm.attributes.length; i++) {
const { name, value } = elm.attributes[i];
if (index.isStr(name) && name.toLowerCase().indexOf('on') === 0) {
return false;
}
if (index.isStr(value) && hasJavascriptUrl(value)) {
return false;
}
}
for (let i = 0; i < elm.childNodes.length; i++) {
if (!isValid(elm.childNodes[i])) {
return false;
}
}
}
return true;
};
const isSvgDataUrl = (url) => url.startsWith('data:image/svg+xml');
const isEncodedDataUrl = (url) => url.indexOf(';utf8,') !== -1;
const ioniconContent = new Map();
const requests = new Map();
let parser;
/**
* Unsanitized content gets its own key so it's never served to an icon that
* sanitizes.
*/
const getCacheKey = (url, sanitize) => `${sanitize !== false ? 'sanitized' : 'unsanitized'}:${url}`;
/**
* Warns when the whole icon is rejected so it doesn't silently render nothing.
*/
const sanitizeSvg = (url, svgContent) => validateContent(svgContent, () => {
const source = url.length > 100 ? `${url.slice(0, 100)}...` : url;
console.warn(`[Ionicons Warning]: The SVG from "${source}" was not rendered because it failed sanitization. Only set sanitize="false" for SVG content from a trusted source.`);
});
/**
* Safely fallback to an empty svg
*/
function safeFallback(cacheKey) {
const svg = '';
ioniconContent.set(cacheKey, svg);
return svg;
}
const getSvgContent = (url, sanitize) => {
const cacheKey = getCacheKey(url, sanitize);
/**
* See if we already have a request for this url
*/
const req = requests.get(cacheKey);
if (req) {
return req;
}
if (typeof fetch !== 'undefined' && typeof document !== 'undefined') {
/**
* If the url is a data url of an svg, then try to parse it
* with the DOMParser. This works with content security policies enabled.
*/
if (isSvgDataUrl(url) && isEncodedDataUrl(url)) {
return Promise.resolve(getSvgByUrl(url, sanitize));
}
return fetchSvg(url, sanitize);
}
return Promise.resolve(safeFallback(cacheKey));
};
function getSvgByUrl(url, sanitize) {
if (!parser) {
/**
* Create an instance of the DOM parser. This creates a single
* parser instance for the entire app, which is more efficient.
*/
parser = new DOMParser();
}
const doc = parser.parseFromString(url, 'text/html');
const svg = doc.querySelector('svg');
if (svg) {
const svgContent = sanitize !== false ? sanitizeSvg(url, svg.outerHTML) : svg.outerHTML;
ioniconContent.set(getCacheKey(url, sanitize), svgContent);
return svgContent;
}
throw new Error(`Could not parse svg from ${url}`);
}
function fetchSvg(url, sanitize) {
const cacheKey = getCacheKey(url, sanitize);
/**
* We don't already have a request
*/
const req = fetch(url)
.then((rsp) => {
/**
* When fetching from a file:// URL, some browsers return
* a 0 status code even when the request succeeds so don't
* rely on rsp.ok as the only signal of success.
*/
return rsp
.text()
.then((svgContent) => {
if (svgContent && sanitize !== false) {
svgContent = sanitizeSvg(url, svgContent);
}
const svg = svgContent || '';
ioniconContent.set(cacheKey, svg);
return svg;
})
.catch(() => safeFallback(cacheKey));
})
.catch(() => safeFallback(cacheKey));
/**
* Cache for the same requests
*/
requests.set(cacheKey, req);
return req;
}
const iconCss = () => `:host{display:inline-block;width:1em;height:1em;font-size:1em;contain:layout style;fill:currentColor;box-sizing:content-box !important}:host .ionicon{stroke:currentColor}.ionicon-fill-none{fill:none}.ionicon-stroke-width{stroke-width:var(--ionicon-stroke-width, 32px)}.icon-inner{display:flex;align-items:center;justify-content:center;width:100%;height:100%}.ionicon,svg{display:block;height:100%;width:100%}::slotted(*){font-size:inherit !important} (background: -webkit-named-image(i)){:host(.icon-rtl) .icon-inner{transform:scaleX(-1)}} not selector(:dir(rtl)) and selector(:host-context([dir='rtl'])){:host(.icon-rtl) .icon-inner{transform:scaleX(-1)}}:host(.flip-rtl):host-context([dir='rtl']) .icon-inner{transform:scaleX(-1)} selector(:dir(rtl)){:host(.flip-rtl:dir(rtl)) .icon-inner{transform:scaleX(-1)}:host(.flip-rtl:dir(ltr)) .icon-inner{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)}`;
const Icon = class {
constructor(hostRef) {
index$1.registerInstance(this, hostRef);
this.iconName = null;
this.inheritedAttributes = {};
this.didLoadIcon = false;
this.isVisible = false;
/**
* The mode determines which platform styles to use.
*/
this.mode = getIonMode();
/**
* If enabled, ion-icon will be loaded lazily when it's visible in the viewport.
* Default, `false`.
*/
this.lazy = false;
/**
* When `true`, SVG content, including SVG `data:` URLs, is checked before it
* renders. SVGs with `<script>` elements, attributes that start with `on`
* (like `onclick`), `javascript:` URLs, or non-SVG elements aren't rendered,
* and `<foreignObject>` elements are removed. Only set this to `false` for
* SVG content from a trusted source.
* @default true
*/
this.sanitize = true;
}
componentWillLoad() {
this.inheritedAttributes = index.inheritAttributes(this.el, ['aria-label']);
}
connectedCallback() {
/**
* purposely do not return the promise here because loading
* the svg file should not hold up loading the app
* only load the svg if it's visible
*/
this.waitUntilVisible(this.el, '50px', () => {
this.isVisible = true;
this.loadIcon();
});
}
/**
* Loads the icon after the component has finished rendering.
*/
componentDidLoad() {
/**
* Addresses an Angular issue where property values are assigned after the 'connectedCallback' but prior to the registration of watchers.
* This enhancement ensures the loading of an icon when the component has finished rendering and the icon has yet to apply the SVG data.
* This modification pertains to the usage of Angular's binding syntax:
* `<ion-icon [name]="myIconName"></ion-icon>`
*/
if (!this.didLoadIcon) {
this.loadIcon();
}
}
/**
* Disconnect the IntersectionObserver.
*/
disconnectedCallback() {
if (this.io) {
this.io.disconnect();
this.io = undefined;
}
}
/**
* Wait until the icon is visible in the viewport.
* @param el - The element to observe.
* @param rootMargin - The root margin of the observer.
* @param cb - The callback to call when the element is visible.
*/
waitUntilVisible(el, rootMargin, cb) {
/**
* IntersectionObserver is a browser API that allows you to observe
* the visibility of an element relative to a root element. It is
* supported in all modern browsers, except IE and when server-side
* rendering.
*/
const hasIntersectionObserverSupport = Boolean(this.lazy && typeof window !== 'undefined' && window.IntersectionObserver);
/**
* browser doesn't support IntersectionObserver
* so just fallback to always show it
*/
if (!hasIntersectionObserverSupport) {
return cb();
}
const io = (this.io = new window.IntersectionObserver((data) => {
if (data[0].isIntersecting) {
io.disconnect();
this.io = undefined;
cb();
}
}, { rootMargin }));
io.observe(el);
}
/**
* Watch for changes to the icon name, src, icon, ios, or md properties.
* When a change is detected, the icon will be loaded.
*/
loadIcon() {
if (this.isVisible) {
const url = index.getUrl(this);
if (url) {
const cacheKey = getCacheKey(url, this.sanitize);
if (ioniconContent.has(cacheKey)) {
// sync if it's already loaded
this.svgContent = ioniconContent.get(cacheKey);
}
else {
// async if it hasn't been loaded
getSvgContent(url, this.sanitize).then(() => (this.svgContent = ioniconContent.get(cacheKey)));
}
this.didLoadIcon = true;
}
}
this.iconName = index.getName(this.name, this.icon, this.mode, this.ios, this.md);
}
render() {
const { flipRtl, iconName, inheritedAttributes, el } = this;
const mode = this.mode || 'md';
/**
* 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
*/
const shouldAutoFlip = iconName
? (iconName.includes('arrow') || iconName.includes('chevron')) && flipRtl !== false
: false;
/**
* if shouldBeFlippable is true, the icon should change direction when `dir` changes
*/
const shouldBeFlippable = flipRtl || shouldAutoFlip;
return (index$1.h(index$1.Host, Object.assign({ key: 'd2d2ba17fc8933d6e411bb95a1dc89accb12b909', role: "img", class: Object.assign(Object.assign({ [mode]: true }, createColorClasses(this.color)), { [`icon-${this.size}`]: !!this.size, 'flip-rtl': shouldBeFlippable, 'icon-rtl': shouldBeFlippable && index.isRTL(el) }) }, inheritedAttributes), this.svgContent ? (index$1.h("div", { class: "icon-inner", innerHTML: this.svgContent })) : (index$1.h("div", { class: "icon-inner" }, index$1.h("slot", null)))));
}
static get assetsDirs() { return ["svg"]; }
get el() { return index$1.getElement(this); }
static get watchers() { return {
"name": [{
"loadIcon": 0
}],
"src": [{
"loadIcon": 0
}],
"icon": [{
"loadIcon": 0
}],
"ios": [{
"loadIcon": 0
}],
"md": [{
"loadIcon": 0
}]
}; }
};
/**
* Get the mode of the document.
* @returns The mode of the document.
*/
const getIonMode = () => (typeof document !== 'undefined' && document.documentElement.getAttribute('mode')) || 'md';
/**
* Create color classes for the icon.
* @param color - The color of the icon.
* @returns The color classes for the icon.
*/
const createColorClasses = (color) => {
return color
? {
'ion-color': true,
[`ion-color-${color}`]: true,
}
: null;
};
Icon.style = iconCss();
exports.ion_icon = Icon;