import { r as registerInstance, h, H as Host, g as getElement } from './index-ca411ad2.js';

let missingAssetPathWarning = false;
/**
 *
 * Reads the component asset path config from meta tag or a global variable.
 * This is a temporary workaround until these issues have been addressed:
 *
 * https://github.com/ionic-team/stencil/issues/2826/
 * https://github.com/ionic-team/stencil/issues/3470
 * https://github.com/ionic-team/stencil-ds-output-targets/issues/186
 */
const getAssetPath = (path) => {
    var _a;
    const metaPineAssetPath = (_a = document.head.querySelector('meta[data-pine-asset-path]')) === null || _a === void 0 ? void 0 : _a.dataset.pineAssetPath;
    // Get the asset path from the window object if available
    const windowAssetPath = window.__PINE_ASSET_PATH__;
    // Set the CDN Asset path using the latest version
    const cdnAssetPath = 'https://cdn.jsdelivr.net/npm/@pine-ds/icons/dist/pds-icons/';
    const assetBasePath = metaPineAssetPath || windowAssetPath || cdnAssetPath || '/';
    // Display a warning if the assets are fetched from the CDN.
    if (assetBasePath.startsWith('https://cdn.jsdelivr.net/npm/') && !missingAssetPathWarning) {
        missingAssetPathWarning = true;
        console.warn(`
      Fetching Pine asssets from jsDelivr CDN.\n\n It's recommended that you bundle Pine Assets with your application and setting the path accordingly.\n\nFor more information you read the documentation: \nhttps://pine-design-system.netlify.app/?path=/docs/resources-assets--docs
    `);
    }
    let assetPath = path;
    if (path.startsWith('./')) {
        assetPath = path.substring(2);
    }
    if (!assetBasePath.endsWith('/')) {
        assetPath = '/' + assetPath;
    }
    return assetBasePath + assetPath;
};

let CACHED_MAP;
const getIconMap = () => {
    if (typeof window === 'undefined') {
        return new Map();
    }
    else {
        if (!CACHED_MAP) {
            const win = window; // eslint-disable-line @typescript-eslint/no-explicit-any
            win.PdsIcons = win.PdsIcons || {};
            CACHED_MAP = win.PdsIcons.map = win.PdsIcons.map || new Map();
        }
        return CACHED_MAP;
    }
};
const getName = (iconName, icon) => {
    if (!iconName && icon && !isSrc(icon)) {
        iconName = icon;
    }
    if (isStr(iconName)) {
        iconName = toLower(iconName);
    }
    if (!isStr(iconName) || iconName.trim() === '') {
        return null;
    }
    const invalidChars = iconName.replace(/[a-z]|-|\d/gi, '');
    if (invalidChars != '') {
        return null;
    }
    return iconName;
};
const getNamedUrl = (iconName) => {
    const url = getIconMap().get(iconName);
    if (url) {
        return url;
    }
    return getAssetPath(`svg/${iconName}.svg`);
};
const getSrc = (src) => {
    if (isStr(src)) {
        src = src.trim();
        if (isSrc(src)) {
            return src;
        }
    }
    return null;
};
const getUrl = (pdsIcon) => {
    let url = getSrc(pdsIcon.src);
    if (url) {
        return url;
    }
    url = getName(pdsIcon.name, pdsIcon.icon);
    if (url) {
        return getNamedUrl(url);
    }
    if (pdsIcon.icon) {
        url = getSrc(pdsIcon.icon);
        if (url) {
            return url;
        }
    }
    return null;
};
const isSrc = (str) => str.length > 0 && /(\/|\.)/.test(str);
const isStr = (val) => typeof val === 'string'; // eslint-disable-line @typescript-eslint/no-explicit-any
const toLower = (val) => val.toLowerCase();
/**
 * Elements inside of web components sometimes need to inherit global attributes
 * set on the host. For example, the inner input in `ion-input` should inherit
 * the `title` attribute that developers set directly on `ion-input`. This
 * helper function should be called in componentWillLoad and assigned to a variable
 * that is later used in the render function.
 *
 * This does not need to be reactive as changing attributes on the host element
 * does not trigger a re-render.
 */
const inheritAttributes = (el, attributes = []) => {
    const attributeObject = {}; // eslint-disable-line @typescript-eslint/no-explicit-any
    attributes.forEach(attr => {
        if (el.hasAttribute(attr)) {
            const value = el.getAttribute(attr);
            if (value !== null) {
                attributeObject[attr] = el.getAttribute(attr);
            }
            el.removeAttribute(attr);
        }
    });
    return attributeObject;
};

const validateContent = (svgContent) => {
    const div = document.createElement('div');
    div.innerHTML = svgContent;
    // setup this way to ensure it works on our buddy IE
    for (let i = div.childNodes.length - 1; i >= 0; i--) {
        if (div.childNodes[i].nodeName.toLowerCase() !== 'svg') {
            div.removeChild(div.childNodes[i]);
        }
    }
    // must only have 1 root element
    const svgElm = div.firstElementChild;
    if (svgElm && svgElm.nodeName.toLowerCase() === 'svg') {
        const svgClass = svgElm.getAttribute('class') || '';
        svgElm.setAttribute('class', (svgClass + ' s-pds-icon').trim());
        // root element must be an svg
        // lets double check we've got valid elements
        // do not allow scripts
        if (isValid(svgElm)) {
            return div.innerHTML;
        }
    }
    return '';
};
const isValid = (elm) => {
    if (elm.nodeType === 1) {
        if (elm.nodeName.toLowerCase() === 'script') {
            return false;
        }
        for (let i = 0; i < elm.attributes.length; i++) {
            const name = elm.attributes[i].name;
            if (isStr(name) && name.toLowerCase().indexOf('on') === 0) {
                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 pdsIconContent = new Map();
const requests = new Map(); // eslint-disable-line @typescript-eslint/no-explicit-any
let parser;
const getSvgContent = (url, sanitize = false) => {
    let req = requests.get(url);
    if (!req) {
        if (typeof fetch != 'undefined' && typeof document !== 'undefined') {
            if (isSvgDataUrl(url) && isEncodedDataUrl(url)) {
                if (!parser) {
                    parser = new DOMParser();
                }
                const doc = parser.parseFromString(url, 'text/html');
                const svg = doc.querySelector('svg');
                if (svg) {
                    pdsIconContent.set(url, svg.outerHTML);
                }
                return Promise.resolve();
            }
            else {
                // we don't have a request
                req = fetch(url).then((rsp) => {
                    if (rsp.ok) {
                        return rsp.text().then((svgContent) => {
                            if (svgContent && sanitize !== false) {
                                svgContent = validateContent(svgContent);
                            }
                            pdsIconContent.set(url, svgContent || '');
                        });
                    }
                    pdsIconContent.set(url, '');
                });
                requests.set(url, req);
            }
        }
        else {
            pdsIconContent.set(url, '');
            return Promise.resolve();
        }
    }
    return req;
};

const pdsIconCss = ":host{--dimension-icon-height:16px;--dimension-icon-width:16px;--color-icon-fill:currentColor;contain:strict;display:inline-block;fill:var(--color-icon-fill);height:var(--dimension-icon-height);width:var(--dimension-icon-width)}:host .pdsicon{fill:var(--color-icon-fill)}.pds-icon-fill-none{fill:none}.icon-inner,.pds-icon,svg{display:block;height:100%;width:100%}";
const PdsIconStyle0 = pdsIconCss;

const PdsIcon = class {
    constructor(hostRef) {
        registerInstance(this, hostRef);
        this.inheritedAttributes = {}; // eslint-disable-line @typescript-eslint/no-explicit-any
        this.hasAriaHidden = () => {
            const { el } = this;
            return el.hasAttribute('aria-hidden') && el.getAttribute('aria-hidden') === 'true';
        };
        this.ariaLabel = undefined;
        this.isVisible = false;
        this.svgContent = undefined;
        this.color = undefined;
        this.icon = undefined;
        this.name = undefined;
        this.size = 'regular';
        this.src = undefined;
    }
    iconSize() {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const sizes = {
            small: '12px',
            regular: '16px',
            medium: '20px',
            large: '24px',
        };
        if (sizes[this.size]) {
            return sizes[this.size];
        }
        else {
            return this.size;
        }
    }
    componentDidLoad() {
        this.setCSSVariables();
    }
    componentWillLoad() {
        this.inheritedAttributes = inheritAttributes(this.el, ['aria-label']);
        this.setCSSVariables();
    }
    setCSSVariables() {
        this.el.style.setProperty(`--dimension-icon-height`, this.iconSize());
        this.el.style.setProperty(`--dimension-icon-width`, this.iconSize());
        this.el.style.setProperty(`--color-icon-fill`, this.color);
    }
    connectedCallback() {
        this.waitUntilVisible(this.el, '50px', () => {
            this.isVisible = true;
            this.loadIcon();
        });
    }
    disconnectedCallback() {
        if (this.io) {
            this.io.disconnect();
            this.io = undefined;
        }
    }
    updateStyles() {
        this.setCSSVariables();
    }
    loadIcon() {
        if (this.isVisible) {
            const url = getUrl(this);
            if (url) {
                if (pdsIconContent.has(url)) {
                    this.svgContent = pdsIconContent.get(url);
                }
                else {
                    getSvgContent(url).then(() => (this.svgContent = pdsIconContent.get(url)));
                }
            }
        }
        const label = getName(this.name, this.icon);
        if (label) {
            this.ariaLabel = label.replace(/\-/g, ' ');
        }
    }
    render() {
        const { ariaLabel, inheritedAttributes } = this;
        return (h(Host, Object.assign({ key: '5797e1b5c3b7bbd222047d0a95a92eff0f661f98', "aria-label": ariaLabel !== undefined && !this.hasAriaHidden() ? ariaLabel : null, alt: "", role: "img", class: Object.assign({}, createColorClasses(this.color)) }, inheritedAttributes), this.svgContent ? (h("div", { class: "icon-inner", innerHTML: this.svgContent })) : (h("div", { class: "icon-inner" }))));
    }
    /*****
     * Private Methods
     ****/
    waitUntilVisible(el, rootMargin, cb) {
        if (typeof window !== 'undefined' && (window).IntersectionObserver) {
            const io = (this.io = new (window).IntersectionObserver((data) => {
                if (data[0].isIntersecting) {
                    io.disconnect();
                    this.io = undefined;
                    cb();
                }
            }, { rootMargin }));
            io.observe(el);
        }
        else {
            // browser doesn't support IntersectionObserver
            // so just fallback to always show it
            cb();
        }
    }
    static get assetsDirs() { return ["svg"]; }
    get el() { return getElement(this); }
    static get watchers() { return {
        "size": ["updateStyles"],
        "color": ["updateStyles"],
        "name": ["loadIcon"],
        "src": ["loadIcon"],
        "icon": ["loadIcon"]
    }; }
};
const createColorClasses = (color) => {
    return color
        ? {
            'pds-color': true,
            [`pds-color-${color}`]: true,
        }
        : null;
};
PdsIcon.style = PdsIconStyle0;

export { PdsIcon as pds_icon };

//# sourceMappingURL=pds-icon.entry.js.map