/**
 * Copyright Aquera Inc 2023
 *
 * This source code is licensed under the BSD-3-Clause license found in the
 * LICENSE file in the root directory of this source tree.
 */
import { __decorate } from "tslib";
import '../nile-icon-button/nile-icon-button';
import { animateTo, stopAnimations } from '../internal/animate';
import { classMap } from 'lit/directives/class-map.js';
import { customElement, property, query } from 'lit/decorators.js';
import { getAnimation, setDefaultAnimation } from '../utilities/animation-registry';
import { HasSlotController } from '../internal/slot';
import { html } from 'lit';
import { ifDefined } from 'lit/directives/if-defined.js';
import { lockBodyScrolling, unlockBodyScrolling } from '../internal/scroll';
import { uppercaseFirstLetter } from '../internal/string';
import { waitForEvent } from '../internal/event';
import { watch } from '../internal/watch';
import Modal from '../internal/modal';
import NileElement from '../internal/nile-element';
import styles from './nile-drawer.css';
/**
 * Nile drawer component.
 *
 * @tag nile-drawer
 *
 * @summary Drawers slide in from a container to expose additional options and information.
 *
 * @dependency nile-icon-button
 *
 * @slot - The drawer's main content.
 * @slot label - The drawer's label. Alternatively, you can use the `label` attribute.
 * @slot header-actions - Optional actions to add to the header. Works best with `<nile-icon-button>`.
 * @slot footer - The drawer's footer, usually one or more buttons representing various options.
 *
 * @event nile-show - Emitted when the drawer opens.
 * @event nile-after-show - Emitted after the drawer opens and all animations are complete.
 * @event nile-hide - Emitted when the drawer closes.
 * @event nile-after-hide - Emitted after the drawer closes and all animations are complete.
 * @event nile-initial-focus - Emitted when the drawer opens and is ready to receive focus. Calling
 *   `event.preventDefault()` will prevent focusing and allow you to set it on a different element, such as an input.
 * @event {{ source: 'close-button' | 'keyboard' | 'overlay' }} nile-request-close - Emitted when the user attempts to
 *   close the drawer by clicking the close button, clicking the overlay, or pressing escape. Calling
 *   `event.preventDefault()` will keep the drawer open. Avoid using this unless closing the drawer will result in
 *   destructive behavior such as data loss.
 *
 * @csspart base - The component's base wrapper.
 * @csspart overlay - The overlay that covers the screen behind the drawer.
 * @csspart panel - The drawer's panel (where the drawer and its content are rendered).
 * @csspart header - The drawer's header. This element wraps the title and header actions.
 * @csspart header-actions - Optional actions to add to the header. Works best with `<nile-icon-button>`.
 * @csspart title - The drawer's title.
 * @csspart close-button - The close button, an `<nile-icon-button>`.
 * @csspart close-button__base - The close button's exported `base` part.
 * @csspart body - The drawer's body.
 * @csspart footer - The drawer's footer.
 *
 * @cssproperty --size - The preferred size of the drawer. This will be applied to the drawer's width or height
 *   depending on its `placement`. Note that the drawer will shrink to accommodate smaller screens.
 * @cssproperty --header-spacing - The amount of padding to use for the header.
 * @cssproperty --body-spacing - The amount of padding to use for the body.
 * @cssproperty --footer-spacing - The amount of padding to use for the footer.
 *
 * @animation drawer.showTop - The animation to use when showing a drawer with `top` placement.
 * @animation drawer.showEnd - The animation to use when showing a drawer with `end` placement.
 * @animation drawer.showBottom - The animation to use when showing a drawer with `bottom` placement.
 * @animation drawer.showStart - The animation to use when showing a drawer with `start` placement.
 * @animation drawer.hideTop - The animation to use when hiding a drawer with `top` placement.
 * @animation drawer.hideEnd - The animation to use when hiding a drawer with `end` placement.
 * @animation drawer.hideBottom - The animation to use when hiding a drawer with `bottom` placement.
 * @animation drawer.hideStart - The animation to use when hiding a drawer with `start` placement.
 * @animation drawer.denyClose - The animation to use when a request to close the drawer is denied.
 * @animation drawer.overlay.show - The animation to use when showing the drawer's overlay.
 * @animation drawer.overlay.hide - The animation to use when hiding the drawer's overlay.
 */
let NileDrawer = class NileDrawer extends NileElement {
    constructor() {
        super(...arguments);
        this.hasSlotController = new HasSlotController(this, 'footer');
        /**
         * Indicates whether or not the drawer is open. You can toggle this attribute to show and hide the drawer, or you can
         * use the `show()` and `hide()` methods and this attribute will reflect the drawer's open state.
         */
        this.open = false;
        this.closeOnEscape = true;
        /**
         * The drawer's label as displayed in the header. You should always include a relevant label even when using
         * `no-header`, as it is required for proper accessibility. If you need to display HTML, use the `label` slot instead.
         */
        this.label = '';
        /** The direction from which the drawer will open. */
        this.placement = 'end';
        /**
         * By default, the drawer slides out of its containing block (usually the viewport). To make the drawer slide out of
         * its parent element, set this attribute and add `position: relative` to the parent.
         */
        this.contained = false;
        /**
         * Drawer doesnt close when clicled on overlay, the only way to close is to do by handling open property
         */
        this.preventOverlayClose = false;
        /**
         * Removes the header. This will also remove the default close button, so please ensure you provide an easy,
         * accessible way for users to dismiss the drawer.
         */
        this.noHeader = false;
    }
    connectedCallback() {
        super.connectedCallback();
        this.handleDocumentKeyDown = this.handleDocumentKeyDown.bind(this);
        this.modal = new Modal(this);
    }
    firstUpdated() {
        this.drawer.hidden = !this.open;
        if (this.open) {
            this.addOpenListeners();
            if (!this.contained) {
                this.modal.activate();
                lockBodyScrolling(this);
            }
        }
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        unlockBodyScrolling(this);
    }
    requestClose(source) {
        if ((source == 'overlay' || source == 'keyboard') && this.preventOverlayClose)
            return;
        const slRequestClose = this.emit('nile-request-close', {
            cancelable: true,
            detail: { source }
        });
        if (slRequestClose.defaultPrevented) {
            const animation = getAnimation(this, 'drawer.denyClose', { dir: '' });
            animateTo(this.panel, animation.keyframes, animation.options);
            return;
        }
        this.hide();
    }
    addOpenListeners() {
        if (this.closeOnEscape)
            document.addEventListener('keydown', this.handleDocumentKeyDown);
    }
    removeOpenListeners() {
        if (this.closeOnEscape)
            document.removeEventListener('keydown', this.handleDocumentKeyDown);
    }
    handleDocumentKeyDown(event) {
        if (this.open && !this.contained && event.key === 'Escape') {
            event.stopPropagation();
            this.requestClose('keyboard');
        }
    }
    async handleOpenChange() {
        if (this.open) {
            // Show
            this.emit('nile-show');
            this.addOpenListeners();
            this.originalTrigger = document.activeElement;
            // Lock body scrolling only if the drawer isn't contained
            if (!this.contained) {
                this.modal.activate();
                lockBodyScrolling(this);
            }
            // When the drawer is shown, Safari will attempt to set focus on whatever element has autofocus. This causes the
            // drawer's animation to jitter, so we'll temporarily remove the attribute, call `focus({ preventScroll: true })`
            // ourselves, and add the attribute back afterwards.
            //
            //
            const autoFocusTarget = this.querySelector('[autofocus]');
            if (autoFocusTarget) {
                autoFocusTarget.removeAttribute('autofocus');
            }
            await Promise.all([stopAnimations(this.drawer), stopAnimations(this.overlay)]);
            this.drawer.hidden = false;
            // Set initial focus
            requestAnimationFrame(() => {
                const slInitialFocus = this.emit('nile-initial-focus', { cancelable: true });
                if (!slInitialFocus.defaultPrevented) {
                    // Set focus to the autofocus target and restore the attribute
                    if (autoFocusTarget) {
                        autoFocusTarget.focus({ preventScroll: true });
                    }
                    else {
                        this.panel.focus({ preventScroll: true });
                    }
                }
                // Restore the autofocus attribute
                if (autoFocusTarget) {
                    autoFocusTarget.setAttribute('autofocus', '');
                }
            });
            const panelAnimation = getAnimation(this, `drawer.show${uppercaseFirstLetter(this.placement)}`, {
                dir: ''
            });
            const overlayAnimation = getAnimation(this, 'drawer.overlay.show', { dir: '' });
            await Promise.all([
                animateTo(this.panel, panelAnimation.keyframes, panelAnimation.options),
                animateTo(this.overlay, overlayAnimation.keyframes, overlayAnimation.options)
            ]);
            this.emit('nile-after-show');
        }
        else {
            // Hide
            this.emit('nile-hide');
            this.removeOpenListeners();
            if (!this.contained) {
                this.modal.deactivate();
                unlockBodyScrolling(this);
            }
            await Promise.all([stopAnimations(this.drawer), stopAnimations(this.overlay)]);
            const panelAnimation = getAnimation(this, `drawer.hide${uppercaseFirstLetter(this.placement)}`, {
                dir: ''
            });
            const overlayAnimation = getAnimation(this, 'drawer.overlay.hide', { dir: '' });
            // Animate the overlay and the panel at the same time. Because animation durations might be different, we need to
            // hide each one individually when the animation finishes, otherwise the first one that finishes will reappear
            // unexpectedly. We'll unhide them after all animations have completed.
            await Promise.all([
                animateTo(this.overlay, overlayAnimation.keyframes, overlayAnimation.options).then(() => {
                    this.overlay.hidden = true;
                }),
                animateTo(this.panel, panelAnimation.keyframes, panelAnimation.options).then(() => {
                    this.panel.hidden = true;
                })
            ]);
            this.drawer.hidden = true;
            // Now that the dialog is hidden, restore the overlay and panel for next time
            this.overlay.hidden = false;
            this.panel.hidden = false;
            // Restore focus to the original trigger
            const trigger = this.originalTrigger;
            if (typeof trigger?.focus === 'function') {
                setTimeout(() => trigger.focus());
            }
            this.emit('nile-after-hide');
        }
    }
    handleNoModalChange() {
        if (this.open && !this.contained) {
            this.modal.activate();
            lockBodyScrolling(this);
        }
        if (this.open && this.contained) {
            this.modal.deactivate();
            unlockBodyScrolling(this);
        }
    }
    /** Shows the drawer. */
    async show() {
        if (this.open) {
            return undefined;
        }
        this.open = true;
        return waitForEvent(this, 'nile-after-show');
    }
    /** Hides the drawer */
    async hide() {
        if (!this.open) {
            return undefined;
        }
        this.open = false;
        return waitForEvent(this, 'nile-after-hide');
    }
    render() {
        return html `
      <div
        part="base"
        class=${classMap({
            drawer: true,
            'drawer--open': this.open,
            'drawer--top': this.placement === 'top',
            'drawer--end': this.placement === 'end',
            'drawer--bottom': this.placement === 'bottom',
            'drawer--start': this.placement === 'start',
            'drawer--contained': this.contained,
            'drawer--fixed': !this.contained,
            'drawer--rtl': 'rtl',
            'drawer--has-footer': this.hasSlotController.test('footer'),
        })}
      >
        <div
          part="overlay"
          class="drawer__overlay"
          @click=${() => this.requestClose('overlay')}
          tabindex="-1"
        ></div>

        <div
          part="panel"
          class="drawer__panel"
          role="dialog"
          aria-modal="true"
          aria-hidden=${this.open ? 'false' : 'true'}
          aria-label=${ifDefined(this.noHeader ? this.label : undefined)}
          aria-labelledby=${ifDefined(!this.noHeader ? 'title' : undefined)}
          tabindex="0"
        >
          ${!this.noHeader
            ? html `
                <header part="header" class="drawer__header">
                  <h2 part="title" class="drawer__title" id="title">
                    <!-- If there's no label, use an invisible character to prevent the header from collapsing -->
                    <slot name="label">
                      ${this.label.length > 0
                ? this.label
                : String.fromCharCode(65279)}
                    </slot>
                  </h2>
                  <div part="header-actions" class="drawer__header-actions">
                    <slot name="header-actions"></slot>
                    <nile-icon
                      class="drawer__close"
                      name="var(--nile-icon-close, var(--ng-icon-x-close))"
                      method="var(--nile-svg-method-fill, var(--ng-svg-method-stroke))"
                      label="close"
                      part="close-button"
                      exportparts="base:close-button__base"
                      color="var(--nile-drawer-remove-icon-color)"
                      @click=${() => this.requestClose('close-button')}
                    ></nile-icon>
                  </div>
                </header>
              `
            : ''}

          <slot part="body" class="drawer__body"></slot>

          <footer part="footer" class="drawer__footer">
            <slot name="footer"></slot>
          </footer>
        </div>
      </div>
    `;
    }
};
NileDrawer.styles = styles;
__decorate([
    query('.drawer')
], NileDrawer.prototype, "drawer", void 0);
__decorate([
    query('.drawer__panel')
], NileDrawer.prototype, "panel", void 0);
__decorate([
    query('.drawer__overlay')
], NileDrawer.prototype, "overlay", void 0);
__decorate([
    property({ type: Boolean, reflect: true })
], NileDrawer.prototype, "open", void 0);
__decorate([
    property({ type: Boolean, reflect: true })
], NileDrawer.prototype, "closeOnEscape", void 0);
__decorate([
    property({ reflect: true })
], NileDrawer.prototype, "label", void 0);
__decorate([
    property({ reflect: true })
], NileDrawer.prototype, "placement", void 0);
__decorate([
    property({ type: Boolean, reflect: true })
], NileDrawer.prototype, "contained", void 0);
__decorate([
    property({ type: Boolean, reflect: true })
], NileDrawer.prototype, "preventOverlayClose", void 0);
__decorate([
    property({ attribute: 'no-header', type: Boolean, reflect: true })
], NileDrawer.prototype, "noHeader", void 0);
__decorate([
    watch('open', { waitUntilFirstUpdate: true })
], NileDrawer.prototype, "handleOpenChange", null);
__decorate([
    watch('contained', { waitUntilFirstUpdate: true })
], NileDrawer.prototype, "handleNoModalChange", null);
NileDrawer = __decorate([
    customElement('nile-drawer')
], NileDrawer);
export { NileDrawer };
// Top
setDefaultAnimation('drawer.showTop', {
    keyframes: [
        { opacity: 0, translate: '0 -100%' },
        { opacity: 1, translate: '0 0' }
    ],
    options: { duration: 250, easing: 'ease' }
});
setDefaultAnimation('drawer.hideTop', {
    keyframes: [
        { opacity: 1, translate: '0 0' },
        { opacity: 0, translate: '0 -100%' }
    ],
    options: { duration: 250, easing: 'ease' }
});
// End
setDefaultAnimation('drawer.showEnd', {
    keyframes: [
        { opacity: 0, translate: '100%' },
        { opacity: 1, translate: '0' }
    ],
    rtlKeyframes: [
        { opacity: 0, translate: '-100%' },
        { opacity: 1, translate: '0' }
    ],
    options: { duration: 250, easing: 'ease' }
});
setDefaultAnimation('drawer.hideEnd', {
    keyframes: [
        { opacity: 1, translate: '0' },
        { opacity: 0, translate: '100%' }
    ],
    rtlKeyframes: [
        { opacity: 1, translate: '0' },
        { opacity: 0, translate: '-100%' }
    ],
    options: { duration: 250, easing: 'ease' }
});
// Bottom
setDefaultAnimation('drawer.showBottom', {
    keyframes: [
        { opacity: 0, translate: '0 100%' },
        { opacity: 1, translate: '0 0' }
    ],
    options: { duration: 250, easing: 'ease' }
});
setDefaultAnimation('drawer.hideBottom', {
    keyframes: [
        { opacity: 1, translate: '0 0' },
        { opacity: 0, translate: '0 100%' }
    ],
    options: { duration: 250, easing: 'ease' }
});
// Start
setDefaultAnimation('drawer.showStart', {
    keyframes: [
        { opacity: 0, translate: '-100%' },
        { opacity: 1, translate: '0' }
    ],
    rtlKeyframes: [
        { opacity: 0, translate: '100%' },
        { opacity: 1, translate: '0' }
    ],
    options: { duration: 250, easing: 'ease' }
});
setDefaultAnimation('drawer.hideStart', {
    keyframes: [
        { opacity: 1, translate: '0' },
        { opacity: 0, translate: '-100%' }
    ],
    rtlKeyframes: [
        { opacity: 1, translate: '0' },
        { opacity: 0, translate: '100%' }
    ],
    options: { duration: 250, easing: 'ease' }
});
// Deny close
setDefaultAnimation('drawer.denyClose', {
    keyframes: [{ scale: 1 }, { scale: 1.01 }, { scale: 1 }],
    options: { duration: 250 }
});
// Overlay
setDefaultAnimation('drawer.overlay.show', {
    keyframes: [{ opacity: 0 }, { opacity: 1 }],
    options: { duration: 250 }
});
setDefaultAnimation('drawer.overlay.hide', {
    keyframes: [{ opacity: 1 }, { opacity: 0 }],
    options: { duration: 250 }
});
//# sourceMappingURL=nile-drawer.js.map