import * as i0 from '@angular/core';
import { EventEmitter, Component, Input, Output, forwardRef, ElementRef, ContentChildren, ViewChild, HostListener, NgModule } from '@angular/core';
import * as i1$1 from '@angular/forms';
import { NG_VALUE_ACCESSOR, FormsModule } from '@angular/forms';
import * as i2$1 from 'primeng/keyfilter';
import { KeyFilterModule } from 'primeng/keyfilter';
import { __decorate } from 'tslib';
import { CheckDisabled } from '@seniorsistemas/angular-components/shared';
import * as i1 from '@seniorsistemas/angular-components/tooltip';
import { TooltipModule } from '@seniorsistemas/angular-components/tooltip';
import * as i2 from '@angular/common';
import { NgTemplateOutlet } from '@angular/common';
import { TemplateDirective } from '@seniorsistemas/angular-components/template';
import { randomHash, isNullOrUndefined } from '@seniorsistemas/angular-components/utils';

class ChipItemComponent {
    dataRender;
    objectField;
    disabled = false;
    templateRef;
    itemIndex = -1;
    showTooltip = true;
    maxLengthRenderWithoutTooltip = 20;
    clickRemove = new EventEmitter();
    chipClicked = new EventEmitter();
    clickedRemove($event) {
        this.clickRemove.emit({ itemIndex: this.itemIndex, event: $event });
    }
    onChipClicked($event) {
        this.chipClicked.emit({ event: $event, data: this.dataRender });
    }
    get _text() {
        const _text = this._rawText;
        return _text.substring(0, _text.length > this.maxLengthRenderWithoutTooltip ? this.maxLengthRenderWithoutTooltip : _text.length) + (_text.length > this.maxLengthRenderWithoutTooltip ? '...' : '');
    }
    get _rawText() {
        return this.objectField ? this.dataRender[this.objectField] || '' : this.dataRender || '';
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: ChipItemComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
    static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "18.2.14", type: ChipItemComponent, selector: "s-chip-item", inputs: { dataRender: "dataRender", objectField: "objectField", disabled: "disabled", templateRef: "templateRef", itemIndex: "itemIndex", showTooltip: "showTooltip", maxLengthRenderWithoutTooltip: "maxLengthRenderWithoutTooltip" }, outputs: { clickRemove: "clickRemove", chipClicked: "chipClicked" }, ngImport: i0, template: "<ng-template #itemRender>\n    <div\n        class=\"chip-item\"\n        [class.chip-item-disabled]=\"disabled\"\n        (click)=\"onChipClicked($event)\" \n        [sTooltip]=\"_rawText\"\n        [showDelay]=\"0\"\n        [visible]=\"showTooltip ? _rawText.length > maxLengthRenderWithoutTooltip : false\">\n            @if(templateRef) {\n                <ng-container\n                    *ngTemplateOutlet=\"templateRef; context: { $implicit: dataRender, text: _text }\">\n                </ng-container>\n            } @else {\n                {{ _text }}\n            }\n            <i class=\"fas fa-times\" (click)=\"clickedRemove($event)\"></i>\n    </div>\n</ng-template>\n\n\n@if(objectField && !templateRef) {\n    <ng-container *ngTemplateOutlet=\"itemRender;\"></ng-container>\n}\n\n@if(!objectField && !templateRef) {\n    <ng-container *ngTemplateOutlet=\"itemRender;\"></ng-container>\n}\n\n@if(templateRef) {\n    <ng-container *ngTemplateOutlet=\"itemRender\"></ng-container>\n}\n", styles: [".chip-item{border-radius:4px;border:1px solid #888b99;background-color:#eeebf2;word-break:break-word;font-size:12px;font-weight:400;text-align:center;display:flex;align-items:center;gap:8px;padding:0 6px}.chip-item i{cursor:pointer}.chip-item:hover:not(.chip-item-disabled){background:#c1c1cc}.chip-item-disabled{opacity:.5}.chip-item-disabled i{cursor:default}\n"], dependencies: [{ kind: "directive", type: i1.TooltipDirective, selector: "[sTooltip]", inputs: ["sTooltip", "tooltipPosition", "showDelay", "displayTime", "tooltipEvent", "escape", "visible", "mobileBehavior", "focusedInputRef", "checkTruncatedText"] }, { kind: "directive", type: i2.NgTemplateOutlet, selector: "[ngTemplateOutlet]", inputs: ["ngTemplateOutletContext", "ngTemplateOutlet", "ngTemplateOutletInjector"] }] });
}
__decorate([
    CheckDisabled()
], ChipItemComponent.prototype, "clickedRemove", null);
__decorate([
    CheckDisabled()
], ChipItemComponent.prototype, "onChipClicked", null);
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: ChipItemComponent, decorators: [{
            type: Component,
            args: [{ selector: 's-chip-item', template: "<ng-template #itemRender>\n    <div\n        class=\"chip-item\"\n        [class.chip-item-disabled]=\"disabled\"\n        (click)=\"onChipClicked($event)\" \n        [sTooltip]=\"_rawText\"\n        [showDelay]=\"0\"\n        [visible]=\"showTooltip ? _rawText.length > maxLengthRenderWithoutTooltip : false\">\n            @if(templateRef) {\n                <ng-container\n                    *ngTemplateOutlet=\"templateRef; context: { $implicit: dataRender, text: _text }\">\n                </ng-container>\n            } @else {\n                {{ _text }}\n            }\n            <i class=\"fas fa-times\" (click)=\"clickedRemove($event)\"></i>\n    </div>\n</ng-template>\n\n\n@if(objectField && !templateRef) {\n    <ng-container *ngTemplateOutlet=\"itemRender;\"></ng-container>\n}\n\n@if(!objectField && !templateRef) {\n    <ng-container *ngTemplateOutlet=\"itemRender;\"></ng-container>\n}\n\n@if(templateRef) {\n    <ng-container *ngTemplateOutlet=\"itemRender\"></ng-container>\n}\n", styles: [".chip-item{border-radius:4px;border:1px solid #888b99;background-color:#eeebf2;word-break:break-word;font-size:12px;font-weight:400;text-align:center;display:flex;align-items:center;gap:8px;padding:0 6px}.chip-item i{cursor:pointer}.chip-item:hover:not(.chip-item-disabled){background:#c1c1cc}.chip-item-disabled{opacity:.5}.chip-item-disabled i{cursor:default}\n"] }]
        }], propDecorators: { dataRender: [{
                type: Input,
                args: [{ required: true }]
            }], objectField: [{
                type: Input,
                args: [{ required: true }]
            }], disabled: [{
                type: Input,
                args: [{ required: true }]
            }], templateRef: [{
                type: Input
            }], itemIndex: [{
                type: Input,
                args: [{ required: true }]
            }], showTooltip: [{
                type: Input,
                args: [{ required: true }]
            }], maxLengthRenderWithoutTooltip: [{
                type: Input,
                args: [{ required: true }]
            }], clickRemove: [{
                type: Output
            }], chipClicked: [{
                type: Output
            }], clickedRemove: [], onChipClicked: [] } });

class ChipsComponent {
    cdr;
    newItem = '';
    chipTemplate;
    disabled = false;
    field = '';
    value = [];
    placeholder;
    max = Infinity;
    maxLength = Infinity;
    inputId = `chips-${randomHash()}`;
    allowDuplicated = true;
    caseSensitiveDuplication = false;
    addOnTab = true;
    addOnBlur = true;
    separator = '';
    autofocus = false;
    infoLabel = '';
    keyFilter;
    showTooltip = true;
    maxLengthRenderWithoutTooltip = 20;
    added = new EventEmitter();
    removed = new EventEmitter();
    focused = new EventEmitter();
    focusLost = new EventEmitter();
    chipClicked = new EventEmitter();
    valueChange = new EventEmitter();
    templates = null;
    input = null;
    isFocused = false;
    onChange = () => { };
    onTouched = () => { };
    isTabEventActive = false;
    constructor(cdr) {
        this.cdr = cdr;
    }
    ngAfterViewInit() {
        if (this.autofocus && this.input) {
            this.input.nativeElement.focus();
        }
        if (this.templates) {
            this.chipTemplate = this.templates.find((x) => x.type === 'chip-container')?.template;
            this.cdr.detectChanges();
        }
    }
    writeValue(obj) {
        if (isNullOrUndefined(obj)) {
            obj = [];
        }
        this.value = obj;
    }
    registerOnChange(fn) {
        this.onChange = fn;
    }
    registerOnTouched(fn) {
        this.onTouched = fn;
    }
    setDisabledState(isDisabled) {
        this.disabled = isDisabled;
    }
    onKeydown($event) {
        const isEnter = $event.key === 'Enter';
        const isSeparator = this.separator && $event.key === this.separator;
        const eventKeyIsTab = $event.key === 'Tab';
        if (eventKeyIsTab) {
            const tabTimeoutTime = 50;
            this.isTabEventActive = true;
            setTimeout(() => {
                this.isTabEventActive = false;
            }, tabTimeoutTime);
        }
        const isTab = this.addOnTab && eventKeyIsTab;
        if (isEnter || isSeparator || isTab) {
            $event.preventDefault();
            this.addItem();
        }
    }
    onInputFocus($event) {
        this.focused.emit($event);
        this.isFocused = true;
    }
    onInputLostFocus($event) {
        this.isFocused = false;
        if (!this.addOnBlur || this.isTabEventActive) {
            return;
        }
        this.addItem();
        this.focusLost.emit($event);
    }
    removeItem({ itemIndex, event }) {
        const _removedItem = this.value[itemIndex];
        this.value.splice(itemIndex, 1);
        this.removed.emit({ value: _removedItem, originalEvent: event });
    }
    onChipClicked({ event, data }) {
        this.chipClicked.emit({ value: data, originalEvent: event });
    }
    addItem() {
        if (!this.hasValueToAdd()) {
            return;
        }
        if (this.isMaxReached()) {
            return;
        }
        if (!this.isValidItemLength()) {
            return;
        }
        const valueToAdd = this.getValueToAdd();
        if (!this.hasDuplicatedItem()) {
            this.storeValue(valueToAdd);
        }
        this.newItem = '';
    }
    hasValueToAdd() {
        return !!this.newItem;
    }
    isMaxReached() {
        return !!(this.max && this.value.length === this.max);
    }
    isValidItemLength() {
        return this.maxLength ? this.newItem.length <= this.maxLength : true;
    }
    getMappedValues() {
        return this.field ? this.value.map((x) => x[this.field]) : this.value;
    }
    getValueToAdd() {
        return this.field ? { [this.field]: this.newItem } : this.newItem;
    }
    hasDuplicatedItem() {
        if (this.allowDuplicated) {
            return false;
        }
        const mappedValues = this.getMappedValues();
        return !!mappedValues.find((x) => {
            if (this.caseSensitiveDuplication) {
                return x === this.newItem;
            }
            else {
                return x.toLowerCase() === this.newItem.toLowerCase();
            }
        });
    }
    storeValue(value) {
        this.value = [...this.value, value];
        this.added.emit({ value });
        this.valueChange.emit(this.value);
        this.writeValue(this.value);
        this.onChange(this.value);
        this.onTouched(this.value);
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: ChipsComponent, deps: [{ token: i0.ChangeDetectorRef }], target: i0.ɵɵFactoryTarget.Component });
    static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "18.2.14", type: ChipsComponent, selector: "s-chips", inputs: { disabled: "disabled", field: "field", value: "value", placeholder: "placeholder", max: "max", maxLength: "maxLength", inputId: "inputId", allowDuplicated: "allowDuplicated", caseSensitiveDuplication: "caseSensitiveDuplication", addOnTab: "addOnTab", addOnBlur: "addOnBlur", separator: "separator", autofocus: "autofocus", infoLabel: "infoLabel", keyFilter: "keyFilter", showTooltip: "showTooltip", maxLengthRenderWithoutTooltip: "maxLengthRenderWithoutTooltip" }, outputs: { added: "added", removed: "removed", focused: "focused", focusLost: "focusLost", chipClicked: "chipClicked", valueChange: "valueChange" }, host: { listeners: { "document:keydown": "onKeydown($event)" } }, providers: [
            {
                provide: NG_VALUE_ACCESSOR,
                useExisting: forwardRef(() => ChipsComponent),
                multi: true,
            },
        ], queries: [{ propertyName: "templates", predicate: TemplateDirective }], viewQueries: [{ propertyName: "input", first: true, predicate: ["input"], descendants: true, read: ElementRef }], ngImport: i0, template: "<ul class=\"chips-container\" [class.chips-container--focused]=\"isFocused\">\n    @for(item of value; track $index) {\n        <li>\n            <s-chip-item\n                [templateRef]=\"chipTemplate\"\n                [dataRender]=\"item\"\n                [objectField]=\"field\"\n                [itemIndex]=\"$index\"\n                [disabled]=\"disabled\"\n                [showTooltip]=\"showTooltip\"\n                [maxLengthRenderWithoutTooltip]=\"maxLengthRenderWithoutTooltip\"\n                (clickRemove)=\"removeItem($event)\"\n                (chipClicked)=\"onChipClicked($event)\">\n            </s-chip-item>\n        </li>\n    }\n\n    @if(keyFilter) {\n        <input\n            #input\n            [disabled]=\"disabled || max === value.length\"\n            [placeholder]=\"placeholder || ''\"\n            [maxlength]=\"maxLength\"\n            [id]=\"inputId\"\n            [(ngModel)]=\"newItem\"\n            [pKeyFilter]=\"keyFilter\"\n            (focus)=\"onInputFocus($event)\"\n            (blur)=\"onInputLostFocus($event)\">\n    }@else {\n        <input\n            #input\n            [disabled]=\"disabled || max === value.length\"\n            [placeholder]=\"placeholder || ''\"\n            [maxlength]=\"maxLength\"\n            [id]=\"inputId\"\n            [(ngModel)]=\"newItem\"\n            (focus)=\"onInputFocus($event)\"\n            (blur)=\"onInputLostFocus($event)\">\n    }\n</ul>\n@if(infoLabel) {\n    <span class=\"info-label\">\n        {{ infoLabel }}\n    </span>\n}\n", styles: [":host.ng-invalid.ng-dirty .chips-container{border:1px solid #c13018}.chips-container{width:100%;padding:6px;display:flex;flex-wrap:wrap;align-items:center;border-radius:3px;border:1px solid #c1c1cc;background-color:#fff;list-style:none;gap:8px;min-height:35px}.chips-container input{background-color:#fff;width:100%;border:none;flex:1}.chips-container input:focus-visible{outline:none}.chips-container--focused{outline:2px solid #428bca}.info-label{color:#888b99;font-size:12px;font-style:normal;font-weight:400}\n"], dependencies: [{ kind: "directive", type: i1$1.DefaultValueAccessor, selector: "input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]" }, { kind: "directive", type: i1$1.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i1$1.MaxLengthValidator, selector: "[maxlength][formControlName],[maxlength][formControl],[maxlength][ngModel]", inputs: ["maxlength"] }, { kind: "directive", type: i1$1.NgModel, selector: "[ngModel]:not([formControlName]):not([formControl])", inputs: ["name", "disabled", "ngModel", "ngModelOptions"], outputs: ["ngModelChange"], exportAs: ["ngModel"] }, { kind: "directive", type: i2$1.KeyFilter, selector: "[pKeyFilter]", inputs: ["pValidateOnly", "pKeyFilter"], outputs: ["ngModelChange"] }, { kind: "component", type: ChipItemComponent, selector: "s-chip-item", inputs: ["dataRender", "objectField", "disabled", "templateRef", "itemIndex", "showTooltip", "maxLengthRenderWithoutTooltip"], outputs: ["clickRemove", "chipClicked"] }] });
}
__decorate([
    CheckDisabled()
], ChipsComponent.prototype, "onKeydown", null);
__decorate([
    CheckDisabled()
], ChipsComponent.prototype, "onInputLostFocus", null);
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: ChipsComponent, decorators: [{
            type: Component,
            args: [{ selector: 's-chips', providers: [
                        {
                            provide: NG_VALUE_ACCESSOR,
                            useExisting: forwardRef(() => ChipsComponent),
                            multi: true,
                        },
                    ], template: "<ul class=\"chips-container\" [class.chips-container--focused]=\"isFocused\">\n    @for(item of value; track $index) {\n        <li>\n            <s-chip-item\n                [templateRef]=\"chipTemplate\"\n                [dataRender]=\"item\"\n                [objectField]=\"field\"\n                [itemIndex]=\"$index\"\n                [disabled]=\"disabled\"\n                [showTooltip]=\"showTooltip\"\n                [maxLengthRenderWithoutTooltip]=\"maxLengthRenderWithoutTooltip\"\n                (clickRemove)=\"removeItem($event)\"\n                (chipClicked)=\"onChipClicked($event)\">\n            </s-chip-item>\n        </li>\n    }\n\n    @if(keyFilter) {\n        <input\n            #input\n            [disabled]=\"disabled || max === value.length\"\n            [placeholder]=\"placeholder || ''\"\n            [maxlength]=\"maxLength\"\n            [id]=\"inputId\"\n            [(ngModel)]=\"newItem\"\n            [pKeyFilter]=\"keyFilter\"\n            (focus)=\"onInputFocus($event)\"\n            (blur)=\"onInputLostFocus($event)\">\n    }@else {\n        <input\n            #input\n            [disabled]=\"disabled || max === value.length\"\n            [placeholder]=\"placeholder || ''\"\n            [maxlength]=\"maxLength\"\n            [id]=\"inputId\"\n            [(ngModel)]=\"newItem\"\n            (focus)=\"onInputFocus($event)\"\n            (blur)=\"onInputLostFocus($event)\">\n    }\n</ul>\n@if(infoLabel) {\n    <span class=\"info-label\">\n        {{ infoLabel }}\n    </span>\n}\n", styles: [":host.ng-invalid.ng-dirty .chips-container{border:1px solid #c13018}.chips-container{width:100%;padding:6px;display:flex;flex-wrap:wrap;align-items:center;border-radius:3px;border:1px solid #c1c1cc;background-color:#fff;list-style:none;gap:8px;min-height:35px}.chips-container input{background-color:#fff;width:100%;border:none;flex:1}.chips-container input:focus-visible{outline:none}.chips-container--focused{outline:2px solid #428bca}.info-label{color:#888b99;font-size:12px;font-style:normal;font-weight:400}\n"] }]
        }], ctorParameters: () => [{ type: i0.ChangeDetectorRef }], propDecorators: { disabled: [{
                type: Input
            }], field: [{
                type: Input
            }], value: [{
                type: Input
            }], placeholder: [{
                type: Input
            }], max: [{
                type: Input
            }], maxLength: [{
                type: Input
            }], inputId: [{
                type: Input
            }], allowDuplicated: [{
                type: Input
            }], caseSensitiveDuplication: [{
                type: Input
            }], addOnTab: [{
                type: Input
            }], addOnBlur: [{
                type: Input
            }], separator: [{
                type: Input
            }], autofocus: [{
                type: Input
            }], infoLabel: [{
                type: Input
            }], keyFilter: [{
                type: Input
            }], showTooltip: [{
                type: Input
            }], maxLengthRenderWithoutTooltip: [{
                type: Input
            }], added: [{
                type: Output
            }], removed: [{
                type: Output
            }], focused: [{
                type: Output
            }], focusLost: [{
                type: Output
            }], chipClicked: [{
                type: Output
            }], valueChange: [{
                type: Output
            }], templates: [{
                type: ContentChildren,
                args: [TemplateDirective]
            }], input: [{
                type: ViewChild,
                args: ['input', { read: ElementRef }]
            }], onKeydown: [{
                type: HostListener,
                args: ['document:keydown', ['$event']]
            }], onInputLostFocus: [] } });

class ChipsModule {
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: ChipsModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
    static ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "18.2.14", ngImport: i0, type: ChipsModule, declarations: [ChipsComponent, ChipItemComponent], imports: [FormsModule, TooltipModule, KeyFilterModule, NgTemplateOutlet], exports: [ChipsComponent] });
    static ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: ChipsModule, imports: [FormsModule, TooltipModule, KeyFilterModule] });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: ChipsModule, decorators: [{
            type: NgModule,
            args: [{
                    declarations: [ChipsComponent, ChipItemComponent],
                    imports: [FormsModule, TooltipModule, KeyFilterModule, NgTemplateOutlet],
                    exports: [ChipsComponent],
                }]
        }] });

/**
 * Generated bundle index. Do not edit.
 */

export { ChipsComponent, ChipsModule };
//# sourceMappingURL=seniorsistemas-angular-components-chips.mjs.map
