import * as i0 from '@angular/core';
import { Pipe, EventEmitter, ContentChild, ViewChild, Output, Input, ChangeDetectionStrategy, Component } from '@angular/core';
import { ENTER, COMMA } from '@angular/cdk/keycodes';
import * as i1 from '@angular/common';
import { CommonModule } from '@angular/common';
import * as i2 from '@angular/forms';
import { NgForm, FormControl, Validators, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import * as i5 from '@angular/material/chips';
import { MatChipsModule } from '@angular/material/chips';
import { MatFormFieldModule } from '@angular/material/form-field';
import * as i4 from '@angular/material/icon';
import { MatIconModule } from '@angular/material/icon';
import * as i3 from '@angular/material/input';
import { MatInputModule } from '@angular/material/input';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatTooltipModule } from '@angular/material/tooltip';
import { SdViewDefDirective, SdLabelDefDirective } from '@sd-angular/core/forms/directives';
import { SdFormControl } from '@sd-angular/core/forms/models';
import { Subscription } from 'rxjs';
import * as uuid from 'uuid';

class SdRemovableChipPipe {
    constructor() { }
    transform(item, removable) {
        if (typeof (removable) === 'boolean') {
            return removable;
        }
        return removable(item);
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: SdRemovableChipPipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe });
    static ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "19.2.17", ngImport: i0, type: SdRemovableChipPipe, isStandalone: true, name: "sdRemovableChip" });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: SdRemovableChipPipe, decorators: [{
            type: Pipe,
            args: [{
                    name: 'sdRemovableChip'
                }]
        }], ctorParameters: () => [] });

class SdChipErrotStateMatcher {
    formControl;
    constructor(formControl) {
        this.formControl = formControl;
    }
    isErrorState(control, form) {
        const isSubmitted = form && form.submitted;
        return !!(this.formControl?.invalid && (this.formControl?.dirty || this.formControl?.touched || isSubmitted));
    }
}
class SdChip {
    ref;
    autoId;
    set _autoId(val) {
        if (!val) {
            return;
        }
        this.autoId = `forms-chip-${val}`;
    }
    #name = uuid.v4();
    set _name(val) {
        if (val) {
            this.#name = val;
        }
    }
    appearance = 'outline';
    separatorKeysCodes = [ENTER, COMMA];
    selectable = true;
    size = 'md';
    #form;
    set form(val) {
        if (val) {
            if (val instanceof NgForm) {
                this.#form = val.form;
            }
            else {
                this.#form = val;
            }
        }
    }
    addable = true;
    set _addable(val) {
        this.addable = val === '' || !!val;
    }
    label = '';
    placeholder;
    removable = true;
    set _removable(val) {
        this.removable = val === '' || val;
    }
    hideInlineError = false;
    set _hideInlineError(val) {
        this.hideInlineError = val === '' || !!val;
    }
    // Model
    set model(values) {
        if (!Array.isArray(values)) {
            values = [];
        }
        this.formControl.setValue(values);
    }
    // Validator
    required = false;
    set _required(val) {
        this.required = val === '' || !!val;
        this.#updateValidator();
    }
    min;
    set pMin(val) {
        this.min = +val || 0;
        this.#updateValidator();
    }
    max;
    set pMax(val) {
        this.max = +val || 0;
        this.#updateValidator();
    }
    modelChange = new EventEmitter();
    // Optional
    set disabled(val) {
        val = val === '' || val;
        if (val) {
            this.formControl.disable();
            this.inputControl.disable();
        }
        else {
            this.formControl.enable();
            this.inputControl.enable();
        }
    }
    sdChange = new EventEmitter();
    input;
    sdView;
    sdLabelDef;
    isBlurring = false;
    isFocused = false;
    inputControl = new FormControl();
    formControl = new SdFormControl();
    matcher = new SdChipErrotStateMatcher(this.formControl);
    #subscription = new Subscription();
    constructor(ref) {
        this.ref = ref;
    }
    ngAfterViewInit() {
        this.#subscription.add(this.formControl.sdChanges.subscribe(() => {
            this.ref.markForCheck();
        }));
        this.#form?.addControl(this.#name, this.formControl);
    }
    ngOnDestroy() {
        this.#form?.removeControl(this.#name);
        this.#subscription.unsubscribe();
    }
    #updateValidator = () => {
        this.formControl.clearValidators();
        this.formControl.clearAsyncValidators();
        const validators = [];
        const asyncValidators = [];
        if (this.required) {
            validators.push(Validators.required);
        }
        if (this.min > 0) {
            validators.push(Validators.minLength(this.min));
        }
        if (this.max > 0) {
            validators.push(Validators.maxLength(this.max));
        }
        this.formControl.setValidators(validators);
        this.formControl.setAsyncValidators(asyncValidators);
        this.formControl.updateValueAndValidity();
    };
    onAdd = (event) => {
        const value = (event.value ?? '').toString().trim();
        const values = this.formControl.value ?? [];
        if (value && this.addable && !values.includes(value)) {
            values.push(value);
            this.formControl.setValue(values);
            this.modelChange.emit(this.formControl.value);
            this.sdChange.emit(this.formControl.value);
        }
        this.input.nativeElement.value = '';
        this.inputControl.setValue('');
    };
    onClickChip = ($event, item) => {
        $event.stopPropagation();
        $event.stopImmediatePropagation();
        if (!this.formControl.disabled) {
            this.focus();
        }
    };
    onRemove = (item) => {
        const values = this.formControl.value ?? [];
        if (typeof item === 'string' || typeof item === 'number') {
            this.formControl.setValue(values.filter(value => item !== value));
            this.modelChange.emit(this.formControl.value);
            this.sdChange.emit(this.formControl.value);
        }
        this.inputControl.setValue('');
        this.focus();
    };
    onSelect = (event) => {
        const item = event.option.value;
        const values = this.formControl.value ?? [];
        if (item) {
            if (typeof item === 'string' || typeof item === 'number') {
                if (!values.includes(item)) {
                    values.push(item);
                    this.formControl.setValue(values);
                    this.modelChange.emit(this.formControl.value);
                    this.sdChange.emit(this.formControl.value);
                }
            }
            this.input.nativeElement.value = '';
            this.inputControl.setValue('', {
                emitEvent: false,
            });
        }
    };
    onFocus = () => {
        this.isFocused = true;
        this.isBlurring = false;
        this.inputControl.setValue('');
    };
    onBlur = () => {
        this.isBlurring = true;
        setTimeout(() => {
            if (this.isBlurring) {
                this.isFocused = false;
                this.inputControl.setValue('', {
                    emitEvent: false,
                });
                this.ref.detectChanges();
            }
        }, 150);
    };
    onClick = () => {
        if (this.sdView?.templateRef) {
            if (!this.formControl.disabled && !this.isFocused) {
                this.focus();
            }
        }
    };
    focus = () => {
        this.isFocused = true;
        this.isBlurring = false;
        setTimeout(() => {
            if (this.isFocused) {
                this.input?.nativeElement?.focus();
            }
        }, 100);
    };
    onClear = ($event) => {
        $event?.stopPropagation();
        this.inputControl.setValue('');
        this.formControl.setValue([]);
        this.modelChange.emit(this.formControl.value);
        this.sdChange.emit(this.formControl.value);
        this.ref.detectChanges();
    };
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: SdChip, deps: [{ token: i0.ChangeDetectorRef }], target: i0.ɵɵFactoryTarget.Component });
    static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "19.2.17", type: SdChip, isStandalone: true, selector: "sd-chip", inputs: { _autoId: ["autoId", "_autoId"], _name: ["name", "_name"], appearance: "appearance", size: "size", form: "form", _addable: ["addable", "_addable"], label: "label", placeholder: "placeholder", _removable: ["removable", "_removable"], _hideInlineError: ["hideInlineError", "_hideInlineError"], model: "model", _required: ["required", "_required"], pMin: ["min", "pMin"], pMax: ["max", "pMax"], disabled: "disabled" }, outputs: { modelChange: "modelChange", sdChange: "sdChange" }, queries: [{ propertyName: "sdView", first: true, predicate: SdViewDefDirective, descendants: true }, { propertyName: "sdLabelDef", first: true, predicate: SdLabelDefDirective, descendants: true }], viewQueries: [{ propertyName: "input", first: true, predicate: ["input"], descendants: true }], ngImport: i0, template: "@let labelTemplate = sdLabelDef?.templateRef;\r\n@let viewTemplate = sdView?.templateRef;\r\n\r\n@if (!appearance && labelTemplate) {\r\n  <ng-container *ngTemplateOutlet=\"labelTemplate\"></ng-container>\r\n}\r\n@if (!appearance && label && !labelTemplate) {\r\n  <div class=\"d-block mb-0 T14M\">{{ label }} <span class=\"text-danger mb-2\" *ngIf=\"required\">*</span></div>\r\n}\r\n<div\r\n  class=\"d-flex align-items-center\"\r\n  [class.sd-view]=\"viewTemplate\"\r\n  [class.c-focused]=\"isFocused\"\r\n  [class.c-disabled]=\"formControl.disabled\"\r\n  (keydown.enter)=\"onClick()\"\r\n  tabindex=\"0\"\r\n  (click)=\"onClick()\">\r\n  @if (viewTemplate && !isFocused) {\r\n    <ng-container *ngTemplateOutlet=\"viewTemplate; context: { value: formControl.value }\"></ng-container>\r\n  } @else {\r\n    <mat-form-field\r\n      [class.sd-md]=\"size === 'md'\"\r\n      [class.sd-sm]=\"size === 'sm'\"\r\n      [class.hide-inline-error]=\"hideInlineError\"\r\n      [appearance]=\"appearance\">\r\n      @if (appearance && label) {\r\n        <mat-label>{{ label }}</mat-label>\r\n      }\r\n      <mat-chip-grid [formControl]=\"formControl\" #chipList [class.sd-md]=\"size === 'md'\" [class.sd-sm]=\"size === 'sm'\">\r\n        @for (item of formControl.value; track $index) {\r\n          @if (item) {\r\n            <mat-chip-row\r\n              [class.sd-md]=\"size === 'md'\"\r\n              [class.sd-sm]=\"size === 'sm'\"\r\n              [removable]=\"removable\"\r\n              (removed)=\"onRemove(item)\"\r\n              [disabled]=\"inputControl.disabled\"\r\n              (click)=\"onClickChip($event, item)\">\r\n              <span>{{ item }}</span>\r\n              @if (!inputControl.disabled && item | sdRemovableChip: removable) {\r\n                <mat-icon matChipRemove>cancel</mat-icon>\r\n              }\r\n            </mat-chip-row>\r\n          }\r\n        }\r\n        <input\r\n          class=\"sd-chip-input\"\r\n          [formControl]=\"inputControl\"\r\n          [placeholder]=\"placeholder || label\"\r\n          [matChipInputFor]=\"chipList\"\r\n          [matChipInputSeparatorKeyCodes]=\"separatorKeysCodes\"\r\n          (matChipInputTokenEnd)=\"onAdd($event)\"\r\n          autocomplete=\"off\"\r\n          [errorStateMatcher]=\"matcher\"\r\n          (focus)=\"onFocus()\"\r\n          (blur)=\"onBlur()\"\r\n          [required]=\"required\"\r\n          matInput\r\n          [attr.data-autoId]=\"autoId\"\r\n          #input />\r\n      </mat-chip-grid>\r\n      @if (formControl.errors?.['required'] && !hideInlineError) {\r\n        <mat-error>{{ 'Vui l\u00F2ng nh\u1EADp th\u00F4ng tin' }}</mat-error>\r\n      }\r\n      @if (formControl.errors?.['minlength'] && !hideInlineError) {\r\n        <mat-error>{{ 'Vui l\u00F2ng nh\u1EADp \u00EDt nh\u1EA5t ' + min + ' gi\u00E1 tr\u1ECB' }} </mat-error>\r\n      }\r\n      @if (formControl.errors?.['maxlength'] && !hideInlineError) {\r\n        <mat-error>{{ 'Vui l\u00F2ng nh\u1EADp t\u1ED1i \u0111a ' + max + ' gi\u00E1 tr\u1ECB' }} </mat-error>\r\n      }\r\n    </mat-form-field>\r\n  }\r\n</div>\r\n", styles: [":host{padding-top:5px;display:block}.sd-chip-input{margin-top:0!important}:host ::ng-deep .mat-mdc-form-field.no-padding-wrapper .mat-mdc-text-field-wrapper{padding-bottom:0}:host ::ng-deep mat-form-field.c-md .mat-mdc-standard-chip{padding:7px 10px;min-height:26px}:host ::ng-deep mat-form-field.c-md .mat-mdc-standard-chip .mat-mdc-chip-trailing-icon{padding:7px 7px 7px 10px}:host ::ng-deep .mat-mdc-chip-row.sd-sm{--mdc-chip-label-text-size: 12px;--mdc-chip-container-height: 20px}:host ::ng-deep .mat-mdc-chip-set.sd-md{margin-top:10px}:host ::ng-deep .mat-mdc-chip-set.sd-sm{margin-top:2px}.sd-view:not(.c-focused):not(.c-disabled):hover{background-color:#ebecf0}\n"], dependencies: [{ kind: "ngmodule", type: CommonModule }, { kind: "directive", type: i1.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "directive", type: i1.NgTemplateOutlet, selector: "[ngTemplateOutlet]", inputs: ["ngTemplateOutletContext", "ngTemplateOutlet", "ngTemplateOutletInjector"] }, { kind: "ngmodule", type: FormsModule }, { 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.RequiredValidator, selector: ":not([type=checkbox])[required][formControlName],:not([type=checkbox])[required][formControl],:not([type=checkbox])[required][ngModel]", inputs: ["required"] }, { kind: "ngmodule", type: ReactiveFormsModule }, { kind: "directive", type: i2.FormControlDirective, selector: "[formControl]", inputs: ["formControl", "disabled", "ngModel"], outputs: ["ngModelChange"], exportAs: ["ngForm"] }, { kind: "ngmodule", type: MatInputModule }, { kind: "directive", type: i3.MatInput, selector: "input[matInput], textarea[matInput], select[matNativeControl],      input[matNativeControl], textarea[matNativeControl]", inputs: ["disabled", "id", "placeholder", "name", "required", "type", "errorStateMatcher", "aria-describedby", "value", "readonly", "disabledInteractive"], exportAs: ["matInput"] }, { kind: "component", type: i3.MatFormField, selector: "mat-form-field", inputs: ["hideRequiredMarker", "color", "floatLabel", "appearance", "subscriptSizing", "hintLabel"], exportAs: ["matFormField"] }, { kind: "directive", type: i3.MatLabel, selector: "mat-label" }, { kind: "directive", type: i3.MatError, selector: "mat-error, [matError]", inputs: ["id"] }, { kind: "ngmodule", type: MatTooltipModule }, { kind: "ngmodule", type: MatFormFieldModule }, { kind: "ngmodule", type: MatAutocompleteModule }, { kind: "ngmodule", type: MatIconModule }, { kind: "component", type: i4.MatIcon, selector: "mat-icon", inputs: ["color", "inline", "svgIcon", "fontSet", "fontIcon"], exportAs: ["matIcon"] }, { kind: "ngmodule", type: MatProgressSpinnerModule }, { kind: "ngmodule", type: MatChipsModule }, { kind: "component", type: i5.MatChipGrid, selector: "mat-chip-grid", inputs: ["disabled", "placeholder", "required", "value", "errorStateMatcher"], outputs: ["change", "valueChange"] }, { kind: "directive", type: i5.MatChipInput, selector: "input[matChipInputFor]", inputs: ["matChipInputFor", "matChipInputAddOnBlur", "matChipInputSeparatorKeyCodes", "placeholder", "id", "disabled"], outputs: ["matChipInputTokenEnd"], exportAs: ["matChipInput", "matChipInputFor"] }, { kind: "directive", type: i5.MatChipRemove, selector: "[matChipRemove]" }, { kind: "component", type: i5.MatChipRow, selector: "mat-chip-row, [mat-chip-row], mat-basic-chip-row, [mat-basic-chip-row]", inputs: ["editable"], outputs: ["edited"] }, { kind: "pipe", type: SdRemovableChipPipe, name: "sdRemovableChip" }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: SdChip, decorators: [{
            type: Component,
            args: [{ selector: 'sd-chip', changeDetection: ChangeDetectionStrategy.OnPush, standalone: true, imports: [
                        CommonModule,
                        FormsModule,
                        ReactiveFormsModule,
                        MatInputModule,
                        MatTooltipModule,
                        MatFormFieldModule,
                        MatAutocompleteModule,
                        MatIconModule,
                        MatProgressSpinnerModule,
                        MatChipsModule,
                        SdRemovableChipPipe,
                    ], template: "@let labelTemplate = sdLabelDef?.templateRef;\r\n@let viewTemplate = sdView?.templateRef;\r\n\r\n@if (!appearance && labelTemplate) {\r\n  <ng-container *ngTemplateOutlet=\"labelTemplate\"></ng-container>\r\n}\r\n@if (!appearance && label && !labelTemplate) {\r\n  <div class=\"d-block mb-0 T14M\">{{ label }} <span class=\"text-danger mb-2\" *ngIf=\"required\">*</span></div>\r\n}\r\n<div\r\n  class=\"d-flex align-items-center\"\r\n  [class.sd-view]=\"viewTemplate\"\r\n  [class.c-focused]=\"isFocused\"\r\n  [class.c-disabled]=\"formControl.disabled\"\r\n  (keydown.enter)=\"onClick()\"\r\n  tabindex=\"0\"\r\n  (click)=\"onClick()\">\r\n  @if (viewTemplate && !isFocused) {\r\n    <ng-container *ngTemplateOutlet=\"viewTemplate; context: { value: formControl.value }\"></ng-container>\r\n  } @else {\r\n    <mat-form-field\r\n      [class.sd-md]=\"size === 'md'\"\r\n      [class.sd-sm]=\"size === 'sm'\"\r\n      [class.hide-inline-error]=\"hideInlineError\"\r\n      [appearance]=\"appearance\">\r\n      @if (appearance && label) {\r\n        <mat-label>{{ label }}</mat-label>\r\n      }\r\n      <mat-chip-grid [formControl]=\"formControl\" #chipList [class.sd-md]=\"size === 'md'\" [class.sd-sm]=\"size === 'sm'\">\r\n        @for (item of formControl.value; track $index) {\r\n          @if (item) {\r\n            <mat-chip-row\r\n              [class.sd-md]=\"size === 'md'\"\r\n              [class.sd-sm]=\"size === 'sm'\"\r\n              [removable]=\"removable\"\r\n              (removed)=\"onRemove(item)\"\r\n              [disabled]=\"inputControl.disabled\"\r\n              (click)=\"onClickChip($event, item)\">\r\n              <span>{{ item }}</span>\r\n              @if (!inputControl.disabled && item | sdRemovableChip: removable) {\r\n                <mat-icon matChipRemove>cancel</mat-icon>\r\n              }\r\n            </mat-chip-row>\r\n          }\r\n        }\r\n        <input\r\n          class=\"sd-chip-input\"\r\n          [formControl]=\"inputControl\"\r\n          [placeholder]=\"placeholder || label\"\r\n          [matChipInputFor]=\"chipList\"\r\n          [matChipInputSeparatorKeyCodes]=\"separatorKeysCodes\"\r\n          (matChipInputTokenEnd)=\"onAdd($event)\"\r\n          autocomplete=\"off\"\r\n          [errorStateMatcher]=\"matcher\"\r\n          (focus)=\"onFocus()\"\r\n          (blur)=\"onBlur()\"\r\n          [required]=\"required\"\r\n          matInput\r\n          [attr.data-autoId]=\"autoId\"\r\n          #input />\r\n      </mat-chip-grid>\r\n      @if (formControl.errors?.['required'] && !hideInlineError) {\r\n        <mat-error>{{ 'Vui l\u00F2ng nh\u1EADp th\u00F4ng tin' }}</mat-error>\r\n      }\r\n      @if (formControl.errors?.['minlength'] && !hideInlineError) {\r\n        <mat-error>{{ 'Vui l\u00F2ng nh\u1EADp \u00EDt nh\u1EA5t ' + min + ' gi\u00E1 tr\u1ECB' }} </mat-error>\r\n      }\r\n      @if (formControl.errors?.['maxlength'] && !hideInlineError) {\r\n        <mat-error>{{ 'Vui l\u00F2ng nh\u1EADp t\u1ED1i \u0111a ' + max + ' gi\u00E1 tr\u1ECB' }} </mat-error>\r\n      }\r\n    </mat-form-field>\r\n  }\r\n</div>\r\n", styles: [":host{padding-top:5px;display:block}.sd-chip-input{margin-top:0!important}:host ::ng-deep .mat-mdc-form-field.no-padding-wrapper .mat-mdc-text-field-wrapper{padding-bottom:0}:host ::ng-deep mat-form-field.c-md .mat-mdc-standard-chip{padding:7px 10px;min-height:26px}:host ::ng-deep mat-form-field.c-md .mat-mdc-standard-chip .mat-mdc-chip-trailing-icon{padding:7px 7px 7px 10px}:host ::ng-deep .mat-mdc-chip-row.sd-sm{--mdc-chip-label-text-size: 12px;--mdc-chip-container-height: 20px}:host ::ng-deep .mat-mdc-chip-set.sd-md{margin-top:10px}:host ::ng-deep .mat-mdc-chip-set.sd-sm{margin-top:2px}.sd-view:not(.c-focused):not(.c-disabled):hover{background-color:#ebecf0}\n"] }]
        }], ctorParameters: () => [{ type: i0.ChangeDetectorRef }], propDecorators: { _autoId: [{
                type: Input,
                args: ['autoId']
            }], _name: [{
                type: Input,
                args: ['name']
            }], appearance: [{
                type: Input
            }], size: [{
                type: Input
            }], form: [{
                type: Input
            }], _addable: [{
                type: Input,
                args: ['addable']
            }], label: [{
                type: Input
            }], placeholder: [{
                type: Input
            }], _removable: [{
                type: Input,
                args: ['removable']
            }], _hideInlineError: [{
                type: Input,
                args: ['hideInlineError']
            }], model: [{
                type: Input
            }], _required: [{
                type: Input,
                args: ['required']
            }], pMin: [{
                type: Input,
                args: ['min']
            }], pMax: [{
                type: Input,
                args: ['max']
            }], modelChange: [{
                type: Output
            }], disabled: [{
                type: Input
            }], sdChange: [{
                type: Output
            }], input: [{
                type: ViewChild,
                args: ['input']
            }], sdView: [{
                type: ContentChild,
                args: [SdViewDefDirective]
            }], sdLabelDef: [{
                type: ContentChild,
                args: [SdLabelDefDirective]
            }] } });

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

export { SdChip, SdRemovableChipPipe };
//# sourceMappingURL=sd-angular-core-forms-chip.mjs.map
