thingsboard/ui-ngx/src/app/shared/components/string-items-list.component.ts

271 lines
7.1 KiB
TypeScript
Raw Normal View History

2023-02-02 15:25:04 +02:00
///
/// Copyright © 2016-2023 The Thingsboard Authors
2023-02-02 15:25:04 +02:00
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
import { Component, ElementRef, forwardRef, Input, OnInit, ViewChild } from '@angular/core';
import {
AbstractControl,
ControlValueAccessor,
FormBuilder,
FormGroup,
NG_VALUE_ACCESSOR,
Validators
} from '@angular/forms';
2023-02-02 15:25:04 +02:00
import { MatChipInputEvent } from '@angular/material/chips';
import { COMMA, ENTER, SEMICOLON } from '@angular/cdk/keycodes';
import { FloatLabelType, MatFormFieldAppearance, SubscriptSizing } from '@angular/material/form-field';
import { coerceArray, coerceBoolean } from '@shared/decorators/coercion';
import { Observable, of } from 'rxjs';
import { filter, mergeMap, share, tap } from 'rxjs/operators';
import { MatAutocompleteTrigger } from '@angular/material/autocomplete';
2023-02-02 15:25:04 +02:00
export interface StringItemsOption {
name: string;
value: any;
}
2023-02-02 15:25:04 +02:00
@Component({
2023-02-13 16:11:23 +02:00
selector: 'tb-string-items-list',
templateUrl: './string-items-list.component.html',
2023-02-02 15:25:04 +02:00
styleUrls: [],
providers: [
{
provide: NG_VALUE_ACCESSOR,
2023-02-13 16:11:23 +02:00
useExisting: forwardRef(() => StringItemsListComponent),
2023-02-02 15:25:04 +02:00
multi: true
}
]
})
export class StringItemsListComponent implements ControlValueAccessor, OnInit {
2023-02-02 15:25:04 +02:00
2023-02-13 16:11:23 +02:00
stringItemsForm: FormGroup;
filteredValues: Observable<Array<StringItemsOption>>;
searchText = '';
itemList: StringItemsOption[] = [];
2023-02-02 15:25:04 +02:00
private modelValue: Array<string> | null;
readonly separatorKeysCodes: number[] = [ENTER, COMMA, SEMICOLON];
@ViewChild('stringItemInput', {static: true}) stringItemInput: ElementRef<HTMLInputElement>;
@ViewChild(MatAutocompleteTrigger) autocomplete: MatAutocompleteTrigger;
2023-02-02 15:25:04 +02:00
private requiredValue: boolean;
2023-02-02 15:25:04 +02:00
get required(): boolean {
return this.requiredValue;
}
2023-02-02 15:25:04 +02:00
@Input()
@coerceBoolean()
2023-02-02 15:25:04 +02:00
set required(value: boolean) {
if (this.requiredValue !== value) {
this.requiredValue = value;
2023-02-02 15:25:04 +02:00
this.updateValidators();
}
}
@Input()
@coerceBoolean()
2023-02-02 15:25:04 +02:00
disabled: boolean;
2023-02-13 16:11:23 +02:00
@Input()
label: string;
@Input()
placeholder: string;
@Input()
hint: string;
@Input()
requiredText: string;
@Input()
floatLabel: FloatLabelType = 'auto';
@Input()
2023-03-06 11:27:07 +02:00
appearance: MatFormFieldAppearance = 'fill';
2023-02-13 16:11:23 +02:00
@Input()
@coerceBoolean()
2023-03-20 16:51:42 +02:00
editable = false;
@Input()
subscriptSizing: SubscriptSizing = 'fixed';
@Input()
@coerceArray()
predefinedValues: StringItemsOption[];
get itemsControl(): AbstractControl {
return this.stringItemsForm.get('items');
}
get itemControl(): AbstractControl {
return this.stringItemsForm.get('item');
}
private propagateChange = (v: any) => {
};
private dirty = false;
2023-02-02 15:25:04 +02:00
constructor(private fb: FormBuilder) {
2023-02-13 16:11:23 +02:00
this.stringItemsForm = this.fb.group({
item: [null],
items: [null]
2023-02-02 15:25:04 +02:00
});
}
ngOnInit() {
if (this.predefinedValues) {
this.filteredValues = this.itemControl.valueChanges
.pipe(
tap((value) => {
if (value && typeof value !== 'string') {
this.add(value);
} else if (value === null) {
this.clear();
}
}),
filter((value) => typeof value === 'string'),
mergeMap(name => this.fetchValues(name)),
share()
);
}
}
2023-02-02 15:25:04 +02:00
updateValidators() {
this.itemsControl.setValidators(this.required ? [Validators.required] : []);
this.itemsControl.updateValueAndValidity();
2023-02-02 15:25:04 +02:00
}
registerOnChange(fn: any): void {
this.propagateChange = fn;
}
registerOnTouched(fn: any): void {
}
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
if (isDisabled) {
2023-02-13 16:11:23 +02:00
this.stringItemsForm.disable({emitEvent: false});
2023-02-02 15:25:04 +02:00
} else {
2023-02-13 16:11:23 +02:00
this.stringItemsForm.enable({emitEvent: false});
2023-02-02 15:25:04 +02:00
}
}
writeValue(value: Array<string> | null): void {
this.searchText = '';
2023-02-02 15:25:04 +02:00
if (value != null && value.length > 0) {
this.modelValue = [...value];
this.itemList = [];
if (this.predefinedValues) {
value.forEach(item => {
const findItem = this.predefinedValues.find(option => option.value === item);
if (findItem) {
this.itemList.push(findItem);
}
});
} else {
value.forEach(item => this.itemList.push({value: item, name: item}));
}
this.itemsControl.setValue(this.itemList, {emitEvents: false});
2023-02-02 15:25:04 +02:00
} else {
this.itemsControl.setValue(null, {emitEvents: false});
2023-02-02 15:25:04 +02:00
this.modelValue = null;
this.itemList = [];
2023-02-02 15:25:04 +02:00
}
this.dirty = true;
2023-02-02 15:25:04 +02:00
}
2023-02-13 16:11:23 +02:00
addItem(event: MatChipInputEvent): void {
const item = event.value?.trim() ?? '';
2023-02-13 16:11:23 +02:00
if (item) {
if (this.predefinedValues) {
const findItems = this.predefinedValues
.filter(value => value.name.toLowerCase().includes(item.toLowerCase()));
if (findItems.length === 1) {
this.add(findItems[0]);
2023-02-02 15:25:04 +02:00
}
} else {
this.add({value: item, name: item});
2023-02-02 15:25:04 +02:00
}
}
}
removeItems(item: StringItemsOption) {
const index = this.modelValue.indexOf(item.value);
2023-02-02 15:25:04 +02:00
if (index >= 0) {
this.modelValue.splice(index, 1);
this.itemList.splice(index, 1);
2023-02-02 15:25:04 +02:00
if (!this.modelValue.length) {
this.modelValue = null;
}
this.itemsControl.setValue(this.itemList);
2023-02-02 15:25:04 +02:00
this.propagateChange(this.modelValue);
this.autocomplete?.closePanel();
}
}
onFocus() {
if (this.dirty) {
this.itemControl.updateValueAndValidity({onlySelf: true, emitEvent: true});
this.dirty = false;
}
}
displayValueFn(values?: StringItemsOption): string | undefined {
return values ? values.name : undefined;
}
private add(item: StringItemsOption) {
if (!this.modelValue || this.modelValue.indexOf(item.value) === -1) {
if (!this.modelValue) {
this.modelValue = [];
}
this.modelValue.push(item.value);
this.itemList.push(item);
this.itemsControl.setValue(this.itemList);
2023-02-02 15:25:04 +02:00
}
this.propagateChange(this.modelValue);
this.clear();
2023-02-02 15:25:04 +02:00
}
private fetchValues(searchText?: string): Observable<Array<StringItemsOption>> {
if (!this.predefinedValues?.length) {
return of([]);
}
this.searchText = searchText;
let result = this.predefinedValues;
if (searchText && searchText.length) {
result = this.predefinedValues.filter(option => option.name.toLowerCase().includes(searchText.toLowerCase()));
}
return of(result);
2023-02-02 15:25:04 +02:00
}
private clear(value: string = '') {
this.stringItemInput.nativeElement.value = value;
this.itemControl.patchValue(value, {emitEvent: true});
setTimeout(() => {
this.stringItemInput.nativeElement.blur();
this.stringItemInput.nativeElement.focus();
}, 0);
}
2023-02-02 15:25:04 +02:00
}