// #region Imports
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { DomServiceLocator } from '../../../../Dom/Dom';
import { Emit } from '../../../../Events/Decorators/EmitDecorator';
import { HTMLElementEventEmitter } from '@breadstone/mosaik-elements';
import { Appearanceable } from '../../../Behaviors/Appearanceable';
import { Clearable } from '../../../Behaviors/Clearable';
import { Disableable } from '../../../Behaviors/Disableable';
import { Invalidable } from '../../../Behaviors/Invalidable';
import { Labelable } from '../../../Behaviors/Labelable';
import { Slottable } from '../../../Behaviors/Slottable';
import { Valueable } from '../../../Behaviors/Valueable';
import { Variantable } from '../../../Behaviors/Variantable';
import { KeyboardController } from '../../../Controllers/KeyboardController';
import { Attribute } from '../../../Decorators/AttributeDecorator';
import { Component } from '../../../Decorators/ComponentDecorator';
import { Key } from '../../../Types/Key';
import { KeyName } from '../../../Types/Key';
import { ButtonElement } from '../../Buttons/Button/ButtonElement';
import { ChipElement } from '../../Media/Chip/ChipElement';
import { InputBaseElement } from '../Abstracts/InputBase';
import { chipBoxElementTemplate } from './ChipBoxElementTemplate';
import { chipBoxElementJoyStyle } from './Themes/ChipBoxElement.Joy';
import { chipBoxElementRetroStyle } from './Themes/ChipBoxElement.Retro';
import { chipBoxElementCosmopolitanStyle } from './Themes/ChipBoxElement.Cosmopolitan';
import { Themeable } from '../../../Behaviors/Themeable';
// #endregion
/**
 * Chip Box - A user interface element for displaying and managing multiple chips.
 *
 * @element mosaik-chipbox
 *
 * @description
 * The Chip Box component is designed to display and manage multiple chips, which are small, interactive elements
 * used to represent selections, chips, or pieces of information. Chip Boxes are commonly used in scenarios
 * where users need to make multiple selections, filter content, or display categorized items. Users can interact
 * with the chips to add or remove selections or filter content.
 *
 * @category Forms
 *
 * @fires cleared - Fired when the value is cleared.
 * @fires chipAdded - Fired when a chip is added.
 * @fires chipRemoved - Fired when a chip is removed.
 *
 * @keyhandle Enter - Adds a chip.
 * @keyhandle Comma - Adds a chip.
 * @keyhandle LeftArrow - Focuses the previous chip.
 * @keyhandle RightArrow - Focuses the next chip.
 * @keyhandle Backspace - Removes the focused chip.
 *
 * @public
 */
let ChipBoxElement = class ChipBoxElement extends Themeable(Slottable(Clearable(Disableable(Invalidable(Valueable(Variantable(Appearanceable(Labelable(InputBaseElement))))))))) {
    // #region Fields
    _chipElements;
    _inputElement;
    _keyboardController;
    _chipAdded;
    _chipRemoved;
    _isEditable;
    _readonly;
    _pressBackspaceToRemove;
    _chips;
    _separatorKeys;
    _transform;
    _value;
    _required;
    _autofocus;
    _name;
    _pattern;
    _placeholder;
    _autocomplete;
    // #endregion
    // #region Ctor
    /**
     * @public
     */
    constructor() {
        super();
        this._value = '';
        this._readonly = false;
        this._required = false;
        this._autofocus = false;
        this._name = '';
        this._pattern = '';
        this._placeholder = '';
        this._autocomplete = false;
        this._isEditable = false;
        this._readonly = false;
        this._chips = [];
        this._separatorKeys = new Array(Key.Enter, Key.Comma);
        this._pressBackspaceToRemove = false;
        this._transform = null;
        this._chipAdded = new HTMLElementEventEmitter(this, 'chipAdded');
        this._chipRemoved = new HTMLElementEventEmitter(this, 'chipRemoved');
        this._keyboardController = new KeyboardController(this);
    }
    // #endregion
    // #region Properties
    /**
     * Returns the `{@link is}` property.
     * The `{@link is}` property represents natural name of this element.
     *
     * @public
     * @static
     * @readonly
     */
    static get is() {
        return 'mosaik-chipbox';
    }
    /**
     * Gets or sets the `value` property.
     *
     * @public
     * @override
     */
    get value() {
        return this._value;
    }
    set value(value) {
        if (this._value !== value) {
            this._value = value;
            this.requestUpdate('value');
        }
    }
    /**
     * Gets or sets the `required` property.
     *
     * @public
     * @attr
     */
    get required() {
        return this._required;
    }
    set required(value) {
        if (this._required !== value) {
            this._required = value;
            this.requestUpdate('required');
        }
    }
    /**
     * Gets or sets the `autofocus` property.
     *
     * @public
     * @override
     */
    get autofocus() {
        return this._autofocus;
    }
    set autofocus(value) {
        if (this._autofocus !== value) {
            this._autofocus = value;
            this.requestUpdate('autofocus');
        }
    }
    /**
     * Gets or sets the `name` property.
     *
     * @public
     * @attr
     */
    get name() {
        return this._name;
    }
    set name(value) {
        if (this._name !== value) {
            this._name = value;
            this.requestUpdate('name');
        }
    }
    /**
     * Gets or sets the `pattern` property.
     *
     * @public
     * @attr
     */
    get pattern() {
        return this._pattern;
    }
    set pattern(value) {
        if (this._pattern !== value) {
            this._pattern = value;
            this.requestUpdate('pattern');
        }
    }
    /**
     * Gets or sets the `placeholder` property.
     *
     * @public
     * @attr
     */
    get placeholder() {
        return this._placeholder;
    }
    set placeholder(value) {
        if (this._placeholder !== value) {
            this._placeholder = value;
            this.requestUpdate('placeholder');
        }
    }
    /**
     * Gets or sets the `autocomplete` property.
     *
     * @public
     * @attr
     */
    get autocomplete() {
        return this._autocomplete;
    }
    set autocomplete(value) {
        if (this._autocomplete !== value) {
            this._autocomplete = value;
            this.requestUpdate('autocomplete');
        }
    }
    /**
     * Gets or sets the `isEditable` property.
     *
     * @public
     * @attr
     */
    get isEditable() {
        return this._isEditable;
    }
    set isEditable(value) {
        if (this._isEditable !== value) {
            this._isEditable = value;
            this.requestUpdate('isEditable');
        }
    }
    /**
     * Gets or sets the `readonly` property.
     *
     * @public
     * @attr
     */
    get readonly() {
        return this._readonly;
    }
    set readonly(value) {
        if (this._readonly !== value) {
            this._readonly = value;
            this.requestUpdate('readonly');
        }
    }
    /**
     * Gets or sets the `pressBackspaceToRemove` property.
     *
     * @public
     * @attr
     */
    get pressBackspaceToRemove() {
        return this._pressBackspaceToRemove;
    }
    set pressBackspaceToRemove(value) {
        if (this._pressBackspaceToRemove !== value) {
            this._pressBackspaceToRemove = value;
            this.requestUpdate('pressBackspaceToRemove');
        }
    }
    /**
     * Gets or sets the `chips` property.
     *
     * @public
     * @attr
     */
    get chips() {
        return this._chips;
    }
    set chips(value) {
        if (this._chips !== value) {
            this._chips = value;
            this.requestUpdate('chips');
        }
    }
    /**
     * Gets or sets the `separatorKeys` property.
     *
     * @public
     * @attr
     */
    get separatorKeys() {
        return this._separatorKeys;
    }
    set separatorKeys(value) {
        if (this._separatorKeys !== value) {
            this._separatorKeys = value;
            this.requestUpdate('separatorKeys');
        }
    }
    /**
     * Gets or sets the `transform` property.
     *
     * @public
     * @attr
     */
    get transform() {
        return this._transform;
    }
    set transform(value) {
        if (this._transform !== value) {
            this._transform = value;
            this.requestUpdate('transform');
        }
    }
    /**
     * Determines whether the element has a prefix or not.
     * The Prefix is a slot that is displayed before the input.
     *
     * @private
     * @readonly
     * @attr
     */
    get hasPrefix() {
        return this.hasSlotContent('prefix');
    }
    /**
     * Determines whether the element has a suffix or not.
     * The Suffix is a slot that is displayed after the input.
     *
     * @private
     * @readonly
     * @attr
     */
    get hasSuffix() {
        return this.hasSlotContent('suffix');
    }
    /**
     * Called when a chip is added.
     * Provides reference to `{chip:unknown}` as event argument.
     *
     * @public
     * @readonly
     * @eventProperty
     */
    get chipAdded() {
        return this._chipAdded;
    }
    /**
     * Called when a chip is removed.
     * Provides reference to `{chip: unknown}` as event argument.
     *
     * @public
     * @readonly
     * @eventProperty
     */
    get chipRemoved() {
        return this._chipRemoved;
    }
    // #endregion
    // #region Methods
    /**
     * @public
     * @override
     */
    connectedCallback() {
        super.connectedCallback();
        this._keyboardController
            .add([Key.LeftArrow], (event) => {
            event?.preventDefault();
            // check if input is focused
            if (this.shadowRoot?.activeElement === this._inputElement) {
                // detect the cursor position of the input
                const isStart = this._inputElement.selectionStart === 0;
                if (isStart) {
                    // focus the last chip
                    this._chipElements[this.chips.length - 1]?.focus();
                }
                return;
            }
            // check if chip is focused
            if (this._chipElements.some((x) => x.isFocused)) {
                // focus the previous chip
                const index = this._chipElements.findIndex((x) => x.isFocused);
                this._chipElements[index - 1]?.focus();
            }
        })
            .add([Key.RightArrow], (event) => {
            event?.preventDefault();
            // check if chip is focused
            if (this._chipElements.some((x) => x.isFocused)) {
                const index = this._chipElements.findIndex((x) => x.isFocused);
                if (index === this.chips.length - 1) {
                    // if the last chip is focused, focus the input
                    this._inputElement.focus();
                }
                else {
                    // focus the next chip
                    this._chipElements[index + 1]?.focus();
                }
            }
        })
            .add([
            Key.Delete,
            Key.Backspace
        ], (event) => {
            event?.preventDefault();
            // check if chip is focused
            if (this._chipElements.some((x) => x.isFocused)) {
                const index = this._chipElements.findIndex((x) => x.isFocused);
                const chip = this.chips[index];
                this.delete(chip);
                // after deleting the chip, focus the next chip or the input
                if (index === this.chips.length - 1) {
                    this._inputElement.focus();
                }
                else {
                    this._chipElements[index]?.focus();
                }
            }
        });
        this.on('click', () => this.focus());
    }
    /**
     * @public
     * @override
     */
    focus() {
        if (this.shadowRoot) {
            DomServiceLocator.current.findDescendant(this.shadowRoot, 'input')?.focus();
        }
    }
    /**
     * @public
     * @override
     */
    blur() {
        if (this.shadowRoot) {
            DomServiceLocator.current.findDescendant(this.shadowRoot, 'input')?.blur();
        }
    }
    /**
     * Clears the value of the element but not the validation.
     *
     * @public
     * @override
     */
    clear(force) {
        const isCleared = super.clear(force);
        if (isCleared) {
            if (!this.readonly) {
                this.emit('input', {
                    bubbles: true,
                    composed: true
                });
            }
            this.emit('change', {
                bubbles: true,
                composed: true
            });
        }
        return isCleared;
    }
    /**
     * Resets the value, all kinds of validation and errors.
     *
     * @public
     * @override
     */
    reset() {
        super.reset();
        this.clear();
        this.invalid = false;
    }
    /**
     * Checks the validity of the element and returns `true` if it is valid; otherwise, `false`.
     *
     * @public
     * @override
     */
    checkValidity() {
        return this.shadowRoot
            ? this._inputElement.checkValidity()
            : true;
    }
    /**
     * @public
     */
    add(chip) {
        // disallow duplicates
        if (this.chips.includes(chip)) {
            return;
        }
        this.chips.push(chip);
        this.onChipAdded({ chip: chip });
        this.clear();
    }
    /**
     * @public
     */
    delete(chip) {
        if (!this._isEditable) {
            return;
        }
        // remove chip from chip list
        const index = this._chips.indexOf(chip);
        if (index > -1) {
            this.chips.splice(index, 1);
            this.requestUpdate('chips');
        }
        this.onChipRemoved({ chip: chip });
        this.clear();
    }
    /**
     * @protected
     * @template
     */
    onKeyUp(event) {
        event.preventDefault();
        if (!this._isEditable) {
            return;
        }
        if (this._separatorKeys.includes(event.keyCode)) {
            if (this._inputElement.value.trim() !== '') {
                const chip = this._inputElement.value.replace(String.fromCharCode(event.keyCode), '');
                this.add(chip);
            }
            this.clear();
        }
    }
    /**
     * @protected
     * @template
     */
    onKeyDown(event) {
        if (event.key === KeyName.Backspace) {
            event.preventDefault();
            // focus last chip on backspace
            if (this._pressBackspaceToRemove && this._inputElement.value === '' && this.chips.length > 0) {
                // check if input or chip is focused
                const chips = this._chipElements;
                if (this._inputElement !== this.shadowRoot?.activeElement && chips.some((x) => x.isFocused)) {
                    const chip = this.chips[this.chips.length - 1];
                    this.delete(chip);
                }
                else {
                    this._chipElements[this.chips.length - 1].focus();
                }
            }
        }
    }
    /**
     * @protected
     * @template
     */
    onPaste(event) {
        event.stopPropagation();
        const paste = event.clipboardData?.getData('text') ?? '';
        const chips = paste.split('\n');
        const transform = this._transform ?? ((x) => x);
        chips.forEach((x) => this.add(transform(x)));
        this.clear();
    }
    /**
     * @protected
     */
    onChipClosed(chip) {
        this.delete(chip);
        this.onChipRemoved({ chip: chip });
    }
    /**
     * Emits the {@link chipAdded} event.
     *
     * @protected
     */
    onChipAdded(args) {
        this._chipAdded.emit(args);
    }
    /**
     * Emits the {@link chipRemoved} event.
     *
     * @protected
     */
    onChipRemoved(args) {
        this._chipRemoved.emit(args);
    }
    /**
     * @protected
     * @override
     */
    onApplyTemplate() {
        super.onApplyTemplate();
        this._inputElement = this.getTemplatePart('input');
        this._chipElements = this.getTemplateParts('chip');
    }
    /**
     * @template
     * @protected
     */
    onChange(event) {
        this.value = event.target.value;
        this.emit('change', { detail: this.value });
    }
    /**
     * @template
     * @protected
     * @override
     */
    onInput(event) {
        super.onInput(event);
        this.value = event.target.value;
        this.emit('input', { detail: this.value });
    }
    /**
     * @template
     * @protected
     * @override
     */
    onFocus(event) {
        super.onFocus(event);
        this.emit('focus', { detail: event });
    }
    /**
     * @template
     * @protected
     * @override
     */
    onBlur(event) {
        super.onBlur(event);
        // add chip if input is not empty
        if (this._inputElement.value.trim() !== '') {
            const chip = this._inputElement.value;
            this.add(chip);
            this.clear();
        }
        this.emit('blur', { detail: event });
    }
};
__decorate([
    Attribute({ type: String }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], ChipBoxElement.prototype, "value", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], ChipBoxElement.prototype, "required", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], ChipBoxElement.prototype, "autofocus", null);
__decorate([
    Attribute({ type: String }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], ChipBoxElement.prototype, "name", null);
__decorate([
    Attribute({ type: String }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], ChipBoxElement.prototype, "pattern", null);
__decorate([
    Attribute({ type: String }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], ChipBoxElement.prototype, "placeholder", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], ChipBoxElement.prototype, "autocomplete", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], ChipBoxElement.prototype, "isEditable", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], ChipBoxElement.prototype, "readonly", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], ChipBoxElement.prototype, "pressBackspaceToRemove", null);
__decorate([
    Attribute({
        type: (Array),
        converter: {
            fromAttribute: (value) => {
                if (!value) {
                    return [];
                }
                return value
                    .split(' ')
                    .map((v) => v.trim());
            },
            toAttribute: (value) => value.join(' ')
        }
    }),
    __metadata("design:type", Array),
    __metadata("design:paramtypes", [Array])
], ChipBoxElement.prototype, "chips", null);
__decorate([
    Attribute({ type: (Array) }),
    __metadata("design:type", Array),
    __metadata("design:paramtypes", [Array])
], ChipBoxElement.prototype, "separatorKeys", null);
__decorate([
    Attribute({ type: Function }),
    __metadata("design:type", Object),
    __metadata("design:paramtypes", [Object])
], ChipBoxElement.prototype, "transform", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [])
], ChipBoxElement.prototype, "hasPrefix", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [])
], ChipBoxElement.prototype, "hasSuffix", null);
__decorate([
    Emit(),
    __metadata("design:type", Object),
    __metadata("design:paramtypes", [])
], ChipBoxElement.prototype, "chipAdded", null);
__decorate([
    Emit(),
    __metadata("design:type", Object),
    __metadata("design:paramtypes", [])
], ChipBoxElement.prototype, "chipRemoved", null);
ChipBoxElement = __decorate([
    Component({
        selector: 'mosaik-chipbox',
        template: chipBoxElementTemplate,
        themes: {
            joy: chipBoxElementJoyStyle,
            retro: chipBoxElementRetroStyle,
            cosmopolitan: chipBoxElementCosmopolitanStyle
        },
        host: {
            tabIndex: '0'
        },
        options: {
            mode: 'open',
            delegatesFocus: true
        },
        imports: [
            ChipElement,
            ButtonElement
        ]
    }),
    __metadata("design:paramtypes", [])
], ChipBoxElement);
export { ChipBoxElement };
//# sourceMappingURL=ChipBoxElement.js.map