/*!
 * Custom elements for Nanopore-Digital Web applications
 */
import { proxyCustomElement, HTMLElement, createEvent, Host, Build } from '@stencil/core/internal/client';
import { h } from './renderer.js';
import { d as defineCustomElement$1 } from './resize-observe.js';

const imgCss = ":host,*,*::before,*::after{box-sizing:border-box}[hidden]{display:none !important}@media (prefers-reduced-motion: reduce){:host,*,*::before,*::after{animation-duration:0.01ms !important;animation-iteration-count:1 !important;transition-duration:0.01ms !important;scroll-behavior:auto !important}}:host,*,*::before,*::after{box-sizing:border-box}[hidden]{display:none !important}@media (prefers-reduced-motion: reduce){:host,*,*::before,*::after{animation-duration:0.01ms !important;animation-iteration-count:1 !important;transition-duration:0.01ms !important;scroll-behavior:auto !important}}:host{--padding:0;display:inline-block;object-fit:cover;object-position:center;background-size:cover;background-position:center}:host *{border-radius:inherit}:host([background]:not([background=false])){display:block}.img{position:relative;object-fit:inherit;object-position:inherit;background-color:inherit;background-position:inherit;background-size:inherit;background-origin:inherit;background-attachment:inherit;background-repeat:inherit;flex:1 1 100%;display:flex;flex-direction:column;min-block-size:inherit;min-inline-size:inherit;block-size:inherit;inline-size:inherit;max-block-size:inherit;max-inline-size:inherit;aspect-ratio:inherit}.img__loader,.img__observer{position:absolute;inset:0;block-size:100%;inline-size:100%;z-index:-1}.img__image,.img__bg{border-radius:inherit;display:block;opacity:0;transition:0.5s ease opacity, 0.3s ease filter 0.4s;filter:blur(5px);flex:1}.img__image.loaded,.img__bg.loaded{opacity:1;filter:blur(0)}@media not all and (resolution >= 0.001dpcm){@supports (-webkit-appearance: none){.img__image.loaded,.img__bg.loaded{filter:blur(0)}}}.img__image{object-fit:inherit;object-position:inherit;min-block-size:inherit;min-inline-size:inherit;block-size:inherit;inline-size:inherit;max-block-size:inherit;max-inline-size:inherit;aspect-ratio:inherit}.img__image.hide{visibility:hidden}.img__image.hide.no-height{block-size:1px;position:absolute;z-index:-1}.img__bg{background-color:inherit;background-position:inherit;background-size:inherit;background-origin:inherit;background-attachment:inherit;background-repeat:inherit;overflow:auto;padding:var(--padding)}.img__bg.no-height{position:absolute;inset:0}";

const Img = /*@__PURE__*/ proxyCustomElement(class Img extends HTMLElement {
    constructor() {
        super();
        this.__registerHost();
        this.__attachShadow();
        this.nanoImgWillLoad = createEvent(this, "nanoImgWillLoad", 7);
        this.nanoImgDidLoad = createEvent(this, "nanoImgDidLoad", 7);
        this.nanoImgError = createEvent(this, "nanoImgError", 7);
    }
    io;
    _srcSet = {};
    get host() { return this; }
    loadSrc;
    loadError;
    hasLoaded = false;
    imgStates = null;
    _src;
    _srcChanged() {
        this.hasLoaded = false;
        this.addIO();
    }
    /** This attribute defines the alternative text describing the image.
     * Users will see this text displayed if the image URL is wrong, or if the image is not yet downloaded. */
    alt;
    /** The image URL. This attribute is mandatory for the `<img>` element. */
    src;
    srcChanged() {
        this._src = this.src;
    }
    /** Optional list string providing media sizes with corresponding image srcs.
     * i.e. show img-x at 300px wide. Format `srcSet="200w src/imgSmall.jpg, 500h src/imgMed.png"` */
    srcSet;
    srcSetChanged() {
        if (!this.srcSet)
            return;
        delete this._srcSet;
        this._srcSet = {};
        this.imgStates = this.srcSet
            .split(',')
            .map((bpSrc) => {
            const [bp, src] = bpSrc.split(' ').filter((bp) => bp.length);
            this._srcSet[bp] = { src: src, active: false };
            return bp;
        })
            .join(', ');
    }
    /** Render image lazily, when it comes into the browser viewport **/
    lazy = true;
    lazyChanged() {
        if (!this.lazy)
            this.load();
    }
    /** Render the image as a background image **/
    background;
    /** When the image is rendered as a background, and there is no preset dimensions of the component,
     * you can set how the component height will be set. Via image size or via the content **/
    autoHeight = 'content';
    /** Emitted when the img src has been set */
    nanoImgWillLoad;
    /** Emitted when the image has finished loading */
    nanoImgDidLoad;
    /** Emitted when the img fails to load */
    nanoImgError;
    addIO() {
        if (!this._src || this.hasLoaded)
            return;
        if (!this.lazy) {
            this.load();
            return;
        }
        if (typeof window !== 'undefined' &&
            'IntersectionObserver' in window) {
            this.removeIO();
            this.io = new IntersectionObserver((data) => {
                if (data[0].isIntersecting) {
                    this.load();
                    this.removeIO();
                }
            });
            this.io.observe(this.host);
        }
        else
            setTimeout(() => this.load(), 200);
    }
    load() {
        this.loadError = this.onError;
        this.loadSrc = this._src;
        this.nanoImgWillLoad.emit();
    }
    onLoad = () => {
        this.nanoImgDidLoad.emit();
        setTimeout(() => (this.hasLoaded = true), 50);
    };
    onError = () => {
        this.nanoImgError.emit();
    };
    onResize = (e) => {
        Object.entries(e.detail).forEach(([bp, active]) => {
            this._srcSet[bp].active = !!active;
        });
        // sort and find the highest sized matching image.
        const srcOpts = [];
        Object.keys(this._srcSet)
            .sort()
            .forEach((bp) => {
            if (this._srcSet[bp].active)
                srcOpts.push(this._srcSet[bp].src);
        });
        if (srcOpts.length)
            this._src = srcOpts.slice(-1)[0];
        // no matching image? Set back to default
        else
            this._src = this.src;
    };
    removeIO() {
        if (this.io) {
            this.io.disconnect();
            this.io = undefined;
        }
    }
    connectedCallback() {
        this.srcChanged();
        this.srcSetChanged();
        this.lazyChanged();
    }
    componentDidLoad() {
        this.addIO();
    }
    disconnectedCallback() {
        this.removeIO();
    }
    render() {
        const bgStyle = this.loadSrc
            ? { 'background-image': `url(${this.loadSrc})` }
            : {};
        return (h(Host, { key: 'f8774fc9ad6e94727378337c2f405a068a7c88fb', class: "nano-img" }, h("div", { key: '15ae3c8ea944c8f0eab8616194f44fc1033e8fe2', class: "img" }, h("div", { key: 'ec3f433ded23dcb7fc57e53b0ecaba789ba492e0', class: "img__loader n-loader-skeleton" }, "Loading"), !!this.background && (h("div", { key: '8f4e8c9d595a31b477b0ae3f9e135f6b5c3f0e69', class: {
                loaded: this.hasLoaded,
                img__bg: true,
                'no-height': this.autoHeight === 'image',
            }, style: bgStyle }, h("slot", { key: '29bab2a5c86b3dfe18db8936af77674c44d743d0' }))), h("img", { key: 'e6731b48ed137d97aa98e64dc55488d56724f672', class: {
                img__image: true,
                loaded: this.hasLoaded,
                hide: this.background,
                'no-height': this.autoHeight === 'content',
            }, decoding: "async", src: Build.isServer ? this.src : this.loadSrc, loading: Build.isServer && this.lazy ? 'lazy' : undefined, alt: this.alt, onLoad: this.onLoad, onError: this.loadError }), h("nano-resize-observe", { key: '0f1ce7d8b82adc19bfa459ff2adae708a4263c6e', class: "img__observer", onNanoResizeStateChange: this.onResize, states: this.imgStates }))));
    }
    static get watchers() { return {
        "_src": ["_srcChanged"],
        "src": ["srcChanged"],
        "srcSet": ["srcSetChanged"],
        "lazy": ["lazyChanged"]
    }; }
    static get style() { return imgCss; }
}, [257, "nano-img", {
        "alt": [1],
        "src": [1],
        "srcSet": [1, "src-set"],
        "lazy": [4],
        "background": [4],
        "autoHeight": [1, "auto-height"],
        "loadSrc": [32],
        "loadError": [32],
        "hasLoaded": [32],
        "imgStates": [32],
        "_src": [32]
    }, undefined, {
        "_src": ["_srcChanged"],
        "src": ["srcChanged"],
        "srcSet": ["srcSetChanged"],
        "lazy": ["lazyChanged"]
    }]);
function defineCustomElement() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["nano-img", "nano-resize-observe"];
    components.forEach(tagName => { switch (tagName) {
        case "nano-img":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, Img);
            }
            break;
        case "nano-resize-observe":
            if (!customElements.get(tagName)) {
                defineCustomElement$1();
            }
            break;
    } });
}

export { Img as I, defineCustomElement as d };
