import { h } from '../webcomponents.core.js';

import './chunk-de721f0a.js';
import './chunk-fec5a75d.js';
import { c as pluck } from './chunk-d51357a9.js';
import { e as Util, j as DomUtil } from './chunk-f9f1602a.js';
import { a as AppService } from './chunk-50f0a6d7.js';

class AppRoot {
    constructor() {
        this.initialized = true;
        this.app = AppService.instance;
        this.config = this.app.config;
        this.stateService = this.app.stateService;
        this.translation = this.app.translation;
        this.app.globalState$.subscribe((state) => {
            this.globalState = Object.assign({}, state);
        });
        this.app.state$.subscribe((state) => {
            this.state = Object.assign({}, state);
            this.render();
        });
        this.app.state$.pipe(pluck('uaas')).subscribe((state) => {
        });
    }
    render() {
        if (!this.globalState.initialized) {
            return (h("div", null,
                h("ema-loading-spinner", { type: "ios", color: "#495057", id: 'loading-spinner' })));
        }
        else {
            return (h("div", null,
                h("ema-flash-message", null),
                h("ema-dialog", { id: 'app-dialog', "allow-close": "true" }),
                h("ema-modal", { id: 'app-modal' }),
                h("ema-modal", { id: 'login-modal', "modal-title": this.translation.get('LOGIN'), width: '80%', "allow-close": "true" },
                    h("ema-login-form", { errorMessage: '' })),
                h("ema-debugger", { type: 'dwp', "api-url": 'api/', "history-size": '100', "max-level": -1, "collapse-at": 4 }),
                h("header", null,
                    h("nav", { class: "navbar navbar-expand-md fixed-top" },
                        h("a", { class: "navbar-brand", href: '/' }, this.config.get('name')),
                        h("a", { href: '/' },
                            h("ion-icon", { id: "logo", name: "code", size: "large" })),
                        h("div", { class: "collapse navbar-collapse", id: "navbarCollapse" },
                            h("ul", { class: "navbar-nav mr-auto" },
                                h("li", { class: "nav-item active" },
                                    h("ema-route-link", { url: '/components' }, "Examples")),
                                h("li", { class: "nav-item active" },
                                    h("ema-route-link", { url: '/documentation' }, "Docs")),
                                h("li", { class: "nav-item active" },
                                    h("ema-route-link", { url: '/architecture' }, "Architecture")),
                                h("li", { class: "nav-item active" },
                                    h("ema-route-link", { url: '/forms' }, "Forms")),
                                this.config.get('dev') &&
                                    h("li", { class: "nav-item active" },
                                        h("ema-route-link", { url: '/sketch' }, "Sketch")),
                                this.config.get('dev') &&
                                    h("li", { class: "nav-item active" },
                                        h("ema-route-link", { url: '/dev' }, "Dev")),
                                this.config.get('dev') &&
                                    h("li", { class: "nav-item active" },
                                        h("ema-route-link", { url: '/swagger' }, "Swag")),
                                this.config.get('dev') &&
                                    h("li", { class: "nav-item active" },
                                        h("ema-route-link", { url: '/drupal/1' }, "Drupal")),
                                this.config.get('dev') &&
                                    h("li", { class: "nav-item active" },
                                        h("ema-route-link", { url: '/wordpress/1' }, "Wp")))),
                        h("button", { class: "navbar-toggler", type: "button", "data-toggle": "collapse", "data-target": "#navbarCollapse", "aria-controls": "navbarCollapse", "aria-expanded": "false", "aria-label": "Toggle navigation" },
                            h("span", { class: "navbar-toggler-icon" })))),
                h("main", null),
                h("ema-router", { "target-selector": "main", level: 0 },
                    h("ema-route", { url: '/', component: 'ema-app-home', exact: true }),
                    h("ema-route", { url: '/components', component: 'ema-app-components', exact: true }),
                    h("ema-route", { url: '/components/:name', component: 'ema-app-components' }),
                    h("ema-route", { url: '/documentation/:path/:page', component: 'ema-app-iframe', exact: true, componentProps: '{ "iframe-url": "assets/documentation/" }' }),
                    h("ema-route", { url: '/documentation', component: 'ema-app-iframe', componentProps: '{ "iframe-url": "assets/documentation-components/" }' }),
                    h("ema-route", { url: '/architecture', component: 'sk-dev-stack', exact: true, componentProps: '{ "data-json": {"title":"architecture"}}' }),
                    h("ema-route", { url: '/sketch', component: 'ema-app-sketch', exact: true, componentProps: '{ "data-json": {"title":"Sketch"}}' }),
                    h("ema-route", { url: '/forms', component: 'ema-app-forms' }),
                    h("ema-route", { url: '/dev', component: 'ema-app-dev' }),
                    h("ema-route", { url: '/swagger', component: 'ema-app-swagger' }),
                    h("ema-route", { url: '/drupal/:nid', component: 'ema-app-drupal', componentProps: '{ "drupal-host": "streamer-local" }' }),
                    h("ema-route", { url: '/wordpress/:pid', component: 'ema-app-wordpress' }))));
        }
    }
    static get is() { return "ema-app-root"; }
    static get properties() { return {
        "dataJson": {
            "type": String,
            "attr": "data-json"
        },
        "errorMessage": {
            "state": true
        },
        "globalState": {
            "state": true
        },
        "initialized": {
            "state": true
        },
        "state": {
            "state": true
        }
    }; }
    static get style() { return "\@import url(https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i,800,800i);:root{--ema-color:#343a40;--ema-primary:#007bff;--ema-secondary:#6c757d;--ema-success:#28a745;--ema-info:#17a2b8;--ema-warning:#ffc107;--ema-danger:#dc3545;--ema-light:#f8f9fa;--ema-dark:#343a40;--ema-background:#fff;--ema-background-diap:rgba(29,29,29,0.97);--ema-border-color:#c5c9cd;--ema-border:1px solid #c5c9cd;--ema-border-radius:3px 3px 3px 3px;--ema-box-shadow:1px 1px 10px 1px #ccc;--ema-margin:0.25rem;--ema-margin-sm:0.5rem;--ema-margin-md:1rem;--ema-margin-lg:1.5rem;--ema-margin-xl:2rem;--ema-padding:0.25rem;--ema-padding-sm:0.5rem;--ema-padding-md:1rem;--ema-padding-lg:1.5rem;--ema-padding-xl:2rem}body,html{height:100%}body{background:var(--ema-background)!important;color:var(--ema-color)!important;font-family:Open Sans,sans-serif,-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol}:focus,a:focus,button:focus,input:focus,textarea:focus{outline:none!important}ema-app-root header nav{background:var(--ema-background-primary,#fff);border-bottom:1px solid #c5c9cd}ema-app-root header ion-icon{margin-top:-.33333rem;margin-right:.5rem}ema-app-root main{margin-top:57px}ema-app-root :focus{outline:none}ema-app-root #loading-spinner{margin-top:5rem}ema-app-root .card{border:1px solid #c5c9cd}ema-app-root .jumbotron{background:var(--ema-background-primary);margin-left:-1rem;margin-right:-1rem}ema-app-root .navbar{padding:0 1rem}ema-app-root .navbar .nav-link{padding:1rem;cursor:pointer}ema-app-root .navbar.fixed-top{min-height:57px;border-bottom:1px solid #c5c9cd}ema-app-root .navbar.fixed-bottom{border-top:1px solid #c5c9cd;-ms-flex-line-pack:center;align-content:center}ema-app-root .navbar.fixed-bottom,ema-app-root .navbar.fixed-top{background-color:var(--ema-background,#fff)}ema-app-root .navbar.fixed-bottom .navbar-brand,ema-app-root .navbar.fixed-top .navbar-brand{color:inherit;margin-top:-3px;font-size:18px;font-weight:700}ema-app-root .navbar.fixed-bottom #logo,ema-app-root .navbar.fixed-top #logo{margin-top:2px}ema-app-root .navbar.fixed-bottom .nav-item,ema-app-root .navbar.fixed-top .nav-item{padding:1rem}ema-app-root .navbar.fixed-bottom .nav-item a span,ema-app-root .navbar.fixed-top .nav-item a span{color:#495057}ema-app-root .navbar.fixed-bottom .nav-item .fas,ema-app-root .navbar.fixed-top .nav-item .fas{color:#495057;margin-right:.5rem}ema-app-root .navbar.fixed-bottom .navbar-toggler,ema-app-root .navbar.fixed-top .navbar-toggler{border:none;font-size:190%;color:#5e5e5e;margin-top:2px;margin-left:.5rem;margin-bottom:-4px;z-index:2000}ema-app-root .navbar.fixed-bottom .navbar-toggler-icon,ema-app-root .navbar.fixed-top .navbar-toggler-icon{background-image:url(/assets/icon/icon-hamburger.svg);margin-top:-.25rem;position:fixed;top:.5rem;right:.5rem;z-index:11000}ema-app-root .navbar.fixed-bottom .navbar-toggler.collapsed,ema-app-root .navbar.fixed-top .navbar-toggler.collapsed{color:grey;rotation:190%}ema-app-root .navbar.fixed-bottom .navbar-collapse .open,ema-app-root .navbar.fixed-top .navbar-collapse .open{max-width:50%}ema-app-root .navbar.fixed-bottom .nav .open>.nav-link,ema-app-root .navbar.fixed-bottom .nav .open>.nav-link:focus,ema-app-root .navbar.fixed-bottom .nav .open>.nav-link:hover,ema-app-root .navbar.fixed-top .nav .open>.nav-link,ema-app-root .navbar.fixed-top .nav .open>.nav-link:focus,ema-app-root .navbar.fixed-top .nav .open>.nav-link:hover{border-right:none}ema-app-root .navbar.fixed-bottom .nav .open>.nav-link:focus li a,ema-app-root .navbar.fixed-bottom .nav .open>.nav-link:hover li a,ema-app-root .navbar.fixed-bottom .nav .open>.nav-link li a,ema-app-root .navbar.fixed-top .nav .open>.nav-link:focus li a,ema-app-root .navbar.fixed-top .nav .open>.nav-link:hover li a,ema-app-root .navbar.fixed-top .nav .open>.nav-link li a{background-color:var(--ema-background,#fff)}\@media screen and (max-width:767px){ema-app-root .navbar.fixed-bottom .navbar-header,ema-app-root .navbar.fixed-top .navbar-header{border-bottom:1px solid #c5c9cd}ema-app-root .navbar.fixed-bottom .navbar-collapse,ema-app-root .navbar.fixed-top .navbar-collapse{background-color:#dee2e6;-webkit-box-shadow:3px 3px 5px 0 rgba(0,0,0,.33);box-shadow:3px 3px 5px 0 rgba(0,0,0,.33);margin-top:1.15rem}ema-app-root .navbar.fixed-bottom .nav-item,ema-app-root .navbar.fixed-top .nav-item{border-left:1px solid #c5c9cd;border-bottom:1px solid #c5c9cd;border-right:1px solid #c5c9cd}ema-app-root .navbar.fixed-bottom .nav-item .icon,ema-app-root .navbar.fixed-top .nav-item .icon{margin-top:.55rem}ema-app-root .navbar.fixed-bottom .nav-item:first-child,ema-app-root .navbar.fixed-top .nav-item:first-child{border-top:1px solid #c5c9cd}ema-app-root .navbar.fixed-bottom .nav-item:last-child,ema-app-root .navbar.fixed-top .nav-item:last-child{border-bottom:none}}ema-app-root .navbar-inverse{background:#000;color:#fff}ema-app-root .visible{display:block}ema-app-root .hidden{display:none}"; }
}

class Debugger {
    constructor() {
        this.history = [];
        this.viewerLabel = 'Select a route to inspect';
        this.addToHistory = true;
        this.isActive = false;
        this.isOpen = false;
        this.isRunning = true;
        this.jsonLoaded = false;
        this.type = "uaas";
        this.historySize = 100;
    }
    componentDidLoad() {
        let event = new CustomEvent("initDebugger", {
            detail: {}
        });
        window.dispatchEvent(event);
        document.onkeydown = (e) => this.handleKeyDown(e);
    }
    setCurrentItem(index, addToHistory = true) {
        this.addToHistory = addToHistory;
        this.currentItem = this.history[index];
        if (this.type === 'dwp') {
            if (this.currentItem.response)
                this.currentItem.config = this.currentItem.response.config;
            this.viewerLabel = 'URL: ' + this.currentItem.config.url.replace(this.apiUrl, '');
        }
        if (this.type === 'uaas') {
            this.viewerLabel = 'URL: ' + this.currentItem.config.url.replace(this.apiUrl, '');
        }
    }
    onListItemClick(index, addToHistory = false) {
        let divs = document.querySelectorAll('.url-list li'), i;
        for (i = 0; i < divs.length; ++i) {
            let el = divs[i];
        }
        this.setCurrentItem(index, addToHistory);
    }
    handleKeyDown(e) {
        let ctrlPressed;
        let altPressed;
        let shiftPressed;
        let evt = (e == null ? event : e);
        shiftPressed = evt.shiftKey;
        altPressed = evt.altKey;
        ctrlPressed = evt.ctrlKey;
        if ((shiftPressed || altPressed || ctrlPressed)
            && (evt.keyCode < 16 || evt.keyCode > 18))
            if (ctrlPressed && evt.keyCode == 68) {
                this.toggle();
            }
        return true;
    }
    pushHistory(value) {
        if (this.history.length >= Number(this.historySize)) {
            this.history.pop();
        }
        this.history.unshift(value);
    }
    async open() {
        this.host.style.display = 'block';
        this.isOpen = true;
    }
    async close() {
        this.host.style.display = 'none';
        this.isOpen = false;
    }
    async toggle() {
        this.isOpen ? this.close() : this.open();
    }
    async run() {
        this.addToHistory = true;
        this.isRunning = true;
    }
    async pause() {
        this.addToHistory = false;
        this.isRunning = false;
    }
    render() {
        if (this.isRunning) {
            if (this.dataJson) {
                this.data = JSON.parse(this.dataJson);
                this.addToHistory ? this.pushHistory(this.data) : this.addToHistory = true;
            }
            if (this.jsonUrl && !this.jsonLoaded) {
                Util.fetchJson(this.jsonUrl).then((res) => {
                    this.data = res;
                    this.addToHistory ? this.pushHistory(this.data) : this.addToHistory = false;
                    this.jsonLoaded = true;
                });
            }
        }
        return (h("div", null,
            h("ema-card", null,
                h("ema-card-header", null,
                    h("span", { class: "ema-card-header-title" },
                        "Debugger: ",
                        this.type),
                    h("span", { class: "ema-card-header-subtitle" },
                        "Api url = ",
                        this.apiUrl),
                    h("div", { class: 'btn-close', onClick: () => this.close() },
                        h("svg", { version: "1.1", xmlns: "http://www.w3.org/2000/svg", width: "22", height: "28", viewBox: "0 0 22 28" },
                            h("title", null, "close"),
                            h("path", { d: "M20.281 20.656c0 0.391-0.156 0.781-0.438 1.062l-2.125 2.125c-0.281 0.281-0.672 0.438-1.062 0.438s-0.781-0.156-1.062-0.438l-4.594-4.594-4.594 4.594c-0.281 0.281-0.672 0.438-1.062 0.438s-0.781-0.156-1.062-0.438l-2.125-2.125c-0.281-0.281-0.438-0.672-0.438-1.062s0.156-0.781 0.438-1.062l4.594-4.594-4.594-4.594c-0.281-0.281-0.438-0.672-0.438-1.062s0.156-0.781 0.438-1.062l2.125-2.125c0.281-0.281 0.672-0.438 1.062-0.438s0.781 0.156 1.062 0.438l4.594 4.594 4.594-4.594c0.281-0.281 0.672-0.438 1.062-0.438s0.781 0.156 1.062 0.438l2.125 2.125c0.281 0.281 0.438 0.672 0.438 1.062s-0.156 0.781-0.438 1.062l-4.594 4.594 4.594 4.594c0.281 0.281 0.438 0.672 0.438 1.062z" }))),
                    this.isRunning ? (h("div", { class: 'btn-pause', onClick: () => this.pause() },
                        h("svg", { version: "1.1", xmlns: "http://www.w3.org/2000/svg", width: "22", height: "22", viewBox: "0 0 22 22" },
                            h("title", null, "pause"),
                            h("path", { d: "M2.75 2.75h6.875v16.5h-6.875zM12.375 2.75h6.875v16.5h-6.875z" })))) : (h("div", { class: 'btn-play', onClick: () => this.run() },
                        h("svg", { version: "1.1", xmlns: "http://www.w3.org/2000/svg", width: "22", height: "22", viewBox: "0 0 22 22" },
                            h("title", null, "play"),
                            h("path", { d: "M4.125 2.75l13.75 8.25-13.75 8.25z" }))))),
                h("ema-card-content", { class: 'url-list' }, this.type === 'dwp' &&
                    h("ul", null, this.history.map((item, i) => h("li", { "data-index": i, onClick: (e) => this.onListItemClick(i, false) }, item.type + ': ' + item.config.url.replace(this.apiUrl, ''))))),
                h("ema-card-bottom", null,
                    h("ema-collapsible", { label: this.viewerLabel, collapsed: false },
                        h("div", null,
                            this.currentItem && !this.currentItem.response &&
                                h("div", null,
                                    h("div", null,
                                        "request: ",
                                        this.currentItem.config.method),
                                    h("ema-json-viewer", { "data-json": JSON.stringify(this.currentItem.config), "allow-copy": 'true', "max-level": this.maxLevel || -1, "collapse-at": this.collapseAt || -1 })),
                            this.currentItem && this.currentItem.response &&
                                h("div", null,
                                    h("div", null, "response:"),
                                    h("ema-json-viewer", { "data-json": JSON.stringify(this.currentItem.response), "allow-copy": 'true', "max-level": this.maxLevel || -1, "collapse-at": this.collapseAt || -1 }))))))));
    }
    static get is() { return "ema-debugger"; }
    static get properties() { return {
        "apiUrl": {
            "type": String,
            "attr": "api-url"
        },
        "close": {
            "method": true
        },
        "collapseAt": {
            "type": Number,
            "attr": "collapse-at"
        },
        "currentItem": {
            "state": true
        },
        "data": {
            "state": true
        },
        "dataJson": {
            "type": String,
            "attr": "data-json"
        },
        "historySize": {
            "type": Number,
            "attr": "history-size"
        },
        "host": {
            "elementRef": true
        },
        "isActive": {
            "state": true
        },
        "isOpen": {
            "state": true
        },
        "isRunning": {
            "state": true
        },
        "jsonLoaded": {
            "state": true
        },
        "jsonUrl": {
            "type": String,
            "attr": "json-url"
        },
        "maxLevel": {
            "type": Number,
            "attr": "max-level"
        },
        "open": {
            "method": true
        },
        "pause": {
            "method": true
        },
        "run": {
            "method": true
        },
        "toggle": {
            "method": true
        },
        "type": {
            "type": String,
            "attr": "type"
        }
    }; }
    static get style() { return "ema-debugger{display:none;border:var(--ema-border,#c5c9cd);position:absolute;top:55px;right:7.5px;min-width:50%;max-width:50%;z-index:9999}ema-debugger ema-card{background:var(--ema-background,#fff)!important}ema-debugger .btn-close{position:absolute;right:30px;top:11px;cursor:pointer}ema-debugger .btn-pause,ema-debugger .btn-play{position:absolute;right:70px;top:15px;cursor:pointer}ema-debugger ema-card-content.url-list ul{list-style-type:none;font-size:90%;padding-left:0;overflow-y:scroll;max-height:200px;min-height:200px;-webkit-box-shadow:var(--ema-box-shadow,1px 1px 10px 1px #ccc);box-shadow:var(--ema-box-shadow,1px 1px 10px 1px #ccc)}ema-debugger ema-card-content.url-list ul li{padding-left:var(--ema-padding-md,1rem);cursor:pointer}ema-debugger ema-card-content.url-list ul .active{background:#fff}ema-debugger ema-collapsible{display:block;-ms-transform:scale(.8);-webkit-transform:scale(.8);transform:scale(.8);-webkit-transform-origin:top left;transform-origin:top left;width:125%}"; }
}

const originalOptions = Object.freeze({
    "prefixClass": "dndod",
    "title": "",
    "msg": "",
    "confirmLabel": "OK",
    "cancelLabel": "Cancel",
    "continueLabel": "Continue",
    "textAlign": "center",
    "animation": "from-top",
    "animationDuration": 400,
    "disableCloseBtn": false,
    "disableOutline": false,
    "enableHTML": false,
    "allowClose": true,
    "hostElement": null,
    "events": {
        "create": null,
        "mount": null,
        "close": null,
        "unmount": null
    },
    "buttons": []
});
class Popup {
    constructor(options) {
        this.$wrapper = null;
        this.$popup = null;
        this.$customBtnWrapper = null;
        this.$previousActiveElement = document['activeElement'] || null;
        this.openTimeout = undefined;
        this.closeTimeout = undefined;
        this.resizeHandler = null;
        let mergedOptions = Object.assign({}, originalOptions);
        this.options = Object.assign(mergedOptions, options);
        typeof this.options.events.create === "function" && this.options.events.create();
    }
    render(msg = "", title = "") {
        this.$wrapper = this.createWrapper();
        this.$popup = this.createPopup(msg, title);
        this.$wrapper.appendChild(this.$popup);
        if (this.options.buttons.length > 0) {
            this.$wrapper.classList.add([this.options.prefixClass, "has-btn"].join("-"));
            this.$customBtnWrapper = this.createCustomBtnWrapper();
            this.options.buttons.forEach(this.createCustomBtn.bind(this));
        }
        if (this.options.disableCloseBtn !== true) {
            this.$popup.appendChild(this.createCloseBtn());
        }
        this.$popup.appendChild(this.createFocusTrap());
    }
    createWrapper() {
        let $wrapper = document.createElement("div");
        $wrapper.classList.add([this.options.prefixClass, "wrapper"].join("-"));
        $wrapper.classList.add([this.options.prefixClass, "animate", this.options.animation].join("-"));
        $wrapper.classList.toggle([this.options.prefixClass, "no-outline"].join("-"), this.options.disableOutline === true);
        if (this.options.animationDuration !== 250) {
            $wrapper.style.transitionDuration = parseInt(this.options.animationDuration, 10) / 1000 + "s";
        }
        $wrapper.setAttribute("tabindex", "0");
        $wrapper['dndodKeydownHandler'] = (e) => {
            e.stopPropagation();
            if (e.keyCode === 27) {
                this.close();
            }
        };
        $wrapper['dndodClickHandler'] = (e) => {
            e.stopPropagation();
            this.close();
        };
        if (this.options.allowClose) {
            $wrapper.addEventListener("keydown", $wrapper['dndodKeydownHandler']);
            $wrapper.addEventListener("click", $wrapper['dndodClickHandler']);
        }
        return $wrapper;
    }
    createPopup(msg, title) {
        let contentProperty = this.options.enableHTML === true ? "innerHTML" : "innerText";
        let $popup = document.createElement("div");
        $popup.classList.add([this.options.prefixClass, "popup"].join("-"));
        $popup.classList.toggle([this.options.prefixClass, "text", this.options.textAlign].join("-"), this.options.textAlign !== "center");
        if (this.options.animationDuration !== 250) {
            $popup.style.transitionDuration = parseInt(this.options.animationDuration, 10) / 1000 + "s";
        }
        $popup.setAttribute("tabindex", "0");
        $popup['dndodClickHandler'] = (e) => {
            e.stopPropagation();
        };
        $popup.addEventListener("click", $popup['dndodClickHandler']);
        let $title = document.createElement("h1");
        $title.classList.add([this.options.prefixClass, "heading"].join("-"));
        $title[contentProperty] = `${title}`;
        $popup.appendChild($title);
        let $message = document.createElement("p");
        $message.classList.add([this.options.prefixClass, "body"].join("-"));
        if (msg instanceof HTMLElement) {
            $message.appendChild(msg);
        }
        else {
            $message[contentProperty] = `${msg}`;
        }
        $popup.appendChild($message);
        return $popup;
    }
    createCloseBtn() {
        let $closeBtn = document.createElement("button");
        $closeBtn.innerHTML = "&times;";
        $closeBtn.setAttribute("title", "Close this popup");
        $closeBtn.classList.add([this.options.prefixClass, "btn-close"].join("-"));
        $closeBtn['dndodClickHandler'] = (e) => {
            e.stopPropagation();
            this.close();
        };
        $closeBtn.addEventListener("click", $closeBtn['dndodClickHandler']);
        return $closeBtn;
    }
    createCustomBtnWrapper() {
        let $customBtnWrapper = document.createElement("div");
        $customBtnWrapper.classList.add([this.options.prefixClass, "custom-btn-wrapper"].join("-"));
        return $customBtnWrapper;
    }
    createCustomBtn(buttonInfo, index, buttons) {
        let $customBtn = document.createElement("button");
        $customBtn.innerHTML = buttonInfo.text;
        $customBtn.classList.add([this.options.prefixClass, "btn-custom"].join("-"));
        buttonInfo.type = buttonInfo.type || "default";
        $customBtn.classList.add([this.options.prefixClass, "btn", buttonInfo.type].join("-"));
        if (typeof buttonInfo.handler === "function") {
            $customBtn['dndodClickHandler'] = (e) => {
                e.stopPropagation();
                buttonInfo.handler(e, this);
            };
            $customBtn.addEventListener("click", $customBtn['dndodClickHandler']);
        }
        this.$customBtnWrapper.appendChild($customBtn);
        buttons[index].$button = $customBtn;
        if (index === buttons.length - 1) {
            this.$popup.appendChild(this.$customBtnWrapper);
        }
    }
    createFocusTrap() {
        let $trap = document.createElement("span");
        $trap.setAttribute("tabindex", "0");
        $trap.addEventListener("focus", (e) => {
            e.stopPropagation();
            this.$popup.focus();
        });
        return $trap;
    }
    watchScreenResize() {
        let classList = this.$wrapper.classList, oversizeClass = [this.options.prefixClass, "oversize"].join("-");
        (this.$popup.offsetHeight > window.innerHeight - 60) ? classList.add(oversizeClass) : classList.remove(oversizeClass);
    }
    removeAllEventHandler() {
        window.removeEventListener("resize", this.resizeHandler);
        this.$popup.removeEventListener("click", this.$popup['dndodClickHandler']);
        this.$wrapper.removeEventListener("keydown", this.$wrapper.dndodKeydownHandler);
        this.$wrapper.removeEventListener("click", this.$wrapper['dndodClickHandler']);
        this.options.buttons.forEach(function (buttonInfo) {
            buttonInfo.$button.removeEventListener("click", buttonInfo.$button['dndodClickHandler']);
        });
    }
    open() {
        this.$previousActiveElement !== null && this.$previousActiveElement['blur']();
        this.render(this.options.msg, this.options.title);
        this.options.animation === "none" && this.$wrapper.classList.add([this.options.prefixClass, "status-show"].join("-"));
        document.body.appendChild(this.$wrapper);
        setTimeout(() => {
            typeof this.options.events.mount === "function" && this.options.events.mount();
            this.options.animation !== "none" && this.$wrapper.classList.add([this.options.prefixClass, "status-show"].join("-"));
        });
        if (this.options.animation === "none") {
            this.$popup.focus();
        }
        else {
            this.openTimeout = setTimeout(() => {
                this.$popup.focus();
            }, this.options.animationDuration);
        }
        this.watchScreenResize();
        this.resizeHandler = this.watchScreenResize.bind(this);
        window.addEventListener("resize", this.resizeHandler);
    }
    close() {
        typeof this.options.events.close === "function" && this.options.events.close();
        this.openTimeout && clearTimeout(this.openTimeout);
        this.removeAllEventHandler();
        if (this.options.animation === "none") {
            this.remove();
        }
        else {
            this.$wrapper.classList.remove([this.options.prefixClass, "status-show"].join("-"));
            this.closeTimeout = setTimeout(() => {
                this.remove();
            }, this.options.animationDuration);
        }
    }
    remove() {
        this.$previousActiveElement !== null && this.$previousActiveElement['focus']();
        this.$wrapper.parentNode.removeChild(this.$wrapper);
        setTimeout(() => {
            typeof this.options.events.unmount === "function" && this.options.events.unmount();
        });
    }
}
const popup = (options = {}) => {
    let pop = new Popup(options);
    pop.open();
};
const notice = (msg = "", options = {}) => {
    options['msg'] = msg;
    let pop = new Popup(options);
    pop.open();
};
const alert = (msg = "", options = {}) => {
    options['msg'] = msg;
    options['buttons'] = [
        {
            text: options['confirmLabel'],
            type: "primary",
            handler: function (e, popup) {
                popup.close();
            }
        }
    ];
    let pop = new Popup(options);
    pop.open();
};
const confirm = (msg = "", calllback = function () { }, options = {}) => {
    options['msg'] = msg;
    options['buttons'] = [
        {
            text: options['cancelLabel'],
            handler: function (e, popup) {
                popup.close();
            }
        },
        {
            text: options['continueLabel'],
            type: "primary",
            handler: function (e, popup) {
                popup.close();
                calllback();
            }
        }
    ];
    let pop = new Popup(options);
    pop.open();
};
var dndod = {
    popup,
    notice,
    alert,
    confirm
};

class Dialog {
    constructor() {
        this.index = 0;
        this.confirmLabel = 'Ok';
        this.cancelLabel = 'Cancel';
        this.continueLabel = 'Yes';
        this.allowClose = true;
    }
    getOptions() {
        return {
            confirmLabel: this.confirmLabel,
            cancelLabel: this.cancelLabel,
            continueLabel: this.continueLabel,
            allowClose: this.allowClose,
            disableCloseBtn: !this.allowClose,
            enableHTML: true,
            hostElement: this.host
        };
    }
    async popup(options = {}) {
        options = Object.assign(options, this.getOptions());
        dndod.popup(options);
    }
    async notice(msg = "", options = {}) {
        options = Object.assign(options, this.getOptions());
        dndod.notice(msg, options);
    }
    async alert(msg = "", options = {}) {
        options = Object.assign(options, this.getOptions());
        dndod.alert(msg, options);
    }
    ;
    async confirm(msg = "", calllback = this.dialogConfirmHandler, options = {}) {
        options = Object.assign(options, this.getOptions());
        dndod.confirm(msg, calllback, options);
    }
    async setConfirmHandler(callBackHandler) {
        this.dialogConfirmHandler = callBackHandler;
    }
    dialogConfirmHandler() {
        if (this && this.dialogConfirmCallback) {
            this.dialogConfirmCallback();
        }
    }
    render() {
        return (h("div", null));
    }
    static get is() { return "ema-dialog"; }
    static get properties() { return {
        "alert": {
            "method": true
        },
        "allowClose": {
            "type": Boolean,
            "attr": "allow-close"
        },
        "cancelLabel": {
            "type": String,
            "attr": "cancel-label"
        },
        "confirm": {
            "method": true
        },
        "confirmLabel": {
            "type": String,
            "attr": "confirm-label"
        },
        "continueLabel": {
            "type": String,
            "attr": "continue-label"
        },
        "host": {
            "elementRef": true
        },
        "index": {
            "state": true
        },
        "notice": {
            "method": true
        },
        "popup": {
            "method": true
        },
        "setConfirmHandler": {
            "method": true
        }
    }; }
    static get style() { return ".dndod-wrapper{overflow:auto;position:fixed;top:0;left:0;right:0;bottom:0;z-index:9998;background-color:transparent;-webkit-transition-property:background-color;transition-property:background-color;-webkit-transform:translateZ(0);transform:translateZ(0)}.dndod-wrapper,.dndod-wrapper .dndod-popup{-webkit-transition-duration:.25s;transition-duration:.25s}.dndod-wrapper .dndod-popup{border-radius:var(--ema-border-radius,3px);background:var(--ema-background,#fff);position:absolute;top:50%;left:50%;z-index:9999;min-width:260px;max-width:100%;min-height:70px;padding:40px 50px;text-align:center;-webkit-box-shadow:var(--ema-box-shadow,1px 1px 10px 1px #ccc);box-shadow:var(--ema-box-shadow,1px 1px 10px 1px #ccc);-webkit-transform:translate(-50%,-50%);transform:translate(-50%,-50%);-webkit-transition-property:top;transition-property:top}.dndod-wrapper .dndod-popup .dndod-btn-close{display:block;overflow:hidden;position:absolute;top:3px;right:3px;width:30px;height:30px;margin:0;padding:0;border:0;font-family:sans-serif;font-size:2em;font-weight:lighter;line-height:1em;color:#c5c5c5;background-color:#fff;text-align:center;cursor:pointer}.dndod-wrapper .dndod-popup .dndod-btn-close:focus,.dndod-wrapper .dndod-popup .dndod-btn-close:hover{color:#929292}.dndod-wrapper .dndod-popup .dndod-btn-close:active{color:#797979}.dndod-wrapper .dndod-popup .dndod-heading{font-size:1.4em;margin:0 0 20px}.dndod-wrapper .dndod-popup .dndod-body{font-size:1.2em;line-height:1.4em;margin:20px 0}.dndod-wrapper .dndod-popup.dndod-text-left{text-align:left}.dndod-wrapper.dndod-status-show{background-color:rgba(0,0,0,.3)}.dndod-wrapper.dndod-animate-from-top .dndod-popup{top:-50%}.dndod-wrapper.dndod-animate-from-bottom .dndod-popup{top:150%}.dndod-wrapper.dndod-animate-from-bottom.dndod-status-show .dndod-popup,.dndod-wrapper.dndod-animate-from-top.dndod-status-show .dndod-popup{top:50%}.dndod-wrapper.dndod-oversize .dndod-popup{-webkit-transform:translate(-50%);transform:translate(-50%)}.dndod-wrapper.dndod-oversize.dndod-status-show .dndod-popup{margin:30px 0;top:0!important;-webkit-transition:none;transition:none}.dndod-wrapper.dndod-has-btn .dndod-popup{padding-bottom:90px}.dndod-wrapper.dndod-no-outline .dndod-popup,.dndod-wrapper.dndod-no-outline .dndod-popup button{outline:0 none}.dndod-custom-btn-wrapper{display:-ms-flexbox;display:flex;position:absolute;left:0;right:0;bottom:0;height:60px;-ms-flex-direction:row;flex-direction:row;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center}.dndod-custom-btn-wrapper .dndod-btn-custom{-ms-flex:auto;flex:auto;-ms-flex-positive:1;flex-grow:1;-ms-flex-preferred-size:0;flex-basis:0;width:auto;height:100%;border:0;margin:0;padding:0;font-size:1.1em;cursor:pointer}.dndod-custom-btn-wrapper .dndod-btn-custom:focus,.dndod-custom-btn-wrapper .dndod-btn-custom:hover{background-color:#ddd}.dndod-custom-btn-wrapper .dndod-btn-custom:active{background-color:#d1d1d1}.dndod-custom-btn-wrapper .dndod-btn-custom.dndod-btn-default{background-color:#d8d8d8;color:#000}.dndod-custom-btn-wrapper .dndod-btn-custom.dndod-btn-default:focus,.dndod-custom-btn-wrapper .dndod-btn-custom.dndod-btn-default:hover{background-color:#cbcbcb}.dndod-custom-btn-wrapper .dndod-btn-custom.dndod-btn-default:active{background-color:#bfbfbf}.dndod-custom-btn-wrapper .dndod-btn-custom.dndod-btn-kakaobank{background-color:#ffde00;color:#000}.dndod-custom-btn-wrapper .dndod-btn-custom.dndod-btn-kakaobank:focus,.dndod-custom-btn-wrapper .dndod-btn-custom.dndod-btn-kakaobank:hover{background-color:#e6c800}.dndod-custom-btn-wrapper .dndod-btn-custom.dndod-btn-kakaobank:active{background-color:#ccb200}.dndod-custom-btn-wrapper .dndod-btn-custom.dndod-btn-primary{background-color:var(--ema-primary,#007bff);color:var(--ema-light,#f8f9fa)}.dndod-custom-btn-wrapper .dndod-btn-custom.dndod-btn-primary:focus,.dndod-custom-btn-wrapper .dndod-btn-custom.dndod-btn-primary:hover{background:-webkit-gradient(linear,left bottom,left top,from(rgba(0,0,0,.05)),to(rgba(0,0,0,.05))) var(--ema-primary,#007bff);background:linear-gradient(0deg,rgba(0,0,0,.05),rgba(0,0,0,.05)) var(--ema-primary,#007bff)}.dndod-custom-btn-wrapper .dndod-btn-custom.dndod-btn-primary:active{background:-webkit-gradient(linear,left bottom,left top,from(rgba(0,0,0,.1)),to(rgba(0,0,0,.1))) var(--ema-primary,#007bff);background:linear-gradient(0deg,rgba(0,0,0,.1),rgba(0,0,0,.1)) var(--ema-primary,#007bff)}.dndod-custom-btn-wrapper .dndod-btn-custom.dndod-btn-danger{background-color:var(--ema-danger,#dc3545);color:var(--ema-color,#343a40)}.dndod-custom-btn-wrapper .dndod-btn-custom.dndod-btn-danger:focus,.dndod-custom-btn-wrapper .dndod-btn-custom.dndod-btn-danger:hover{background:-webkit-gradient(linear,left bottom,left top,from(rgba(0,0,0,.05)),to(rgba(0,0,0,.05))) var(--ema-danger,#dc3545);background:linear-gradient(0deg,rgba(0,0,0,.05),rgba(0,0,0,.05)) var(--ema-danger,#dc3545)}.dndod-custom-btn-wrapper .dndod-btn-custom.dndod-btn-danger:active{background:-webkit-gradient(linear,left bottom,left top,from(rgba(0,0,0,.1)),to(rgba(0,0,0,.1))) var(--ema-danger,#dc3545);background:linear-gradient(0deg,rgba(0,0,0,.1),rgba(0,0,0,.1)) var(--ema-danger,#dc3545)}.dndod-custom-btn-wrapper .dndod-btn-custom.dndod-btn-warning{background-color:#ffdd57;color:rgba(0,0,0,.7)}.dndod-custom-btn-wrapper .dndod-btn-custom.dndod-btn-warning:focus,.dndod-custom-btn-wrapper .dndod-btn-custom.dndod-btn-warning:hover{background-color:#ffd83e}.dndod-custom-btn-wrapper .dndod-btn-custom.dndod-btn-warning:active{background-color:#ffd324}.dndod-custom-btn-wrapper .dndod-btn-custom.dndod-btn-success{background-color:var(--ema-success,#28a745);color:var(--ema-color,#343a40)}.dndod-custom-btn-wrapper .dndod-btn-custom.dndod-btn-success:focus,.dndod-custom-btn-wrapper .dndod-btn-custom.dndod-btn-success:hover{background:-webkit-gradient(linear,left bottom,left top,from(rgba(0,0,0,.05)),to(rgba(0,0,0,.05))) var(--ema-success,#28a745);background:linear-gradient(0deg,rgba(0,0,0,.05),rgba(0,0,0,.05)) var(--ema-success,#28a745)}.dndod-custom-btn-wrapper .dndod-btn-custom.dndod-btn-success:active{background:-webkit-gradient(linear,left bottom,left top,from(rgba(0,0,0,.1)),to(rgba(0,0,0,.1))) var(--ema-success,#28a745);background:linear-gradient(0deg,rgba(0,0,0,.1),rgba(0,0,0,.1)) var(--ema-success,#28a745)}.dndod-custom-btn-wrapper .dndod-btn-custom.dndod-btn-info{background-color:var(--ema-primary,#007bff);color:var(--ema-color,#343a40)}.dndod-custom-btn-wrapper .dndod-btn-custom.dndod-btn-info:focus,.dndod-custom-btn-wrapper .dndod-btn-custom.dndod-btn-info:hover{background:-webkit-gradient(linear,left bottom,left top,from(rgba(0,0,0,.05)),to(rgba(0,0,0,.05))) var(--ema-primary,#007bff);background:linear-gradient(0deg,rgba(0,0,0,.05),rgba(0,0,0,.05)) var(--ema-primary,#007bff)}.dndod-custom-btn-wrapper .dndod-btn-custom.dndod-btn-info:active{background:-webkit-gradient(linear,left bottom,left top,from(rgba(0,0,0,.1)),to(rgba(0,0,0,.1))) var(--ema-primary,#007bff);background:linear-gradient(0deg,rgba(0,0,0,.1),rgba(0,0,0,.1)) var(--ema-primary,#007bff)}"; }
}

class FlashMessage {
    constructor() {
        this.active = false;
        this.activeClass = 'primary';
    }
    async show(message, activeClass, duration = 2000) {
        this.message = message;
        this.activeClass = activeClass;
        this.active = true;
        DomUtil.fadeIn(this.el, 150, 0, 'flex');
        this.timeout = setTimeout(() => {
            this.active = false;
        }, duration);
    }
    dismiss() {
        this.active = false;
        DomUtil.fadeOut(this.el, 150, 0);
        clearTimeout(this.timeout);
    }
    render() {
        return (h("div", { onClick: () => this.dismiss(), class: 'flash-container ' + (this.active ? 'show ' : 'hide ') + this.activeClass },
            h("div", { class: "message" }, this.message),
            h("p", { class: "dismiss" }, "tap to dismiss")));
    }
    static get is() { return "ema-flash-message"; }
    static get properties() { return {
        "active": {
            "state": true
        },
        "activeClass": {
            "state": true
        },
        "el": {
            "elementRef": true
        },
        "message": {
            "state": true
        },
        "show": {
            "method": true
        }
    }; }
    static get style() { return "ema-flash-message{position:fixed;z-index:31000;top:0;left:50%;-webkit-transition:opacity .7s;transition:opacity .7s;display:none;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center}ema-flash-message .flash-container{background-color:#000;border-radius:var(--ema-border-radius);display:block;min-height:56px;min-width:360px;max-width:480px;color:var(--ema-light);margin:0 auto 0 -50%;padding:var(--ema-padding,.5rem);text-align:center}ema-flash-message .show{display:block;opacity:1}ema-flash-message .hide{display:none;opacity:0}ema-flash-message .dismiss{cursor:pointer;position:absolute;min-width:360px;bottom:var(--ema-padding,.5rem);margin:0 auto;font-size:.7em;opacity:.5;text-align:center}ema-flash-message .primary{background-color:var(--ema-primary)}ema-flash-message .secondary,ema-flash-message .success{background-color:var(--ema-success)}ema-flash-message .danger{background-color:var(--ema-danger)}ema-flash-message .light{background-color:var(--ema-background,#fff)}ema-flash-message .dark{background-color:var(--ema-background-diap)}"; }
}

class Route {
    constructor() {
        this.exact = false;
    }
    componentDidLoad() {
        this.el.style.display = "none";
    }
    async getUrl() {
        return this.url;
    }
    render() {
        return (h("div", null));
    }
    static get is() { return "ema-route"; }
    static get properties() { return {
        "action": {
            "type": String,
            "attr": "action"
        },
        "actionParams": {
            "type": String,
            "attr": "action-params"
        },
        "component": {
            "type": String,
            "attr": "component"
        },
        "componentProps": {
            "type": String,
            "attr": "component-props"
        },
        "el": {
            "elementRef": true
        },
        "exact": {
            "type": Boolean,
            "attr": "exact"
        },
        "getUrl": {
            "method": true
        },
        "state": {
            "state": true
        },
        "url": {
            "type": String,
            "attr": "url"
        }
    }; }
}

var isarray = Array.isArray || function (arr) {
  return Object.prototype.toString.call(arr) == '[object Array]';
};

/**
 * Expose `pathToRegexp`.
 */
var pathToRegexp_1 = pathToRegexp;
var parse_1 = parse;
var compile_1 = compile;
var tokensToFunction_1 = tokensToFunction;
var tokensToRegExp_1 = tokensToRegExp;

/**
 * The main path matching regexp utility.
 *
 * @type {RegExp}
 */
var PATH_REGEXP = new RegExp([
  // Match escaped characters that would otherwise appear in future matches.
  // This allows the user to escape special characters that won't transform.
  '(\\\\.)',
  // Match Express-style parameters and un-named parameters with a prefix
  // and optional suffixes. Matches appear as:
  //
  // "/:test(\\d+)?" => ["/", "test", "\d+", undefined, "?", undefined]
  // "/route(\\d+)"  => [undefined, undefined, undefined, "\d+", undefined, undefined]
  // "/*"            => ["/", undefined, undefined, undefined, undefined, "*"]
  '([\\/.])?(?:(?:\\:(\\w+)(?:\\(((?:\\\\.|[^()])+)\\))?|\\(((?:\\\\.|[^()])+)\\))([+*?])?|(\\*))'
].join('|'), 'g');

/**
 * Parse a string for the raw tokens.
 *
 * @param  {String} str
 * @return {Array}
 */
function parse (str) {
  var tokens = [];
  var key = 0;
  var index = 0;
  var path = '';
  var res;

  while ((res = PATH_REGEXP.exec(str)) != null) {
    var m = res[0];
    var escaped = res[1];
    var offset = res.index;
    path += str.slice(index, offset);
    index = offset + m.length;

    // Ignore already escaped sequences.
    if (escaped) {
      path += escaped[1];
      continue
    }

    // Push the current path onto the tokens.
    if (path) {
      tokens.push(path);
      path = '';
    }

    var prefix = res[2];
    var name = res[3];
    var capture = res[4];
    var group = res[5];
    var suffix = res[6];
    var asterisk = res[7];

    var repeat = suffix === '+' || suffix === '*';
    var optional = suffix === '?' || suffix === '*';
    var delimiter = prefix || '/';
    var pattern = capture || group || (asterisk ? '.*' : '[^' + delimiter + ']+?');

    tokens.push({
      name: name || key++,
      prefix: prefix || '',
      delimiter: delimiter,
      optional: optional,
      repeat: repeat,
      pattern: escapeGroup(pattern)
    });
  }

  // Match any characters still remaining.
  if (index < str.length) {
    path += str.substr(index);
  }

  // If the path exists, push it onto the end.
  if (path) {
    tokens.push(path);
  }

  return tokens
}

/**
 * Compile a string to a template function for the path.
 *
 * @param  {String}   str
 * @return {Function}
 */
function compile (str) {
  return tokensToFunction(parse(str))
}

/**
 * Expose a method for transforming tokens into the path function.
 */
function tokensToFunction (tokens) {
  // Compile all the tokens into regexps.
  var matches = new Array(tokens.length);

  // Compile all the patterns before compilation.
  for (var i = 0; i < tokens.length; i++) {
    if (typeof tokens[i] === 'object') {
      matches[i] = new RegExp('^' + tokens[i].pattern + '$');
    }
  }

  return function (obj) {
    var path = '';
    var data = obj || {};

    for (var i = 0; i < tokens.length; i++) {
      var token = tokens[i];

      if (typeof token === 'string') {
        path += token;

        continue
      }

      var value = data[token.name];
      var segment;

      if (value == null) {
        if (token.optional) {
          continue
        } else {
          throw new TypeError('Expected "' + token.name + '" to be defined')
        }
      }

      if (isarray(value)) {
        if (!token.repeat) {
          throw new TypeError('Expected "' + token.name + '" to not repeat, but received "' + value + '"')
        }

        if (value.length === 0) {
          if (token.optional) {
            continue
          } else {
            throw new TypeError('Expected "' + token.name + '" to not be empty')
          }
        }

        for (var j = 0; j < value.length; j++) {
          segment = encodeURIComponent(value[j]);

          if (!matches[i].test(segment)) {
            throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '", but received "' + segment + '"')
          }

          path += (j === 0 ? token.prefix : token.delimiter) + segment;
        }

        continue
      }

      segment = encodeURIComponent(value);

      if (!matches[i].test(segment)) {
        throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but received "' + segment + '"')
      }

      path += token.prefix + segment;
    }

    return path
  }
}

/**
 * Escape a regular expression string.
 *
 * @param  {String} str
 * @return {String}
 */
function escapeString (str) {
  return str.replace(/([.+*?=^!:${}()[\]|\/])/g, '\\$1')
}

/**
 * Escape the capturing group by escaping special characters and meaning.
 *
 * @param  {String} group
 * @return {String}
 */
function escapeGroup (group) {
  return group.replace(/([=!:$\/()])/g, '\\$1')
}

/**
 * Attach the keys as a property of the regexp.
 *
 * @param  {RegExp} re
 * @param  {Array}  keys
 * @return {RegExp}
 */
function attachKeys (re, keys) {
  re.keys = keys;
  return re
}

/**
 * Get the flags for a regexp from the options.
 *
 * @param  {Object} options
 * @return {String}
 */
function flags (options) {
  return options.sensitive ? '' : 'i'
}

/**
 * Pull out keys from a regexp.
 *
 * @param  {RegExp} path
 * @param  {Array}  keys
 * @return {RegExp}
 */
function regexpToRegexp (path, keys) {
  // Use a negative lookahead to match only capturing groups.
  var groups = path.source.match(/\((?!\?)/g);

  if (groups) {
    for (var i = 0; i < groups.length; i++) {
      keys.push({
        name: i,
        prefix: null,
        delimiter: null,
        optional: false,
        repeat: false,
        pattern: null
      });
    }
  }

  return attachKeys(path, keys)
}

/**
 * Transform an array into a regexp.
 *
 * @param  {Array}  path
 * @param  {Array}  keys
 * @param  {Object} options
 * @return {RegExp}
 */
function arrayToRegexp (path, keys, options) {
  var parts = [];

  for (var i = 0; i < path.length; i++) {
    parts.push(pathToRegexp(path[i], keys, options).source);
  }

  var regexp = new RegExp('(?:' + parts.join('|') + ')', flags(options));

  return attachKeys(regexp, keys)
}

/**
 * Create a path regexp from string input.
 *
 * @param  {String} path
 * @param  {Array}  keys
 * @param  {Object} options
 * @return {RegExp}
 */
function stringToRegexp (path, keys, options) {
  var tokens = parse(path);
  var re = tokensToRegExp(tokens, options);

  // Attach keys back to the regexp.
  for (var i = 0; i < tokens.length; i++) {
    if (typeof tokens[i] !== 'string') {
      keys.push(tokens[i]);
    }
  }

  return attachKeys(re, keys)
}

/**
 * Expose a function for taking tokens and returning a RegExp.
 *
 * @param  {Array}  tokens
 * @param  {Array}  keys
 * @param  {Object} options
 * @return {RegExp}
 */
function tokensToRegExp (tokens, options) {
  options = options || {};

  var strict = options.strict;
  var end = options.end !== false;
  var route = '';
  var lastToken = tokens[tokens.length - 1];
  var endsWithSlash = typeof lastToken === 'string' && /\/$/.test(lastToken);

  // Iterate over the tokens and create our regexp string.
  for (var i = 0; i < tokens.length; i++) {
    var token = tokens[i];

    if (typeof token === 'string') {
      route += escapeString(token);
    } else {
      var prefix = escapeString(token.prefix);
      var capture = token.pattern;

      if (token.repeat) {
        capture += '(?:' + prefix + capture + ')*';
      }

      if (token.optional) {
        if (prefix) {
          capture = '(?:' + prefix + '(' + capture + '))?';
        } else {
          capture = '(' + capture + ')?';
        }
      } else {
        capture = prefix + '(' + capture + ')';
      }

      route += capture;
    }
  }

  // In non-strict mode we allow a slash at the end of match. If the path to
  // match already ends with a slash, we remove it for consistency. The slash
  // is valid at the end of a path match, not in the middle. This is important
  // in non-ending mode, where "/test/" shouldn't match "/test//route".
  if (!strict) {
    route = (endsWithSlash ? route.slice(0, -2) : route) + '(?:\\/(?=$))?';
  }

  if (end) {
    route += '$';
  } else {
    // In non-ending mode, we need the capturing groups to match as much as
    // possible by using a positive lookahead to the end or next path segment.
    route += strict && endsWithSlash ? '' : '(?=\\/|$)';
  }

  return new RegExp('^' + route, flags(options))
}

/**
 * Normalize the given path string, returning a regular expression.
 *
 * An empty array can be passed in for the keys, which will hold the
 * placeholder key descriptions. For example, using `/user/:id`, `keys` will
 * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.
 *
 * @param  {(String|RegExp|Array)} path
 * @param  {Array}                 [keys]
 * @param  {Object}                [options]
 * @return {RegExp}
 */
function pathToRegexp (path, keys, options) {
  keys = keys || [];

  if (!isarray(keys)) {
    options = keys;
    keys = [];
  } else if (!options) {
    options = {};
  }

  if (path instanceof RegExp) {
    return regexpToRegexp(path, keys, options)
  }

  if (isarray(path)) {
    return arrayToRegexp(path, keys, options)
  }

  return stringToRegexp(path, keys, options)
}

pathToRegexp_1.parse = parse_1;
pathToRegexp_1.compile = compile_1;
pathToRegexp_1.tokensToFunction = tokensToFunction_1;
pathToRegexp_1.tokensToRegExp = tokensToRegExp_1;

/**
   * Module dependencies.
   */

  

  /**
   * Short-cuts for global-object checks
   */

  var hasDocument = ('undefined' !== typeof document);
  var hasWindow = ('undefined' !== typeof window);
  var hasHistory = ('undefined' !== typeof history);
  var hasProcess = typeof process !== 'undefined';

  /**
   * Detect click event
   */
  var clickEvent = hasDocument && document.ontouchstart ? 'touchstart' : 'click';

  /**
   * To work properly with the URL
   * history.location generated polyfill in https://github.com/devote/HTML5-History-API
   */

  var isLocation = hasWindow && !!(window.history.location || window.location);

  /**
   * The page instance
   * @api private
   */
  function Page(options) {
    // public things
    this.callbacks = [];
    this.exits = [];
    this.current = '';
    this.len = 0;

    // private things
    this._dispatch = true;
    this._decodeURLComponents = true;
    this._base = '';
    this._strict = false;
    this._running = false;
    this._hashbang = false;

    // bound functions
    this._onclick = this._onclick.bind(this);
    this._onpopstate = this._onpopstate.bind(this);

    this.configure(options);
  }

  /**
   * Configure the instance of page. This can be called multiple times.
   *
   * @param {Object} options
   * @api public
   */

  Page.prototype.configure = function(options) {
    var opts = options || {};

    this._window = opts.window || (hasWindow && window);
    this._dispatch = opts.dispatch !== false;
    this._decodeURLComponents = opts.decodeURLComponents !== false;
    this._popstate = opts.popstate !== false && hasWindow;
    this._click = opts.click !== false && hasDocument;
    this._hashbang = !!opts.hashbang;

    var _window = this._window;
    if(this._popstate) {
      _window.addEventListener('popstate', this._onpopstate, false);
    } else if(hasWindow) {
      _window.removeEventListener('popstate', this._onpopstate, false);
    }

    if (this._click) {
      _window.document.addEventListener(clickEvent, this._onclick, false);
    } else if(hasDocument) {
      _window.document.removeEventListener(clickEvent, this._onclick, false);
    }

    if(this._hashbang && hasWindow && !hasHistory) {
      _window.addEventListener('hashchange', this._onpopstate, false);
    } else if(hasWindow) {
      _window.removeEventListener('hashchange', this._onpopstate, false);
    }
  };

  /**
   * Get or set basepath to `path`.
   *
   * @param {string} path
   * @api public
   */

  Page.prototype.base = function(path) {
    if (0 === arguments.length) return this._base;
    this._base = path;
  };

  /**
   * Gets the `base`, which depends on whether we are using History or
   * hashbang routing.

   * @api private
   */
  Page.prototype._getBase = function() {
    var base = this._base;
    if(!!base) return base;
    var loc = hasWindow && this._window && this._window.location;
    return (hasWindow && this._hashbang && loc && loc.protocol === 'file:') ? loc.pathname : base;
  };

  /**
   * Get or set strict path matching to `enable`
   *
   * @param {boolean} enable
   * @api public
   */

  Page.prototype.strict = function(enable) {
    if (0 === arguments.length) return this._strict;
    this._strict = enable;
  };


  /**
   * Bind with the given `options`.
   *
   * Options:
   *
   *    - `click` bind to click events [true]
   *    - `popstate` bind to popstate [true]
   *    - `dispatch` perform initial dispatch [true]
   *
   * @param {Object} options
   * @api public
   */

  Page.prototype.start = function(options) {
    this.configure(options);

    if (!this._dispatch) return;
    this._running = true;

    var url;
    if(isLocation) {
      var window = this._window;
      var loc = window.location;

      if(this._hashbang && ~loc.hash.indexOf('#!')) {
        url = loc.hash.substr(2) + loc.search;
      } else if (this._hashbang) {
        url = loc.search + loc.hash;
      } else {
        url = loc.pathname + loc.search + loc.hash;
      }
    }

    this.replace(url, null, true, this._dispatch);
  };

  /**
   * Unbind click and popstate event handlers.
   *
   * @api public
   */

  Page.prototype.stop = function() {
    if (!this._running) return;
    this.current = '';
    this.len = 0;
    this._running = false;

    var window = this._window;
    hasDocument && window.document.removeEventListener(clickEvent, this._onclick, false);
    hasWindow && window.removeEventListener('popstate', this._onpopstate, false);
    hasWindow && window.removeEventListener('hashchange', this._onpopstate, false);
  };

  /**
   * Show `path` with optional `state` object.
   *
   * @param {string} path
   * @param {Object=} state
   * @param {boolean=} dispatch
   * @param {boolean=} push
   * @return {!Context}
   * @api public
   */

  Page.prototype.show = function(path, state, dispatch, push) {
    var ctx = new Context(path, state, this),
      prev = this.prevContext;
    this.prevContext = ctx;
    this.current = ctx.path;
    if (this._dispatch) this.dispatch(ctx, prev);
    if (false !== ctx.handled && false !== push) ctx.pushState();
    return ctx;
  };

  /**
   * Goes back in the history
   * Back should always let the current route push state and then go back.
   *
   * @param {string} path - fallback path to go back if no more history exists, if undefined defaults to page.base
   * @param {Object=} state
   * @api public
   */

  Page.prototype.back = function(path, state) {
    var page = this;
    if (this.len > 0) {
      var window = this._window;
      // this may need more testing to see if all browsers
      // wait for the next tick to go back in history
      hasHistory && window.history.back();
      this.len--;
    } else if (path) {
      setTimeout(function() {
        page.show(path, state);
      });
    } else {
      setTimeout(function() {
        page.show(page._getBase(), state);
      });
    }
  };

  /**
   * Register route to redirect from one path to other
   * or just redirect to another route
   *
   * @param {string} from - if param 'to' is undefined redirects to 'from'
   * @param {string=} to
   * @api public
   */
  Page.prototype.redirect = function(from, to) {
    var inst = this;

    // Define route from a path to another
    if ('string' === typeof from && 'string' === typeof to) {
      page.call(this, from, function(e) {
        setTimeout(function() {
          inst.replace(/** @type {!string} */ (to));
        }, 0);
      });
    }

    // Wait for the push state and replace it with another
    if ('string' === typeof from && 'undefined' === typeof to) {
      setTimeout(function() {
        inst.replace(from);
      }, 0);
    }
  };

  /**
   * Replace `path` with optional `state` object.
   *
   * @param {string} path
   * @param {Object=} state
   * @param {boolean=} init
   * @param {boolean=} dispatch
   * @return {!Context}
   * @api public
   */


  Page.prototype.replace = function(path, state, init, dispatch) {
    var ctx = new Context(path, state, this),
      prev = this.prevContext;
    this.prevContext = ctx;
    this.current = ctx.path;
    ctx.init = init;
    ctx.save(); // save before dispatching, which may redirect
    if (false !== dispatch) this.dispatch(ctx, prev);
    return ctx;
  };

  /**
   * Dispatch the given `ctx`.
   *
   * @param {Context} ctx
   * @api private
   */

  Page.prototype.dispatch = function(ctx, prev) {
    var i = 0, j = 0, page = this;

    function nextExit() {
      var fn = page.exits[j++];
      if (!fn) return nextEnter();
      fn(prev, nextExit);
    }

    function nextEnter() {
      var fn = page.callbacks[i++];

      if (ctx.path !== page.current) {
        ctx.handled = false;
        return;
      }
      if (!fn) return unhandled.call(page, ctx);
      fn(ctx, nextEnter);
    }

    if (prev) {
      nextExit();
    } else {
      nextEnter();
    }
  };

  /**
   * Register an exit route on `path` with
   * callback `fn()`, which will be called
   * on the previous context when a new
   * page is visited.
   */
  Page.prototype.exit = function(path, fn) {
    if (typeof path === 'function') {
      return this.exit('*', path);
    }

    var route = new Route$1(path, null, this);
    for (var i = 1; i < arguments.length; ++i) {
      this.exits.push(route.middleware(arguments[i]));
    }
  };

  /**
   * Handle "click" events.
   */

  /* jshint +W054 */
  Page.prototype._onclick = function(e) {
    if (1 !== this._which(e)) return;

    if (e.metaKey || e.ctrlKey || e.shiftKey) return;
    if (e.defaultPrevented) return;

    // ensure link
    // use shadow dom when available if not, fall back to composedPath()
    // for browsers that only have shady
    var el = e.target;
    var eventPath = e.path || (e.composedPath ? e.composedPath() : null);

    if(eventPath) {
      for (var i = 0; i < eventPath.length; i++) {
        if (!eventPath[i].nodeName) continue;
        if (eventPath[i].nodeName.toUpperCase() !== 'A') continue;
        if (!eventPath[i].href) continue;

        el = eventPath[i];
        break;
      }
    }

    // continue ensure link
    // el.nodeName for svg links are 'a' instead of 'A'
    while (el && 'A' !== el.nodeName.toUpperCase()) el = el.parentNode;
    if (!el || 'A' !== el.nodeName.toUpperCase()) return;

    // check if link is inside an svg
    // in this case, both href and target are always inside an object
    var svg = (typeof el.href === 'object') && el.href.constructor.name === 'SVGAnimatedString';

    // Ignore if tag has
    // 1. "download" attribute
    // 2. rel="external" attribute
    if (el.hasAttribute('download') || el.getAttribute('rel') === 'external') return;

    // ensure non-hash for the same path
    var link = el.getAttribute('href');
    if(!this._hashbang && this._samePath(el) && (el.hash || '#' === link)) return;

    // Check for mailto: in the href
    if (link && link.indexOf('mailto:') > -1) return;

    // check target
    // svg target is an object and its desired value is in .baseVal property
    if (svg ? el.target.baseVal : el.target) return;

    // x-origin
    // note: svg links that are not relative don't call click events (and skip page.js)
    // consequently, all svg links tested inside page.js are relative and in the same origin
    if (!svg && !this.sameOrigin(el.href)) return;

    // rebuild path
    // There aren't .pathname and .search properties in svg links, so we use href
    // Also, svg href is an object and its desired value is in .baseVal property
    var path = svg ? el.href.baseVal : (el.pathname + el.search + (el.hash || ''));

    path = path[0] !== '/' ? '/' + path : path;

    // strip leading "/[drive letter]:" on NW.js on Windows
    if (hasProcess && path.match(/^\/[a-zA-Z]:\//)) {
      path = path.replace(/^\/[a-zA-Z]:\//, '/');
    }

    // same page
    var orig = path;
    var pageBase = this._getBase();

    if (path.indexOf(pageBase) === 0) {
      path = path.substr(pageBase.length);
    }

    if (this._hashbang) path = path.replace('#!', '');

    if (pageBase && orig === path) return;

    e.preventDefault();
    this.show(orig);
  };

  /**
   * Handle "populate" events.
   * @api private
   */

  Page.prototype._onpopstate = (function () {
    var loaded = false;
    if ( ! hasWindow ) {
      return;
    }
    if (hasDocument && document.readyState === 'complete') {
      loaded = true;
    } else {
      window.addEventListener('load', function() {
        setTimeout(function() {
          loaded = true;
        }, 0);
      });
    }
    return function onpopstate(e) {
      if (!loaded) return;
      var page = this;
      if (e.state) {
        var path = e.state.path;
        page.replace(path, e.state);
      } else if (isLocation) {
        var loc = page._window.location;
        page.show(loc.pathname + loc.search + loc.hash, undefined, undefined, false);
      }
    };
  })();

  /**
   * Event button.
   */
  Page.prototype._which = function(e) {
    e = e || (hasWindow && this._window.event);
    return null == e.which ? e.button : e.which;
  };

  /**
   * Convert to a URL object
   * @api private
   */
  Page.prototype._toURL = function(href) {
    var window = this._window;
    if(typeof URL === 'function' && isLocation) {
      return new URL(href, window.location.toString());
    } else if (hasDocument) {
      var anc = window.document.createElement('a');
      anc.href = href;
      return anc;
    }
  };

  /**
   * Check if `href` is the same origin.
   * @param {string} href
   * @api public
   */

  Page.prototype.sameOrigin = function(href) {
    if(!href || !isLocation) return false;

    var url = this._toURL(href);
    var window = this._window;

    var loc = window.location;
    return loc.protocol === url.protocol &&
      loc.hostname === url.hostname &&
      loc.port === url.port;
  };

  /**
   * @api private
   */
  Page.prototype._samePath = function(url) {
    if(!isLocation) return false;
    var window = this._window;
    var loc = window.location;
    return url.pathname === loc.pathname &&
      url.search === loc.search;
  };

  /**
   * Remove URL encoding from the given `str`.
   * Accommodates whitespace in both x-www-form-urlencoded
   * and regular percent-encoded form.
   *
   * @param {string} val - URL component to decode
   * @api private
   */
  Page.prototype._decodeURLEncodedURIComponent = function(val) {
    if (typeof val !== 'string') { return val; }
    return this._decodeURLComponents ? decodeURIComponent(val.replace(/\+/g, ' ')) : val;
  };

  /**
   * Create a new `page` instance and function
   */
  function createPage(options) {
    var pageInstance = new Page();

    function pageFn(/* args */) {
      return page.apply(pageInstance, arguments);
    }

    // Copy all of the things over. In 2.0 maybe we use setPrototypeOf
    pageFn.callbacks = pageInstance.callbacks;
    pageFn.exits = pageInstance.exits;
    pageFn.base = pageInstance.base.bind(pageInstance);
    pageFn.strict = pageInstance.strict.bind(pageInstance);
    pageFn.start = pageInstance.start.bind(pageInstance);
    pageFn.stop = pageInstance.stop.bind(pageInstance);
    pageFn.show = pageInstance.show.bind(pageInstance);
    pageFn.back = pageInstance.back.bind(pageInstance);
    pageFn.redirect = pageInstance.redirect.bind(pageInstance);
    pageFn.replace = pageInstance.replace.bind(pageInstance);
    pageFn.dispatch = pageInstance.dispatch.bind(pageInstance);
    pageFn.exit = pageInstance.exit.bind(pageInstance);
    pageFn.configure = pageInstance.configure.bind(pageInstance);
    pageFn.sameOrigin = pageInstance.sameOrigin.bind(pageInstance);

    pageFn.create = createPage;

    Object.defineProperty(pageFn, 'len', {
      get: function(){
        return pageInstance.len;
      },
      set: function(val) {
        pageInstance.len = val;
      }
    });

    Object.defineProperty(pageFn, 'current', {
      get: function(){
        return pageInstance.current;
      },
      set: function(val) {
        pageInstance.current = val;
      }
    });

    // In 2.0 these can be named exports
    pageFn.Context = Context;
    pageFn.Route = Route$1;

    return pageFn;
  }

  /**
   * Register `path` with callback `fn()`,
   * or route `path`, or redirection,
   * or `page.start()`.
   *
   *   page(fn);
   *   page('*', fn);
   *   page('/user/:id', load, user);
   *   page('/user/' + user.id, { some: 'thing' });
   *   page('/user/' + user.id);
   *   page('/from', '/to')
   *   page();
   *
   * @param {string|!Function|!Object} path
   * @param {Function=} fn
   * @api public
   */

  function page(path, fn) {
    // <callback>
    if ('function' === typeof path) {
      return page.call(this, '*', path);
    }

    // route <path> to <callback ...>
    if ('function' === typeof fn) {
      var route = new Route$1(/** @type {string} */ (path), null, this);
      for (var i = 1; i < arguments.length; ++i) {
        this.callbacks.push(route.middleware(arguments[i]));
      }
      // show <path> with [state]
    } else if ('string' === typeof path) {
      this['string' === typeof fn ? 'redirect' : 'show'](path, fn);
      // start [options]
    } else {
      this.start(path);
    }
  }

  /**
   * Unhandled `ctx`. When it's not the initial
   * popstate then redirect. If you wish to handle
   * 404s on your own use `page('*', callback)`.
   *
   * @param {Context} ctx
   * @api private
   */
  function unhandled(ctx) {
    if (ctx.handled) return;
    var current;
    var page = this;
    var window = page._window;

    if (page._hashbang) {
      current = isLocation && this._getBase() + window.location.hash.replace('#!', '');
    } else {
      current = isLocation && window.location.pathname + window.location.search;
    }

    if (current === ctx.canonicalPath) return;
    page.stop();
    ctx.handled = false;
    isLocation && (window.location.href = ctx.canonicalPath);
  }

  /**
   * Initialize a new "request" `Context`
   * with the given `path` and optional initial `state`.
   *
   * @constructor
   * @param {string} path
   * @param {Object=} state
   * @api public
   */

  function Context(path, state, pageInstance) {
    var _page = this.page = pageInstance || page;
    var window = _page._window;
    var hashbang = _page.hashbang;

    var pageBase = _page._getBase();
    if ('/' === path[0] && 0 !== path.indexOf(pageBase)) path = pageBase + (hashbang ? '#!' : '') + path;
    var i = path.indexOf('?');

    this.canonicalPath = path;
    this.path = path.replace(pageBase, '') || '/';
    if (hashbang) this.path = this.path.replace('#!', '') || '/';

    this.title = (hasDocument && window.document.title);
    this.state = state || {};
    this.state.path = path;
    this.querystring = ~i ? _page._decodeURLEncodedURIComponent(path.slice(i + 1)) : '';
    this.pathname = _page._decodeURLEncodedURIComponent(~i ? path.slice(0, i) : path);
    this.params = {};

    // fragment
    this.hash = '';
    if (!hashbang) {
      if (!~this.path.indexOf('#')) return;
      var parts = this.path.split('#');
      this.path = this.pathname = parts[0];
      this.hash = _page._decodeURLEncodedURIComponent(parts[1]) || '';
      this.querystring = this.querystring.split('#')[0];
    }
  }

  /**
   * Push state.
   *
   * @api private
   */

  Context.prototype.pushState = function() {
    var page = this.page;
    var window = page._window;
    var hashbang = page._hashbang;

    page.len++;
    if (hasHistory) {
        window.history.pushState(this.state, this.title,
          hashbang && this.path !== '/' ? '#!' + this.path : this.canonicalPath);
    }
  };

  /**
   * Save the context state.
   *
   * @api public
   */

  Context.prototype.save = function() {
    var page = this.page;
    if (hasHistory && page._window.location.protocol !== 'file:') {
        page._window.history.replaceState(this.state, this.title,
          page._hashbang && this.path !== '/' ? '#!' + this.path : this.canonicalPath);
    }
  };

  /**
   * Initialize `Route` with the given HTTP `path`,
   * and an array of `callbacks` and `options`.
   *
   * Options:
   *
   *   - `sensitive`    enable case-sensitive routes
   *   - `strict`       enable strict matching for trailing slashes
   *
   * @constructor
   * @param {string} path
   * @param {Object=} options
   * @api private
   */

  function Route$1(path, options, page) {
    var _page = this.page = page || globalPage;
    var opts = options || {};
    opts.strict = opts.strict || page._strict;
    this.path = (path === '*') ? '(.*)' : path;
    this.method = 'GET';
    this.regexp = pathToRegexp_1(this.path, this.keys = [], opts);
  }

  /**
   * Return route middleware with
   * the given callback `fn()`.
   *
   * @param {Function} fn
   * @return {Function}
   * @api public
   */

  Route$1.prototype.middleware = function(fn) {
    var self = this;
    return function(ctx, next) {
      if (self.match(ctx.path, ctx.params)) return fn(ctx, next);
      next();
    };
  };

  /**
   * Check if this route matches `path`, if so
   * populate `params`.
   *
   * @param {string} path
   * @param {Object} params
   * @return {boolean}
   * @api private
   */

  Route$1.prototype.match = function(path, params) {
    var keys = this.keys,
      qsIndex = path.indexOf('?'),
      pathname = ~qsIndex ? path.slice(0, qsIndex) : path,
      m = this.regexp.exec(decodeURIComponent(pathname));

    if (!m) return false;

    for (var i = 1, len = m.length; i < len; ++i) {
      var key = keys[i - 1];
      var val = this.page._decodeURLEncodedURIComponent(m[i]);
      if (val !== undefined || !(hasOwnProperty.call(params, key.name))) {
        params[key.name] = val;
      }
    }

    return true;
  };


  /**
   * Module exports.
   */

  var globalPage = createPage();
  var page_js = globalPage;
  page.default = globalPage;

class Router {
    constructor() {
        this._url = '/';
        this.routes = [];
        this.hash = '';
    }
    componentDidLoad() {
        this.el.style.display = "none";
        this.postRender();
        if (this.level == 0) {
            page_js(window.location.pathname);
        }
    }
    componentDidUpdate() {
        this.postRender();
    }
    postRender() {
        let routeComponents = Array.from(this.el.getElementsByTagName('ema-route'));
        routeComponents.forEach((route) => {
            this.routes.push({
                'component': route.component,
                'component-props': route.componentProps,
                'url': route.url,
                'exact': route.exact,
                'action': route.action,
                'action-params': route.actionParams,
            });
        });
        this.routes.forEach((route) => {
            page_js(route.url, (pageContext) => {
                if (route.component) {
                    pageContext.state.component = route.component;
                }
                this._pageContext = pageContext;
                this.state = {
                    context: pageContext,
                    route: route,
                    routes: this.routes,
                    component: route.component,
                };
                this.activateRoute();
                this.change.emit(this.state);
            });
        });
    }
    activateRoute() {
        let breadcrumb = [];
        let component;
        let pageClass = 'page';
        let pageContext = this.state.context;
        let params = pageContext.params;
        let route = this.state.route;
        let routeComponent;
        let url = this._url = pageContext.state.path;
        let urlParsed = this.urlParamsToUrl(route.url);
        if (!route.component) {
            console.error('No component defined for url: ' + url);
            return;
        }
        else {
            component = route.component;
        }
        this.deleteRouterClasses();
        pageContext.state.path.split('/').forEach((p) => {
            if (p !== '') {
                breadcrumb.push(p);
            }
        });
        if (pageContext.state.component) {
            routeComponent = pageContext.state.component;
        }
        breadcrumb.forEach((level) => {
            pageClass += ('-' + level);
            this.removeClass(document.querySelector('body'), pageClass);
        });
        if (component && component === routeComponent && url === urlParsed) {
            if (route['exact'] && route['url'] !== url) ;
            if (this._compDiv) {
                if (this.targetSelector) {
                    if (document.querySelector(this.targetSelector)) {
                        document.querySelector(this.targetSelector).removeChild(this._compDiv);
                    }
                }
                else {
                    this.el.parentNode.removeChild(this._compDiv);
                }
            }
            this._compDiv = document.createElement(component);
            if (route['component-props']) {
                let cprops = JSON.parse(route['component-props']);
                Object.keys(cprops).forEach((k) => {
                    let v = cprops[k];
                    if (typeof v !== 'string') {
                        v = JSON.stringify(v);
                    }
                    this._compDiv.setAttribute(k, v);
                });
            }
            if (this.targetSelector) {
                if (document.querySelector(this.targetSelector)) {
                    document.querySelector(this.targetSelector).appendChild(this._compDiv);
                }
            }
            else {
                this.el.parentNode.insertBefore(this._compDiv, this.el.nextSibling);
            }
            this.addClass(document.querySelector('body'), component);
        }
        this.addClass(document.querySelector('body'), pageClass);
    }
    deleteRouterClasses() {
        let bodyElement = document.querySelector('body');
        this.state.routes.forEach((r) => {
            if (r.component) {
                this.removeClass(bodyElement, r.component);
            }
        });
        bodyElement.classList.forEach((classId) => {
            if (classId.startsWith('page-')) {
                this.removeClass(bodyElement, classId);
            }
        });
    }
    urlParamsToUrl(url) {
        let parsedUrl = url;
        let params = this.state.context.params;
        let parts = url.split('/');
        let hasParams = false;
        parts.forEach((part, i) => {
            let variable;
            let value;
            if (part.startsWith(':')) {
                hasParams = true;
                variable = part.split(':')[1];
                value = params[variable];
                parsedUrl = parsedUrl.replace(part, value);
            }
        });
        if (hasParams) {
            return parsedUrl;
        }
        else {
            return url;
        }
    }
    async url(url) {
        if (url) {
            page_js(this.hash + url);
        }
        else {
            return this._url;
        }
    }
    async page() {
        return page_js;
    }
    async getState() {
        return this.state;
    }
    addClass(el, className) {
        if (el.classList)
            el.classList.add(className);
        else
            el.className += ' ' + className;
    }
    removeClass(el, className) {
        if (el.classList)
            el.classList.remove(className);
        else
            el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
    }
    render() {
        return (h("div", null));
    }
    static get is() { return "ema-router"; }
    static get properties() { return {
        "dataJson": {
            "type": String,
            "attr": "data-json"
        },
        "el": {
            "elementRef": true
        },
        "getState": {
            "method": true
        },
        "hash": {
            "type": String,
            "attr": "hash"
        },
        "level": {
            "type": Number,
            "attr": "level"
        },
        "page": {
            "method": true
        },
        "routerLinks": {
            "state": true
        },
        "routes": {
            "state": true
        },
        "state": {
            "state": true
        },
        "targetSelector": {
            "type": String,
            "attr": "target-selector"
        },
        "url": {
            "method": true
        }
    }; }
    static get events() { return [{
            "name": "change",
            "method": "change",
            "bubbles": true,
            "cancelable": true,
            "composed": true
        }]; }
}

export { AppRoot as EmaAppRoot, Debugger as EmaDebugger, Dialog as EmaDialog, FlashMessage as EmaFlashMessage, Route as EmaRoute, Router as EmaRouter };
