import { __decorate } from "tslib";
import { html, nothing } from "lit";
import { property, queryAsync, state } from "lit/decorators.js";
import { classMap } from "lit/directives/class-map.js";
import { when } from 'lit/directives/when.js';
import { EventUtils } from "@api-client/core/build/browser.js"; // build/src/lib/events/Utils.js
import { UiElement } from "../UiElement.js";
import { ripple } from '../effects/rippleDirective.js';
import { close, arrowDropDown, check } from "../icons/Icons.js";
import { isDisabled, setDisabled } from "../lib/disabled.js";
import '../../define/ui/ui-ripple.js';
export var ChipType;
(function (ChipType) {
    ChipType["assist"] = "assist";
    ChipType["filter"] = "filter";
    ChipType["input"] = "input";
    ChipType["suggestion"] = "suggestion";
})(ChipType || (ChipType = {}));
/**
 * @slot icon - The leading icon, sized 18x18 px
 * @slot avatar - The leading image, sized 24x24 px
 * @fires list - When the user requested to activate the list associated with the element.
 * @fires select - When the checked state changed through a user interaction. This only related to `filter` chips. Note, `select` is dispatched just before the `click` event.
 */
export default class UiChip extends UiElement {
    /**
     * Whether the chip is disabled. The user can't interact with the chip when `true`.
     * @attribute
     */
    get disabled() {
        return isDisabled(this);
    }
    set disabled(value) {
        const old = isDisabled(this);
        setDisabled(this, value);
        this.requestUpdate('disabled', old);
    }
    constructor() {
        super();
        this.showRipple = false;
        this.getRipple = () => {
            this.showRipple = true;
            return this.ripple;
        };
        this.renderRipple = () => {
            const { disabled } = this;
            return html `<ui-ripple class="ripple" ?disabled="${disabled}"></ui-ripple>`;
        };
        this.disabled = false;
        this.type = ChipType.assist;
        this.hasIcon = false;
        this.hasAvatar = false;
        this.actionController.cancelKeyboardEvents = true;
        this.addEventListener('click', this.handleClick.bind(this));
        this.addEventListener('keydown', this.handleKeyDown.bind(this));
        this.addEventListener('keyup', this.handleKeyUp.bind(this));
        this.addEventListener('pointerdown', this.handlePointerDown.bind(this));
        this.addEventListener('pointerup', this.handlePointerUp.bind(this));
        this.addEventListener('pointercancel', this.handlePointerCancel.bind(this));
        this.addEventListener('pointerleave', this.handlePointerLeave.bind(this));
        this.addEventListener('contextmenu', this.handleContextMenu.bind(this));
        this.addEventListener('focus', this.handleFocus.bind(this));
        this.addEventListener('blur', this.handleBlur.bind(this));
    }
    connectedCallback() {
        super.connectedCallback();
        if (!this.hasAttribute('role')) {
            this.setAttribute('role', 'button');
        }
        if (!this.hasAttribute('tabindex') && !this.disabled) {
            this.setAttribute('tabindex', '0');
        }
    }
    async pressRipple() {
        const element = await this.getRipple();
        if (element && !element.isPressed) {
            element.beginPress();
        }
    }
    async endRipple() {
        const element = await this.getRipple();
        element?.endPress();
    }
    beginPress(options) {
        super.beginPress(options);
        this.pressRipple();
    }
    async handleKeyDown(e) {
        super.handleKeyDown(e);
        if (this.type === ChipType.filter && e.code === 'ArrowDown') {
            e.preventDefault();
            this.listAction();
        }
        else if (this.closable && e.code === 'Backspace') {
            e.preventDefault();
            this.closeAction();
        }
    }
    async handleFocus() {
        const element = await this.getRipple();
        element?.beginFocus();
    }
    async handleBlur() {
        const element = await this.getRipple();
        element?.endFocus();
    }
    endPress(info) {
        super.endPress(info);
        this.endRipple();
        const { cancelled, reason } = info;
        if (cancelled) {
            return;
        }
        if (reason === 'enter' || reason === 'space') {
            this.click();
        }
    }
    handleClick(e) {
        super.handleClick(e);
        if (this.type === ChipType.filter) {
            this.toggleChecked();
        }
    }
    /**
     * Toggles the "filter" type of the chip.
     */
    toggleChecked() {
        this.checked = !this.checked;
        this.dispatchEvent(new Event('select'));
    }
    /**
     * Sets the `hasIcon` state property when the "icon" slot change event is dispatched.
     */
    handleIconSlotChange(e) {
        const slot = e.target;
        this.hasIcon = !!slot.assignedNodes().length;
    }
    /**
     * Sets the `_hasAvatar` state property when the "avatar" slot change event is dispatched.
     */
    handleAvatarSlotChange(e) {
        const slot = e.target;
        this.hasAvatar = !!slot.assignedNodes().length;
    }
    handleListClick(e) {
        e.preventDefault();
        e.stopPropagation();
        this.listAction();
    }
    handleClose(e) {
        e.preventDefault();
        e.stopPropagation();
        this.closeAction();
    }
    async closeAction() {
        this.dispatchEvent(new Event('close'));
    }
    async listAction() {
        this.dispatchEvent(new Event('list'));
    }
    render() {
        const { pressed = false } = this;
        const containerClasses = classMap({
            surface: true,
            withIcon: this.hasIcon,
            withAvatar: this.hasAvatar,
            pressed,
        });
        return html `
    <div class="${containerClasses}" ${ripple(this.getRipple)}>
      <div class="container"></div>
      ${when(this.showRipple, this.renderRipple)}
      <div class="content">
        ${this.renderLeadingIcon()}
        ${this.renderAvatar()}
        <slot></slot>
        ${this.renderTrailingIcon()}
      </div>
    </div>
    `;
    }
    renderLeadingIcon() {
        const { type } = this;
        if (type === ChipType.suggestion) {
            return nothing;
        }
        if (type === ChipType.filter) {
            const iconClasses = classMap({
                'leading-icon': true,
                'check-mark': true,
                checked: !!this.checked,
            });
            return html `<span class="${iconClasses}" role="presentation">${check}</span>`;
        }
        return html `<slot name="icon" @slotchange="${this.handleIconSlotChange}"></slot>`;
    }
    renderAvatar() {
        const { type } = this;
        if (type === ChipType.input) {
            return html `<slot name="avatar" @slotchange="${this.handleAvatarSlotChange}"></slot>`;
        }
        return nothing;
    }
    renderTrailingIcon() {
        const { closable = false, list, type } = this;
        if (type === ChipType.filter) {
            if (list) {
                return html `<span class="trailing-icon" role="presentation" @click="${this.handleListClick}" @keypress="${EventUtils.cancelEvent}">${arrowDropDown}</span>`;
            }
        }
        if (type === ChipType.input && closable) {
            return html `<span 
        class="trailing-icon" 
        @click="${this.handleClose}" 
        @keypress="${EventUtils.cancelEvent}"
        role="button"
        aria-label="Activate to close or disabled this chip."
      >${close}</span>`;
        }
        return nothing;
    }
}
__decorate([
    property({ type: Boolean, reflect: true })
], UiChip.prototype, "disabled", null);
__decorate([
    property({ type: String })
], UiChip.prototype, "type", void 0);
__decorate([
    property({ type: Boolean, reflect: true })
], UiChip.prototype, "elevated", void 0);
__decorate([
    property({ type: Boolean, reflect: true })
], UiChip.prototype, "closable", void 0);
__decorate([
    property({ type: Boolean, reflect: true })
], UiChip.prototype, "checked", void 0);
__decorate([
    property({ type: String, reflect: true })
], UiChip.prototype, "list", void 0);
__decorate([
    queryAsync('ui-ripple')
], UiChip.prototype, "ripple", void 0);
__decorate([
    state()
], UiChip.prototype, "showRipple", void 0);
__decorate([
    state()
], UiChip.prototype, "hasIcon", void 0);
__decorate([
    state()
], UiChip.prototype, "hasAvatar", void 0);
//# sourceMappingURL=UiChip.js.map