import { ENTER, COMMA } from '@angular/cdk/keycodes';
import * as i0 from '@angular/core';
import { Directive, Input, HostListener, Component, ChangeDetectionStrategy, ViewChild, NgModule } from '@angular/core';
import * as i2 from '@angular/forms';
import { UntypedFormControl, FormsModule, ReactiveFormsModule } from '@angular/forms';
import * as i5 from '@angular/material/legacy-autocomplete';
import { MatLegacyAutocompleteModule } from '@angular/material/legacy-autocomplete';
import { equals, isOverflowing, HelperPipesModule } from '@aztrix/helpers';
import { BehaviorSubject, Subscription, combineLatest } from 'rxjs';
import { startWith, map } from 'rxjs/operators';
import * as i1 from '@angular/common';
import { CommonModule } from '@angular/common';
import * as i3 from '@angular/material/legacy-form-field';
import { MatLegacyFormFieldModule } from '@angular/material/legacy-form-field';
import * as i4 from '@angular/material/legacy-core';
import * as i6 from '@aztrix/icons';
import { IconsModule } from '@aztrix/icons';
import * as i7 from '@angular/material/legacy-chips';
import { MatLegacyChipsModule } from '@angular/material/legacy-chips';
import * as i8 from '@aztrix/components/button';
import { ButtonModule } from '@aztrix/components/button';
import * as i9 from '@aztrix/components/property-published-button';
import { PropertyPublishedButtonModule } from '@aztrix/components/property-published-button';
import { ScrollingModule } from '@angular/cdk/scrolling';
import { MatLegacyInputModule } from '@angular/material/legacy-input';
import { MatLegacySelectModule } from '@angular/material/legacy-select';

class DisableSpecialFileCharactersDirective {
    constructor(el) {
        this.el = el;
        this.regex = /[\\/:*?"<>|]/g;
        this._disableSpecialFileCharacters = true;
    }
    set axDisableSpecialFileCharacters(disableSpecialFileCharacters) {
        this._disableSpecialFileCharacters = disableSpecialFileCharacters;
    }
    onKeyPress(event) {
        this.validateFields(event);
        return this._disableSpecialFileCharacters ? !this.regex.test(event.key) : true;
    }
    onPaste(event) {
        this.validateFields(event);
    }
    validateFields(event) {
        if (this._disableSpecialFileCharacters) {
            setTimeout(() => {
                this.el.nativeElement.value = this.el.nativeElement.value.replace(this.regex, '');
                event.preventDefault();
            }, 100);
        }
    }
}
DisableSpecialFileCharactersDirective.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.5", ngImport: i0, type: DisableSpecialFileCharactersDirective, deps: [{ token: i0.ElementRef }], target: i0.ɵɵFactoryTarget.Directive });
DisableSpecialFileCharactersDirective.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "15.1.5", type: DisableSpecialFileCharactersDirective, selector: "[axDisableSpecialFileCharacters]", inputs: { axDisableSpecialFileCharacters: "axDisableSpecialFileCharacters" }, host: { listeners: { "keypress": "onKeyPress($event)", "paste": "onPaste($event)" } }, ngImport: i0 });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.5", ngImport: i0, type: DisableSpecialFileCharactersDirective, decorators: [{
            type: Directive,
            args: [{
                    selector: '[axDisableSpecialFileCharacters]',
                }]
        }], ctorParameters: function () { return [{ type: i0.ElementRef }]; }, propDecorators: { axDisableSpecialFileCharacters: [{
                type: Input
            }], onKeyPress: [{
                type: HostListener,
                args: ['keypress', ['$event']]
            }], onPaste: [{
                type: HostListener,
                args: ['paste', ['$event']]
            }] } });

class ChipsEditComponent {
    constructor() {
        this.required = false;
        this.disableSpecialFileCharacters = false;
        this.published = false;
        this.readonly = false;
        this.separatorKeysCodes = [ENTER, COMMA];
        this.chipsCtrl = new UntypedFormControl();
        this.chips = [];
        this.chips$ = new BehaviorSubject([]);
        this.formSubscription = new Subscription();
        this.chipsCtrlSubscription = new Subscription();
        this.collapsed = false;
        this.overflowing = false;
        this.filteredChips$ = combineLatest([
            this.chipsCtrl.valueChanges.pipe(startWith(this.chipsCtrl.value)),
            this.chips$,
        ]).pipe(map(([value]) => this.autocompleteValues?.filter((chip) => (!value || chip.toLowerCase().indexOf(value?.toLowerCase()) === 0) &&
            !this._duplicate(chip))));
    }
    ngOnChanges(changes) {
        if (changes.form && this.form) {
            this.formSubscription.unsubscribe();
            this.formSubscription = this.form.valueChanges
                .pipe(startWith(this.form.value))
                .subscribe((property) => {
                const values = property?.value?.split(',').filter((v) => v?.length);
                if (!equals(this.chips$.value, values)) {
                    this.chips = values;
                    this.chips$.next(values);
                }
            });
            this.formSubscription.add(this.form.statusChanges.subscribe(() => {
                this._setFormState();
            }));
        }
    }
    add({ chipInput, value }) {
        value = (value || '').trim();
        if (value && !this._duplicate(value)) {
            this.chips.push(value);
            this.chips$.next(this.chips);
        }
        if (chipInput) {
            chipInput.inputElement.value = '';
        }
        this.chipsCtrl.setValue(null);
        this._setFormValue();
    }
    remove(value) {
        const index = this.chips.indexOf(value);
        if (index >= 0) {
            this.chips.splice(index, 1);
            this.chips$.next(this.chips);
        }
        this._setFormState();
        this._setFormValue();
    }
    selected(event) {
        if (!this._duplicate(event.option.viewValue)) {
            this.chips.push(event.option.viewValue.trim());
            this.chips$.next(this.chips);
        }
        this.chipsCtrl.setValue(null);
        this._setFormState();
        this._setFormValue();
    }
    blur(event) {
        if (event.chipInput?.inputElement?.tagName?.toLowerCase() !== 'mat-option') {
            this.add(event);
        }
    }
    clearValue() {
        this.chips = [];
        this.chips$.next(this.chips);
        this.form.patchValue(null);
        this.form.markAsDirty();
    }
    _setFormValue() {
        const value = this.chips$.value?.join(',');
        this.form.setValue({ ...this.form.value, value });
        this.form.markAsDirty();
    }
    _setFormState() {
        this.chipList.errorState = this.form.invalid;
        this.chipsCtrl.updateValueAndValidity();
    }
    _duplicate(valueToCheck) {
        return (this.chips
            .map((chip) => chip.toLowerCase())
            .findIndex((chip) => valueToCheck.trim().toLowerCase() === chip) >= 0);
    }
    get hasValue() {
        return this.form?.value?.value;
    }
    isOverflowing() {
        if (!this.overflowing) {
            this.overflowing = isOverflowing(this.hintElement);
            return this.overflowing;
        }
        return this.overflowing;
    }
}
ChipsEditComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.5", ngImport: i0, type: ChipsEditComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
ChipsEditComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "15.1.5", type: ChipsEditComponent, selector: "ax-chips-edit", inputs: { form: "form", label: "label", hint: "hint", required: "required", autocompleteValues: "autocompleteValues", disableSpecialFileCharacters: "disableSpecialFileCharacters", errorsTemplate: "errorsTemplate", published: "published", readonly: "readonly" }, viewQueries: [{ propertyName: "chipList", first: true, predicate: ["chipList"], descendants: true }, { propertyName: "matAutocomplete", first: true, predicate: ["auto"], descendants: true }, { propertyName: "hintElement", first: true, predicate: ["hintElement"], descendants: true }], usesOnChanges: true, ngImport: i0, template: "<div>\n  <mat-form-field\n    class=\"c-input\"\n    [ngClass]=\"{readonly: readonly}\"\n    appearance=\"outline\"\n    style=\"width: 100%\"\n  >\n    <mat-label>{{ label }}<span *ngIf=\"required\">&nbsp;*</span></mat-label>\n    <mat-chip-list [disabled]=\"form?.disabled\" #chipList aria-label=\"Chips selection\">\n      <mat-chip\n        *ngFor=\"let chip of chips$ | async\"\n        [selectable]=\"false\"\n        [removable]=\"true\"\n        (removed)=\"remove(chip)\"\n      >\n        {{ chip }}\n        <ax-icon matChipRemove class=\"icon\" name=\"close\"></ax-icon>\n      </mat-chip>\n      <input\n        [axDisableSpecialFileCharacters]=\"disableSpecialFileCharacters\"\n        [formControl]=\"chipsCtrl\"\n        (focusout)=\"form.markAsTouched()\"\n        [matAutocomplete]=\"auto\"\n        [matChipInputFor]=\"chipList\"\n        [matChipInputSeparatorKeyCodes]=\"separatorKeysCodes\"\n        [readonly]=\"readonly\"\n        (matChipInputTokenEnd)=\"add($event)\"\n        (blur)=\"blur($event)\"\n      />\n    </mat-chip-list>\n    <mat-hint\n      [ngClass]=\"{collapsed}\"\n      (click)=\"collapsed = !collapsed\"\n      class=\"hint collapsible\"\n      align=\"end\"\n      #hintElement\n    >\n      <div><ax-icon *ngIf=\"isOverflowing()\" class=\"icon\" name=\"chevron-down\"></ax-icon></div>\n      <span [ngClass]=\"{overflowing: isOverflowing()}\">{{ hint }}</span>\n    </mat-hint>\n    <mat-error><ng-template [ngTemplateOutlet]=\"errorsTemplate\"></ng-template></mat-error>\n    <mat-autocomplete #auto=\"matAutocomplete\" (optionSelected)=\"selected($event)\">\n      <mat-option *ngFor=\"let chip of filteredChips$ | async\" [value]=\"chip\">\n        {{ chip }}\n      </mat-option>\n    </mat-autocomplete>\n\n    <button\n      axButton\n      icon-button\n      type=\"button\"\n      *ngIf=\"form?.enabled && hasValue\"\n      matSuffix\n      (click)=\"clearValue()\"\n    >\n      <ax-icon class=\"icon\" name=\"close\"></ax-icon>\n    </button>\n  </mat-form-field>\n</div>\n<ax-property-published-button *ngIf=\"published\"></ax-property-published-button>\n", styles: [":host{display:block;position:relative}\n"], dependencies: [{ kind: "directive", type: i1.NgClass, selector: "[ngClass]", inputs: ["class", "ngClass"] }, { kind: "directive", type: i1.NgForOf, selector: "[ngFor][ngForOf]", inputs: ["ngForOf", "ngForTrackBy", "ngForTemplate"] }, { kind: "directive", type: i1.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "directive", type: i1.NgTemplateOutlet, selector: "[ngTemplateOutlet]", inputs: ["ngTemplateOutletContext", "ngTemplateOutlet", "ngTemplateOutletInjector"] }, { kind: "directive", type: i2.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: i2.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i2.FormControlDirective, selector: "[formControl]", inputs: ["formControl", "disabled", "ngModel"], outputs: ["ngModelChange"], exportAs: ["ngForm"] }, { kind: "directive", type: i3.MatLegacyError, selector: "mat-error", inputs: ["id"] }, { kind: "component", type: i3.MatLegacyFormField, selector: "mat-form-field", inputs: ["color", "appearance", "hideRequiredMarker", "hintLabel", "floatLabel"], exportAs: ["matFormField"] }, { kind: "directive", type: i3.MatLegacyHint, selector: "mat-hint", inputs: ["align", "id"] }, { kind: "directive", type: i3.MatLegacyLabel, selector: "mat-label" }, { kind: "directive", type: i3.MatLegacySuffix, selector: "[matSuffix]" }, { kind: "component", type: i4.MatLegacyOption, selector: "mat-option", exportAs: ["matOption"] }, { kind: "component", type: i5.MatLegacyAutocomplete, selector: "mat-autocomplete", inputs: ["disableRipple"], exportAs: ["matAutocomplete"] }, { kind: "directive", type: i5.MatLegacyAutocompleteTrigger, selector: "input[matAutocomplete], textarea[matAutocomplete]", exportAs: ["matAutocompleteTrigger"] }, { kind: "component", type: i6.IconComponent, selector: "ax-icon", inputs: ["name", "inline"] }, { kind: "component", type: i7.MatLegacyChipList, selector: "mat-chip-list", inputs: ["role", "aria-describedby", "errorStateMatcher", "multiple", "compareWith", "value", "required", "placeholder", "disabled", "aria-orientation", "selectable", "tabIndex"], outputs: ["change", "valueChange"], exportAs: ["matChipList"] }, { kind: "directive", type: i7.MatLegacyChip, selector: "mat-basic-chip, [mat-basic-chip], mat-chip, [mat-chip]", inputs: ["color", "disableRipple", "tabIndex", "role", "selected", "value", "selectable", "disabled", "removable"], outputs: ["selectionChange", "destroyed", "removed"], exportAs: ["matChip"] }, { kind: "directive", type: i7.MatLegacyChipInput, selector: "input[matChipInputFor]", inputs: ["matChipInputFor", "matChipInputAddOnBlur", "matChipInputSeparatorKeyCodes", "placeholder", "id", "disabled"], outputs: ["matChipInputTokenEnd"], exportAs: ["matChipInput", "matChipInputFor"] }, { kind: "directive", type: i7.MatLegacyChipRemove, selector: "[matChipRemove]" }, { kind: "directive", type: i8.ButtonDirective, selector: "[axButton]", inputs: ["color", "labelHideMobile", "smallButton", "bigButton", "fullWidth", "filled", "outline", "icon-button", "hoverLabel", "hover", "lowercase", "disabled"] }, { kind: "component", type: i9.PropertyPublishedButtonComponent, selector: "ax-property-published-button" }, { kind: "directive", type: DisableSpecialFileCharactersDirective, selector: "[axDisableSpecialFileCharacters]", inputs: ["axDisableSpecialFileCharacters"] }, { kind: "pipe", type: i1.AsyncPipe, name: "async" }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.5", ngImport: i0, type: ChipsEditComponent, decorators: [{
            type: Component,
            args: [{ selector: 'ax-chips-edit', changeDetection: ChangeDetectionStrategy.OnPush, template: "<div>\n  <mat-form-field\n    class=\"c-input\"\n    [ngClass]=\"{readonly: readonly}\"\n    appearance=\"outline\"\n    style=\"width: 100%\"\n  >\n    <mat-label>{{ label }}<span *ngIf=\"required\">&nbsp;*</span></mat-label>\n    <mat-chip-list [disabled]=\"form?.disabled\" #chipList aria-label=\"Chips selection\">\n      <mat-chip\n        *ngFor=\"let chip of chips$ | async\"\n        [selectable]=\"false\"\n        [removable]=\"true\"\n        (removed)=\"remove(chip)\"\n      >\n        {{ chip }}\n        <ax-icon matChipRemove class=\"icon\" name=\"close\"></ax-icon>\n      </mat-chip>\n      <input\n        [axDisableSpecialFileCharacters]=\"disableSpecialFileCharacters\"\n        [formControl]=\"chipsCtrl\"\n        (focusout)=\"form.markAsTouched()\"\n        [matAutocomplete]=\"auto\"\n        [matChipInputFor]=\"chipList\"\n        [matChipInputSeparatorKeyCodes]=\"separatorKeysCodes\"\n        [readonly]=\"readonly\"\n        (matChipInputTokenEnd)=\"add($event)\"\n        (blur)=\"blur($event)\"\n      />\n    </mat-chip-list>\n    <mat-hint\n      [ngClass]=\"{collapsed}\"\n      (click)=\"collapsed = !collapsed\"\n      class=\"hint collapsible\"\n      align=\"end\"\n      #hintElement\n    >\n      <div><ax-icon *ngIf=\"isOverflowing()\" class=\"icon\" name=\"chevron-down\"></ax-icon></div>\n      <span [ngClass]=\"{overflowing: isOverflowing()}\">{{ hint }}</span>\n    </mat-hint>\n    <mat-error><ng-template [ngTemplateOutlet]=\"errorsTemplate\"></ng-template></mat-error>\n    <mat-autocomplete #auto=\"matAutocomplete\" (optionSelected)=\"selected($event)\">\n      <mat-option *ngFor=\"let chip of filteredChips$ | async\" [value]=\"chip\">\n        {{ chip }}\n      </mat-option>\n    </mat-autocomplete>\n\n    <button\n      axButton\n      icon-button\n      type=\"button\"\n      *ngIf=\"form?.enabled && hasValue\"\n      matSuffix\n      (click)=\"clearValue()\"\n    >\n      <ax-icon class=\"icon\" name=\"close\"></ax-icon>\n    </button>\n  </mat-form-field>\n</div>\n<ax-property-published-button *ngIf=\"published\"></ax-property-published-button>\n", styles: [":host{display:block;position:relative}\n"] }]
        }], ctorParameters: function () { return []; }, propDecorators: { form: [{
                type: Input
            }], label: [{
                type: Input
            }], hint: [{
                type: Input
            }], required: [{
                type: Input
            }], autocompleteValues: [{
                type: Input
            }], disableSpecialFileCharacters: [{
                type: Input
            }], errorsTemplate: [{
                type: Input
            }], published: [{
                type: Input
            }], readonly: [{
                type: Input
            }], chipList: [{
                type: ViewChild,
                args: ['chipList']
            }], matAutocomplete: [{
                type: ViewChild,
                args: ['auto']
            }], hintElement: [{
                type: ViewChild,
                args: ['hintElement']
            }] } });

class ChipsEditModule {
}
ChipsEditModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.5", ngImport: i0, type: ChipsEditModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
ChipsEditModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.1.5", ngImport: i0, type: ChipsEditModule, declarations: [ChipsEditComponent, DisableSpecialFileCharactersDirective], imports: [CommonModule,
        FormsModule,
        ReactiveFormsModule,
        MatLegacyFormFieldModule,
        MatLegacyInputModule,
        MatLegacySelectModule,
        MatLegacyAutocompleteModule,
        ScrollingModule,
        IconsModule,
        HelperPipesModule,
        MatLegacyChipsModule,
        ButtonModule,
        PropertyPublishedButtonModule], exports: [ChipsEditComponent] });
ChipsEditModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "15.1.5", ngImport: i0, type: ChipsEditModule, imports: [CommonModule,
        FormsModule,
        ReactiveFormsModule,
        MatLegacyFormFieldModule,
        MatLegacyInputModule,
        MatLegacySelectModule,
        MatLegacyAutocompleteModule,
        ScrollingModule,
        IconsModule,
        HelperPipesModule,
        MatLegacyChipsModule,
        ButtonModule,
        PropertyPublishedButtonModule] });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.5", ngImport: i0, type: ChipsEditModule, decorators: [{
            type: NgModule,
            args: [{
                    declarations: [ChipsEditComponent, DisableSpecialFileCharactersDirective],
                    imports: [
                        CommonModule,
                        FormsModule,
                        ReactiveFormsModule,
                        MatLegacyFormFieldModule,
                        MatLegacyInputModule,
                        MatLegacySelectModule,
                        MatLegacyAutocompleteModule,
                        ScrollingModule,
                        IconsModule,
                        HelperPipesModule,
                        MatLegacyChipsModule,
                        ButtonModule,
                        PropertyPublishedButtonModule,
                    ],
                    exports: [ChipsEditComponent],
                }]
        }] });

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

export { ChipsEditComponent, ChipsEditModule };
//# sourceMappingURL=aztrix-components-chips-edit.mjs.map
//# sourceMappingURL=aztrix-components-chips-edit.mjs.map
