import { __esDecorate, __runInitializers } from "tslib";
import { html, LitElement } from 'lit';
import { property, query, queryAssignedElements, state } from 'lit/decorators.js';
import { classMap } from 'lit/directives/class-map.js';
import { styleMap } from 'lit/directives/style-map.js';
import { Easing } from '../../motion/animation.js';
import UiTab from './Tab.js';
import '../../icon-button/ui-icon-button.js';
import '../../divider/ui-divider.js';
import '../../icons/ui-icon.js';
/**
 * Calculates value in percentages
 * @param w Element width
 * @param w0 Parent width
 * @return The percentage of element's width relative to parent.
 */
export function calcPercent(w, w0) {
    return (100 * w) / w0;
}
let UiTabs = (() => {
    let _classSuper = LitElement;
    let _tabs_decorators;
    let _tabs_initializers = [];
    let _tabs_extraInitializers = [];
    let _tabsScrollerElement_decorators;
    let _tabsScrollerElement_initializers = [];
    let _tabsScrollerElement_extraInitializers = [];
    let _slotElement_decorators;
    let _slotElement_initializers = [];
    let _slotElement_extraInitializers = [];
    let _pointer_decorators;
    let _pointer_initializers = [];
    let _pointer_extraInitializers = [];
    let _priority_decorators;
    let _priority_initializers = [];
    let _priority_extraInitializers = [];
    let _pointerStyles_decorators;
    let _pointerStyles_initializers = [];
    let _pointerStyles_extraInitializers = [];
    let _indicated_decorators;
    let _indicated_initializers = [];
    let _indicated_extraInitializers = [];
    let _isVisible_decorators;
    let _isVisible_initializers = [];
    let _isVisible_extraInitializers = [];
    let _autoActivate_decorators;
    let _autoActivate_initializers = [];
    let _autoActivate_extraInitializers = [];
    return class UiTabs extends _classSuper {
        static {
            const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
            _tabs_decorators = [queryAssignedElements({ flatten: true, selector: 'ui-tab' })];
            _tabsScrollerElement_decorators = [query('.tabs')];
            _slotElement_decorators = [query('slot')];
            _pointer_decorators = [query('.pointer')];
            _priority_decorators = [property({ type: String, reflect: true })];
            _pointerStyles_decorators = [state()];
            _indicated_decorators = [state()];
            _isVisible_decorators = [state()];
            _autoActivate_decorators = [property({ type: Boolean })];
            __esDecorate(this, null, _tabs_decorators, { kind: "accessor", name: "tabs", static: false, private: false, access: { has: obj => "tabs" in obj, get: obj => obj.tabs, set: (obj, value) => { obj.tabs = value; } }, metadata: _metadata }, _tabs_initializers, _tabs_extraInitializers);
            __esDecorate(this, null, _tabsScrollerElement_decorators, { kind: "accessor", name: "tabsScrollerElement", static: false, private: false, access: { has: obj => "tabsScrollerElement" in obj, get: obj => obj.tabsScrollerElement, set: (obj, value) => { obj.tabsScrollerElement = value; } }, metadata: _metadata }, _tabsScrollerElement_initializers, _tabsScrollerElement_extraInitializers);
            __esDecorate(this, null, _slotElement_decorators, { kind: "accessor", name: "slotElement", static: false, private: false, access: { has: obj => "slotElement" in obj, get: obj => obj.slotElement, set: (obj, value) => { obj.slotElement = value; } }, metadata: _metadata }, _slotElement_initializers, _slotElement_extraInitializers);
            __esDecorate(this, null, _pointer_decorators, { kind: "accessor", name: "pointer", static: false, private: false, access: { has: obj => "pointer" in obj, get: obj => obj.pointer, set: (obj, value) => { obj.pointer = value; } }, metadata: _metadata }, _pointer_initializers, _pointer_extraInitializers);
            __esDecorate(this, null, _priority_decorators, { kind: "accessor", name: "priority", static: false, private: false, access: { has: obj => "priority" in obj, get: obj => obj.priority, set: (obj, value) => { obj.priority = value; } }, metadata: _metadata }, _priority_initializers, _priority_extraInitializers);
            __esDecorate(this, null, _pointerStyles_decorators, { kind: "accessor", name: "pointerStyles", static: false, private: false, access: { has: obj => "pointerStyles" in obj, get: obj => obj.pointerStyles, set: (obj, value) => { obj.pointerStyles = value; } }, metadata: _metadata }, _pointerStyles_initializers, _pointerStyles_extraInitializers);
            __esDecorate(this, null, _indicated_decorators, { kind: "accessor", name: "indicated", static: false, private: false, access: { has: obj => "indicated" in obj, get: obj => obj.indicated, set: (obj, value) => { obj.indicated = value; } }, metadata: _metadata }, _indicated_initializers, _indicated_extraInitializers);
            __esDecorate(this, null, _isVisible_decorators, { kind: "accessor", name: "isVisible", static: false, private: false, access: { has: obj => "isVisible" in obj, get: obj => obj.isVisible, set: (obj, value) => { obj.isVisible = value; } }, metadata: _metadata }, _isVisible_initializers, _isVisible_extraInitializers);
            __esDecorate(this, null, _autoActivate_decorators, { kind: "accessor", name: "autoActivate", static: false, private: false, access: { has: obj => "autoActivate" in obj, get: obj => obj.autoActivate, set: (obj, value) => { obj.autoActivate = value; } }, metadata: _metadata }, _autoActivate_initializers, _autoActivate_extraInitializers);
            if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        activeItem = null;
        previousItem = null;
        /**
         * The currently selected tab, `null` only when there are no tab children.
         */
        get activeTab() {
            return this.tabs.find((tab) => tab.selected) ?? null;
        }
        set activeTab(tab) {
            // Ignore setting activeTab to null. As long as there are children, one tab
            // must be selected.
            if (tab) {
                this.activateTab(tab);
            }
        }
        /**
         * The index of the currently selected tab.
         */
        get activeTabIndex() {
            return this.tabs.findIndex((tab) => tab.selected);
        }
        /**
         * Sets the active tab by index.
         */
        set activeTabIndex(index) {
            const activateTabAtIndex = () => {
                const tab = this.tabs[index];
                // Ignore out-of-bound indices.
                if (tab) {
                    this.activateTab(tab);
                }
            };
            if (!this.slotElement) {
                // This is needed to support setting the activeTabIndex via a lit property
                // binding.
                //
                // ```ts
                // html`
                //   <ui-tabs .activeTabIndex=${1}>
                //     <ui-tab>First</ui-tab>
                //     <ui-tab>Second</ui-tab>
                //   </ui-tabs>
                // `;
                // ```
                //
                // It's needed since lit's rendering lifecycle is asynchronous, and the
                // `<slot>` element hasn't rendered, so `tabs` is empty.
                this.updateComplete.then(activateTabAtIndex);
                return;
            }
            activateTabAtIndex();
        }
        get focusedTab() {
            return this.tabs.find((tab) => tab.matches(':focus-within'));
        }
        #tabs_accessor_storage = __runInitializers(this, _tabs_initializers, void 0);
        get tabs() { return this.#tabs_accessor_storage; }
        set tabs(value) { this.#tabs_accessor_storage = value; }
        #tabsScrollerElement_accessor_storage = (__runInitializers(this, _tabs_extraInitializers), __runInitializers(this, _tabsScrollerElement_initializers, void 0));
        get tabsScrollerElement() { return this.#tabsScrollerElement_accessor_storage; }
        set tabsScrollerElement(value) { this.#tabsScrollerElement_accessor_storage = value; }
        #slotElement_accessor_storage = (__runInitializers(this, _tabsScrollerElement_extraInitializers), __runInitializers(this, _slotElement_initializers, void 0));
        get slotElement() { return this.#slotElement_accessor_storage; }
        set slotElement(value) { this.#slotElement_accessor_storage = value; }
        #pointer_accessor_storage = (__runInitializers(this, _slotElement_extraInitializers), __runInitializers(this, _pointer_initializers, void 0));
        get pointer() { return this.#pointer_accessor_storage; }
        set pointer(value) { this.#pointer_accessor_storage = value; }
        #priority_accessor_storage = (__runInitializers(this, _pointer_extraInitializers), __runInitializers(this, _priority_initializers, 'primary'));
        /**
         * The priority of the tabs.
         *
         * @default primary
         * @attribute
         */
        get priority() { return this.#priority_accessor_storage; }
        set priority(value) { this.#priority_accessor_storage = value; }
        #pointerStyles_accessor_storage = (__runInitializers(this, _priority_extraInitializers), __runInitializers(this, _pointerStyles_initializers, void 0));
        get pointerStyles() { return this.#pointerStyles_accessor_storage; }
        set pointerStyles(value) { this.#pointerStyles_accessor_storage = value; }
        #indicated_accessor_storage = (__runInitializers(this, _pointerStyles_extraInitializers), __runInitializers(this, _indicated_initializers, false));
        get indicated() { return this.#indicated_accessor_storage; }
        set indicated(value) { this.#indicated_accessor_storage = value; }
        observer = __runInitializers(this, _indicated_extraInitializers);
        #isVisible_accessor_storage = __runInitializers(this, _isVisible_initializers, void 0);
        /**
         * This is set by the intersection observer. Once the tabs are in the view it turns to `true`.
         * This we can properly visualize selection.
         */
        get isVisible() { return this.#isVisible_accessor_storage; }
        set isVisible(value) { this.#isVisible_accessor_storage = value; }
        #autoActivate_accessor_storage = (__runInitializers(this, _isVisible_extraInitializers), __runInitializers(this, _autoActivate_initializers, false));
        /**
         * Whether or not to automatically select a tab when it is focused.
         */
        get autoActivate() { return this.#autoActivate_accessor_storage; }
        set autoActivate(value) { this.#autoActivate_accessor_storage = value; }
        internals = (__runInitializers(this, _autoActivate_extraInitializers), this.attachInternals());
        constructor() {
            super();
            this.internals.role = 'tablist';
            this.observer = new IntersectionObserver(this.intersectionCallback.bind(this), {
                threshold: 1.0,
                rootMargin: '0px',
            });
            this.addEventListener('keydown', this.handleKeydown.bind(this));
            this.addEventListener('keyup', this.handleKeyup.bind(this));
            this.addEventListener('focusout', this.handleFocusout.bind(this));
        }
        willUpdate(cp) {
            if (cp.has('isVisible')) {
                this.handleVisibility();
            }
            super.willUpdate(cp);
        }
        connectedCallback() {
            super.connectedCallback();
            this.observer.observe(this);
            if (!this.hasAttribute('role')) {
                this.setAttribute('role', 'tablist');
            }
        }
        disconnectedCallback() {
            super.disconnectedCallback();
            this.observer.unobserve(this);
        }
        intersectionCallback(entries) {
            const [entry] = entries;
            this.isVisible = entry.isIntersecting;
        }
        /**
         * Scrolls the toolbar, if overflowing, to the active tab, or the provided
         * tab.
         *
         * @param tabToScrollTo The tab that should be scrolled to. Defaults to the
         *     active tab.
         * @return A Promise that resolves after the tab has been scrolled to.
         */
        async scrollToTab(tabToScrollTo) {
            await this.updateComplete;
            const { tabs } = this;
            tabToScrollTo ??= this.activeTab;
            if (!tabToScrollTo || !tabs.includes(tabToScrollTo) || !this.tabsScrollerElement) {
                return;
            }
            // wait for tabs to render.
            await Promise.all(tabs.map((tab) => tab.updateComplete));
            tabToScrollTo.scrollIntoView({
                block: 'nearest',
                inline: 'nearest',
                behavior: !this.focusedTab ? 'instant' : 'auto',
            });
        }
        handleVisibility() {
            const { previousItem, activeItem } = this;
            if (!activeItem) {
                return;
            }
            this.positionPointer(activeItem, previousItem);
        }
        async positionPointer(tab, old) {
            const { pointer, isVisible } = this;
            if (!isVisible) {
                tab.indicated = true;
                return;
            }
            const index = this.tabs.indexOf(tab);
            if (index < 0 || !pointer) {
                this.pointerStyles = undefined;
                return;
            }
            if (!old) {
                // no start animation, just show indicator.
                tab.indicated = true;
                return;
            }
            const isPrimary = this.priority === 'primary';
            const final = this.getTabSizing(tab);
            if (this.pointerStyles && this.pointerStyles.left === `${final.left}px`) {
                tab.indicated = true;
                return;
            }
            // first position this indicator in the place of the old one.
            // update the view and then run the animation.
            this.indicated = true;
            const starting = this.getTabSizing(old);
            this.pointerStyles = { left: `${starting.left}px`, width: `${starting.width}px` };
            await this.updateComplete;
            const frames = isPrimary ? this.getPrimaryKeyframes(starting, final) : this.getSecondaryKeyframes(starting, final);
            if (this.moveAnimation) {
                this.moveAnimation.cancel();
            }
            const moveAnimation = pointer.animate(frames, {
                duration: 200,
                iterations: 1,
                easing: Easing.EMPHASIZED_DECELERATE,
            });
            const finalStyles = {
                left: `${final.left}px`,
                width: `${final.width}px`,
            };
            moveAnimation.addEventListener('finish', () => {
                this.pointerStyles = finalStyles;
                this.moveAnimation = undefined;
                tab.indicated = true;
                this.indicated = false;
            });
            moveAnimation.addEventListener('cancel', () => {
                this.pointerStyles = finalStyles;
            });
            this.moveAnimation = moveAnimation;
        }
        moveAnimation;
        getTabSizing(tab) {
            const contentBox = this.tabsScrollerElement.getBoundingClientRect();
            const sizing = tab.getIndicatorSizing();
            sizing.left = sizing.left - contentBox.x;
            return sizing;
        }
        getPrimaryKeyframes(start, final) {
            return [
                {
                    left: `${start.left}px`,
                    width: `${start.width}px`,
                },
                {
                    left: `${final.left}px`,
                    width: `${final.width}px`,
                },
            ];
        }
        getSecondaryKeyframes(start, final) {
            return [
                {
                    left: `${start.left}px`,
                    width: `${start.width}px`,
                },
                {
                    left: `${final.left}px`,
                    width: `${final.width}px`,
                },
            ];
        }
        async handleTabClick(e) {
            const tab = e.composedPath().find((el) => isTab(el));
            // Allow event to bubble
            await new Promise((resolve) => setTimeout(resolve, 0));
            if (e.defaultPrevented || !tab || tab.selected) {
                return;
            }
            this.activateTab(tab);
        }
        activateTab(activeTab) {
            const { tabs } = this;
            const previousTab = this.activeTab;
            if (!tabs.includes(activeTab) || previousTab === activeTab) {
                // Ignore setting activeTab to a tab element that is not a child.
                return;
            }
            for (const tab of tabs) {
                tab.selected = tab === activeTab;
            }
            if (previousTab) {
                // Don't dispatch a change event if activating a tab when no previous tabs
                // were selected, such as when md-tabs auto-selects the first tab.
                const detail = {
                    item: activeTab,
                    index: this.tabs.indexOf(activeTab),
                };
                const defaultPrevented = !this.dispatchEvent(new CustomEvent('change', { detail, bubbles: false, cancelable: true }));
                if (defaultPrevented) {
                    for (const tab of tabs) {
                        tab.selected = tab === previousTab;
                    }
                    return;
                }
                previousTab.indicated = false;
            }
            activeTab.indicated = false;
            this.positionPointer(activeTab, previousTab);
            this.updateFocusableTab(activeTab);
            this.scrollToTab(activeTab);
        }
        updateFocusableTab(focusableTab) {
            for (const tab of this.tabs) {
                tab.tabIndex = tab === focusableTab ? 0 : -1;
            }
        }
        async handleKeydown(event) {
            // Allow event to bubble.
            await new Promise((resolve) => setTimeout(resolve, 0));
            const isLeft = event.key === 'ArrowLeft';
            const isRight = event.key === 'ArrowRight';
            const isHome = event.key === 'Home';
            const isEnd = event.key === 'End';
            // Ignore non-navigation keys
            if (event.defaultPrevented || (!isLeft && !isRight && !isHome && !isEnd)) {
                return;
            }
            const { tabs } = this;
            // Don't try to select another tab if there aren't any.
            if (tabs.length < 2) {
                return;
            }
            // Prevent default interactions, such as scrolling.
            event.preventDefault();
            let indexToFocus;
            if (isHome || isEnd) {
                indexToFocus = isHome ? 0 : tabs.length - 1;
            }
            else {
                // Check if moving forwards or backwards
                const isRtl = getComputedStyle(this).direction === 'rtl';
                const forwards = isRtl ? isLeft : isRight;
                const { focusedTab } = this;
                if (!focusedTab) {
                    // If there is not already a tab focused, select the first or last tab
                    // based on the direction we're traveling.
                    indexToFocus = forwards ? 0 : tabs.length - 1;
                }
                else {
                    const focusedIndex = this.tabs.indexOf(focusedTab);
                    indexToFocus = forwards ? focusedIndex + 1 : focusedIndex - 1;
                    if (indexToFocus >= tabs.length) {
                        // Return to start if moving past the last item.
                        indexToFocus = 0;
                    }
                    else if (indexToFocus < 0) {
                        // Go to end if moving before the first item.
                        indexToFocus = tabs.length - 1;
                    }
                }
            }
            const tabToFocus = tabs[indexToFocus];
            tabToFocus.focus();
            if (this.autoActivate) {
                this.activateTab(tabToFocus);
            }
            else {
                this.updateFocusableTab(tabToFocus);
            }
        }
        // scroll to item on keyup.
        handleKeyup() {
            this.scrollToTab(this.focusedTab ?? this.activeTab);
        }
        handleFocusout() {
            // restore focus to selected item when blurring the tab bar.
            if (this.matches(':focus-within')) {
                return;
            }
            const { activeTab } = this;
            if (activeTab) {
                this.updateFocusableTab(activeTab);
            }
        }
        handleSlotChange() {
            for (const tab of this.tabs) {
                tab.priority = this.priority;
                if (tab.selected) {
                    tab.indicated = true;
                }
            }
            const firstTab = this.tabs[0];
            if (!this.activeTab && firstTab) {
                // If the active tab was removed, auto-select the first one. There should
                // always be a selected tab while the bar has children.
                this.activateTab(firstTab);
            }
            // When children shift, ensure the active tab is visible. For example, if
            // many children are added before the active tab, it'd be pushed off screen.
            // This ensures it stays visible.
            this.scrollToTab(this.activeTab);
            if (this.activeTab) {
                this.updateFocusableTab(this.activeTab);
            }
        }
        render() {
            return html `
      <div class="tabs">${this.renderSlot()}</div>
      ${this.renderIndicator()}
      <ui-divider class="divider"></ui-divider>
    `;
        }
        renderSlot() {
            return html `<slot @slotchange="${this.handleSlotChange}" @click="${this.handleTabClick}"></slot>`;
        }
        renderIndicator() {
            const classes = {
                indicator: true,
                indicated: this.indicated,
                primary: this.priority === 'primary',
                secondary: this.priority === 'secondary',
            };
            return html `
      <div class="${classMap(classes)}">
        <span role="presentation" class="pointer" style="${styleMap(this.pointerStyles || {})}"></span>
      </div>
    `;
        }
    };
})();
/**
 * A container for tabs.
 *
 * @fires change - A non bubbling event when selection change through user interaction.
 */
export default UiTabs;
function isTab(element) {
    return element instanceof UiTab;
}
//# sourceMappingURL=Tabs.js.map