thingsboard/ui-ngx/src/app/shared/components/unit-input.component.ts

257 lines
7.3 KiB
TypeScript
Raw Normal View History

2023-07-07 17:27:59 +03:00
///
2025-02-25 09:39:16 +02:00
/// Copyright © 2016-2025 The Thingsboard Authors
2023-07-07 17:27:59 +03: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 {
booleanAttribute,
Component,
ElementRef,
forwardRef,
HostBinding,
Input,
OnChanges,
OnInit,
Renderer2,
SimpleChanges,
ViewChild,
ViewContainerRef,
2023-10-20 15:19:10 +03:00
ViewEncapsulation
} from '@angular/core';
import { ControlValueAccessor, FormBuilder, FormControl, NG_VALUE_ACCESSOR, Validators } from '@angular/forms';
import { Observable, of, shareReplay } from 'rxjs';
import {
AllMeasures,
getSourceTbUnitSymbol,
2025-05-16 14:01:44 +03:00
getTbUnitFromSearch,
isTbUnitMapping,
2025-05-16 14:01:44 +03:00
searchUnit,
TbUnit,
UnitInfo,
UnitSystem
} from '@shared/models/unit.models';
import { map, mergeMap } from 'rxjs/operators';
2025-05-01 16:05:35 +03:00
import { UnitService } from '@core/services/unit.service';
import { TbPopoverService } from '@shared/components/popover.service';
import { UnitSettingsPanelComponent } from '@shared/components/unit-settings-panel.component';
2025-05-16 14:01:44 +03:00
import { isDefinedAndNotNull, isEqual } from '@core/utils';
2023-07-14 19:30:18 +03:00
2023-07-07 17:27:59 +03:00
@Component({
selector: 'tb-unit-input',
templateUrl: './unit-input.component.html',
styleUrls: ['./unit-input.component.scss'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => UnitInputComponent),
multi: true
}
],
encapsulation: ViewEncapsulation.None
})
export class UnitInputComponent implements ControlValueAccessor, OnInit, OnChanges {
@HostBinding('style.display') readonly hostDisplay = 'flex';
@ViewChild('unitInput', {static: true}) unitInput: ElementRef;
2023-07-07 17:27:59 +03:00
2025-05-01 16:05:35 +03:00
unitsFormControl: FormControl<TbUnit | UnitInfo>;
2023-07-07 17:27:59 +03:00
2025-04-29 15:35:18 +03:00
@Input({transform: booleanAttribute})
2023-07-07 17:27:59 +03:00
disabled: boolean;
@Input({transform: booleanAttribute})
required = false;
2023-09-12 15:07:33 +03:00
@Input()
tagFilter: string;
2023-09-12 15:07:33 +03:00
@Input()
measure: AllMeasures;
@Input()
unitSystem: UnitSystem;
@Input({transform: booleanAttribute})
supportsUnitConversion = false;
2023-07-07 17:27:59 +03:00
@Input({transform: booleanAttribute})
onlySystemUnits = false;
filteredUnits$: Observable<Array<[AllMeasures, Array<UnitInfo>]>>;
2023-07-07 17:27:59 +03:00
searchText = '';
2025-04-29 15:35:18 +03:00
isUnitMapping = false;
2025-04-28 18:27:35 +03:00
2023-07-07 17:27:59 +03:00
private dirty = false;
private modelValue: TbUnit | null;
2025-05-01 16:05:35 +03:00
private fetchUnits$: Observable<Array<[AllMeasures, Array<UnitInfo>]>> = null;
2023-07-07 17:27:59 +03:00
private propagateChange = (_val: any) => {};
2023-10-20 15:19:10 +03:00
constructor(private fb: FormBuilder,
private unitService: UnitService,
private popoverService: TbPopoverService,
private renderer: Renderer2,
private viewContainerRef: ViewContainerRef,
private elementRef: ElementRef) {
2023-07-07 17:27:59 +03:00
}
ngOnInit() {
2025-05-01 16:05:35 +03:00
this.unitsFormControl = this.fb.control<TbUnit | UnitInfo>('', this.required ? [Validators.required] : []);
this.filteredUnits$ = this.unitsFormControl.valueChanges.pipe(
map(value => {
this.updateModel(value);
return getSourceTbUnitSymbol(value);
}),
mergeMap(symbol => this.fetchUnits(symbol))
);
2023-07-07 17:27:59 +03:00
}
ngOnChanges(changes: SimpleChanges) {
for (const propName of Object.keys(changes)) {
const change = changes[propName];
if (!change.firstChange && change.currentValue !== change.previousValue) {
if (propName === 'measure' || propName === 'unitSystem') {
this.fetchUnits$ = null;
this.dirty = true;
}
}
}
}
writeValue(symbol?: TbUnit): void {
2023-07-07 17:27:59 +03:00
this.searchText = '';
this.modelValue = symbol;
if (typeof symbol === 'string') {
2025-05-01 16:05:35 +03:00
this.unitsFormControl.patchValue(this.unitService.getUnitInfo(symbol) ?? symbol, {emitEvent: false});
2025-04-29 15:35:18 +03:00
this.isUnitMapping = false;
} else {
this.unitsFormControl.patchValue(symbol, {emitEvent: false});
this.isUnitMapping = isDefinedAndNotNull(symbol);
}
this.dirty = true;
2023-07-07 17:27:59 +03:00
}
onFocus() {
if (this.dirty) {
this.unitsFormControl.updateValueAndValidity({onlySelf: true, emitEvent: true});
this.dirty = false;
}
}
2025-05-01 16:05:35 +03:00
displayUnitFn(unit?: TbUnit | UnitInfo): string | undefined {
2023-07-07 17:27:59 +03:00
if (unit) {
return getSourceTbUnitSymbol(unit);
2023-07-07 17:27:59 +03:00
}
return undefined;
}
registerOnChange(fn: any): void {
this.propagateChange = fn;
}
registerOnTouched(_fn: any): void {
2023-07-07 17:27:59 +03:00
}
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
if (this.disabled) {
this.unitsFormControl.disable({emitEvent: false});
} else {
this.unitsFormControl.enable({emitEvent: false});
}
}
2025-04-29 15:35:18 +03:00
clear($event: Event) {
$event.stopPropagation();
2023-07-07 17:27:59 +03:00
this.unitsFormControl.patchValue(null, {emitEvent: true});
setTimeout(() => {
this.unitInput.nativeElement.blur();
this.unitInput.nativeElement.focus();
}, 0);
2023-07-07 17:27:59 +03:00
}
2023-07-14 19:30:18 +03:00
openUnitSettingsPopup($event: Event) {
if (!this.supportsUnitConversion) {
2025-04-29 15:35:18 +03:00
return;
}
$event.stopPropagation();
2025-04-29 15:35:18 +03:00
this.unitInput.nativeElement.blur();
const trigger = this.elementRef.nativeElement;
if (this.popoverService.hasPopover(trigger)) {
this.popoverService.hidePopover(trigger);
} else {
const popover = this.popoverService.displayPopover({
trigger,
renderer: this.renderer,
componentType: UnitSettingsPanelComponent,
hostView: this.viewContainerRef,
preferredPlacement: ['left', 'bottom', 'top'],
context: {
2025-05-16 14:01:44 +03:00
unit: getTbUnitFromSearch(this.unitsFormControl.value),
2025-04-29 15:35:18 +03:00
required: this.required,
disabled: this.disabled,
tagFilter: this.tagFilter,
measure: this.measure
},
isModal: true
});
popover.tbComponentRef.instance.unitSettingsApplied.subscribe((unitSetting) => {
popover.hide();
this.unitsFormControl.patchValue(unitSetting, {emitEvent: false});
this.updateModel(unitSetting);
});
}
}
private updateModel(value: UnitInfo | TbUnit ) {
2025-05-16 14:01:44 +03:00
let res = getTbUnitFromSearch(value);
if (this.onlySystemUnits && !isTbUnitMapping(res)) {
const unitInfo = this.unitService.getUnitInfo(res as string);
if (unitInfo) {
if (this.measure && unitInfo.measure !== this.measure) {
res = null;
}
} else {
res = null;
}
}
if (!isEqual(this.modelValue, res)) {
this.modelValue = res;
this.isUnitMapping = isTbUnitMapping(res);
this.propagateChange(this.modelValue);
}
}
2025-05-01 16:05:35 +03:00
private fetchUnits(searchText?: string): Observable<Array<[AllMeasures, Array<UnitInfo>]>> {
this.searchText = searchText;
return this.getGroupedUnits().pipe(
2025-05-16 14:01:44 +03:00
map(unit => searchUnit(unit, searchText))
);
}
private getGroupedUnits(): Observable<Array<[AllMeasures, Array<UnitInfo>]>> {
2023-07-14 19:30:18 +03:00
if (this.fetchUnits$ === null) {
2025-05-16 14:01:44 +03:00
this.fetchUnits$ = of(this.unitService.getUnitsGroupedByMeasure(this.measure, this.unitSystem, this.tagFilter)).pipe(
map(data => Object.entries(data) as Array<[AllMeasures, UnitInfo[]]>),
shareReplay(1)
2023-07-14 19:30:18 +03:00
);
}
return this.fetchUnits$;
}
2023-07-07 17:27:59 +03:00
}