widget-settings.models.ts
37.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
///
/// Copyright © 2016-2024 The Thingsboard Authors
///
/// 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 { isDefinedAndNotNull, isNumber, isNumeric, isUndefinedOrNull, mergeDeep, parseFunction } from '@core/utils';
import {
DataEntry,
DataKey,
Datasource,
DatasourceData,
DatasourceType,
TargetDevice,
TargetDeviceType,
widgetType
} from '@shared/models/widget.models';
import { EventEmitter, Injector } from '@angular/core';
import { DatePipe } from '@angular/common';
import { DateAgoPipe } from '@shared/pipe/date-ago.pipe';
import { TranslateService } from '@ngx-translate/core';
import { AlarmFilterConfig } from '@shared/models/query/query.models';
import { AlarmSearchStatus } from '@shared/models/alarm.models';
import { EMPTY, Observable, of } from 'rxjs';
import { ImagePipe } from '@shared/pipe/image.pipe';
import { map } from 'rxjs/operators';
import { DomSanitizer } from '@angular/platform-browser';
import { AVG_MONTH, DAY, HOUR, Interval, IntervalMath, MINUTE, SECOND, YEAR } from '@shared/models/time/time.models';
import moment from 'moment';
import tinycolor from 'tinycolor2';
import { WidgetContext } from '@home/models/widget-component.models';
import { DataKeyType } from '@shared/models/telemetry/telemetry.models';
import {
IWidgetSubscription,
WidgetSubscriptionCallbacks,
WidgetSubscriptionOptions
} from '@core/api/widget-api.models';
export type ComponentStyle = {[klass: string]: any};
export const cssUnits = ['px', 'em', '%', 'rem', 'pt', 'pc', 'in', 'cm', 'mm', 'ex', 'ch', 'vw', 'vh', 'vmin', 'vmax'] as const;
type cssUnitTuple = typeof cssUnits;
export type cssUnit = cssUnitTuple[number];
export const fontWeights = ['normal', 'bold', 'bolder', 'lighter', '100', '200', '300', '400', '500', '600', '700', '800', '900'] as const;
type fontWeightTuple = typeof fontWeights;
export type fontWeight = fontWeightTuple[number];
export const fontWeightTranslations = new Map<fontWeight, string>(
[
['normal', 'widgets.widget-font.font-weight-normal'],
['bold', 'widgets.widget-font.font-weight-bold'],
['bolder', 'widgets.widget-font.font-weight-bolder'],
['lighter', 'widgets.widget-font.font-weight-lighter']
]
);
export const fontStyles = ['normal', 'italic', 'oblique'] as const;
type fontStyleTuple = typeof fontStyles;
export type fontStyle = fontStyleTuple[number];
export const fontStyleTranslations = new Map<fontStyle, string>(
[
['normal', 'widgets.widget-font.font-style-normal'],
['italic', 'widgets.widget-font.font-style-italic'],
['oblique', 'widgets.widget-font.font-style-oblique']
]
);
export const commonFonts = ['Roboto', 'monospace', 'sans-serif', 'serif'];
export interface Font {
size: number;
sizeUnit: cssUnit;
family: string;
weight: fontWeight;
style: fontStyle;
lineHeight: string;
}
export enum ValueSourceType {
constant = 'constant',
latestKey = 'latestKey',
entity = 'entity'
}
export const ValueSourceTypes = Object.keys(ValueSourceType) as ValueSourceType[];
export const ValueSourceTypeTranslation = new Map<ValueSourceType, string>(
[
[ValueSourceType.constant, 'widgets.value-source.type-constant'],
[ValueSourceType.latestKey, 'widgets.value-source.type-latest-key'],
[ValueSourceType.entity, 'widgets.value-source.type-entity']
]
);
export interface ValueSourceConfig {
type: ValueSourceType;
value?: number;
latestKeyType?: DataKeyType.attribute | DataKeyType.timeseries;
latestKey?: string;
entityKeyType?: DataKeyType.attribute | DataKeyType.timeseries;
entityAlias?: string;
entityKey?: string;
}
export enum ColorType {
constant = 'constant',
gradient = 'gradient',
range = 'range',
function = 'function'
}
export const colorTypeTranslations = new Map<ColorType, string>(
[
[ColorType.constant, 'widgets.color.color-type-constant'],
[ColorType.gradient, 'widgets.color.color-type-gradient'],
[ColorType.range, 'widgets.color.color-type-range'],
[ColorType.function, 'widgets.color.color-type-function']
]
);
interface AdvancedColorMode {
advancedMode?: boolean;
}
export interface ColorRange {
from?: number;
to?: number;
color: string;
}
export interface AdvancedColorRange {
from?: ValueSourceConfig;
to?: ValueSourceConfig;
color: string;
}
export interface ColorRangeSettings extends AdvancedColorMode {
range?: ColorRange[];
rangeAdvanced?: AdvancedColorRange[];
}
export interface ColorGradientSettings extends AdvancedColorMode {
gradient?: string[];
gradientAdvanced?: AdvancedGradient[];
minValue?: number;
maxValue?: number;
}
export interface AdvancedGradient {
source: ValueSourceConfig;
color: string;
}
export interface ColorSettings {
type: ColorType;
color: string;
rangeList?: ColorRangeSettings;
gradient?: ColorGradientSettings;
colorFunction?: string;
}
export const colorRangeIncludes = (range: ColorRange, toCheck: ColorRange): boolean => {
if (isNumber(range.from) && isNumber(range.to)) {
if (isNumber(toCheck.from) && isNumber(toCheck.to)) {
return toCheck.from >= range.from && toCheck.to < range.to;
} else {
return false;
}
} else if (isNumber(range.from)) {
if (isNumber(toCheck.from)) {
return toCheck.from >= range.from;
} else {
return false;
}
} else if (isNumber(range.to)) {
if (isNumber(toCheck.to)) {
return toCheck.to < range.to;
} else {
return false;
}
} else {
return false;
}
};
export const filterIncludingColorRanges = (ranges: Array<ColorRange>): Array<ColorRange> => {
const result = [...ranges];
let includes = true;
while (includes) {
let index = -1;
for (let i = 0; i < result.length; i++) {
const range = result[i];
if (result.some((value, i1) => i1 !== i && colorRangeIncludes(value, range))) {
index = i;
break;
}
}
if (index > -1) {
result.splice(index, 1);
} else {
includes = false;
}
}
return result;
};
export const sortedColorRange = (ranges: Array<ColorRange>): Array<ColorRange> => ranges ? [...ranges].sort(
(a, b) => {
if (isNumber(a.from) && isNumber(a.to) && isNumber(b.from) && isNumber(b.to)) {
if (b.from >= a.from && b.to < a.to) {
return 1;
} else if (a.from >= b.from && a.to < b.to) {
return -1;
} else {
return a.from - b.from;
}
} else if (isNumber(a.from) && isNumber(b.from)) {
return a.from - b.from;
} else if (isNumber(a.to) && isNumber(b.to)) {
return a.to - b.to;
} else if (isNumber(a.from) && isUndefinedOrNull(b.from)) {
return 1;
} else if (isUndefinedOrNull(a.from) && isNumber(b.from)) {
return -1;
} else if (isNumber(a.to) && isUndefinedOrNull(b.to)) {
return 1;
} else if (isUndefinedOrNull(a.to) && isNumber(b.to)) {
return -1;
} else {
return 0;
}
}
) : [];
export interface TimewindowStyle {
showIcon: boolean;
icon: string;
iconSize: string;
iconPosition: 'left' | 'right';
font?: Font;
color?: string;
displayTypePrefix?: boolean;
}
export const defaultTimewindowStyle: TimewindowStyle = {
showIcon: true,
icon: 'query_builder',
iconSize: '24px',
iconPosition: 'left',
displayTypePrefix: true
};
export const constantColor = (color: string): ColorSettings => ({
type: ColorType.constant,
color,
colorFunction: defaultColorFunction
});
export const gradientColor = (defaultColor: string, colors: string[], minValue?: number, maxValue?: number): ColorSettings => ({
type: ColorType.gradient,
color: defaultColor,
colorFunction: defaultColorFunction,
gradient: {
advancedMode: false,
gradient: colors,
minValue: isDefinedAndNotNull(minValue) ? minValue : 0,
maxValue: isDefinedAndNotNull(maxValue) ? maxValue : 100
}
});
export const defaultGradient = (minValue?: number, maxValue?: number): ColorGradientSettings => ({
advancedMode: false,
gradient: ['rgba(0, 255, 0, 1)', 'rgba(255, 0, 0, 1)'],
gradientAdvanced: [
{
source: {type: ValueSourceType.constant},
color: 'rgba(0, 255, 0, 1)'
},
{
source: {type: ValueSourceType.constant},
color: 'rgba(255, 0, 0, 1)'
}
],
minValue: isDefinedAndNotNull(minValue) ? minValue : 0,
maxValue: isDefinedAndNotNull(maxValue) ? maxValue : 100
});
export const defaultRange = (): ColorRangeSettings => ({
advancedMode: false,
range: [],
rangeAdvanced: []
});
const updateGradientMinMaxValues = (colorSettings: ColorSettings, minValue?: number, maxValue?: number): void => {
if (isDefinedAndNotNull(colorSettings.gradient)) {
if (isDefinedAndNotNull(minValue)) {
colorSettings.gradient.minValue = minValue;
}
if (isDefinedAndNotNull(maxValue)) {
colorSettings.gradient.maxValue = maxValue;
}
}
};
export const defaultColorFunction = 'var temperature = value;\n' +
'if (typeof temperature !== undefined) {\n' +
' var percent = (temperature + 60)/120 * 100;\n' +
' return tinycolor.mix(\'blue\', \'red\', percent).toHexString();\n' +
'}\n' +
'return \'blue\';';
export const cssSizeToStrSize = (size?: number, unit?: cssUnit): string => (isDefinedAndNotNull(size) ? size + '' : '0') + (unit || 'px');
export const resolveCssSize = (strSize?: string): [number, cssUnit] => {
if (!strSize || !strSize.trim().length) {
return [null, 'px'];
}
let resolvedUnit: cssUnit;
let resolvedSize = strSize;
for (const unit of cssUnits) {
if (strSize.endsWith(unit)) {
resolvedUnit = unit;
break;
}
}
if (resolvedUnit) {
resolvedSize = strSize.substring(0, strSize.length - resolvedUnit.length);
}
resolvedUnit = resolvedUnit || 'px';
let numericSize: number = null;
if (isNumeric(resolvedSize)) {
numericSize = Number(resolvedSize);
}
return [numericSize, resolvedUnit];
};
export const validateCssSize = (strSize?: string): string | undefined => {
const resolved = resolveCssSize(strSize);
if (!!resolved[0] && !!resolved[1]) {
return cssSizeToStrSize(resolved[0], resolved[1]);
} else {
return undefined;
}
};
type ValueColorFunction = (value: any) => string;
export interface ColorProcessorSettings {
settings: ColorSettings;
ctx?: WidgetContext;
minGradientValue?: number;
maxGradientValue?: number;
}
export abstract class ColorProcessor {
static fromSettings(color: ColorSettings, ctx?: WidgetContext): ColorProcessor {
return ColorProcessor.fromColorProcessorSettings({
settings: color,
ctx
});
}
static fromColorProcessorSettings(setting: ColorProcessorSettings): ColorProcessor {
const settings = setting.settings || constantColor(null);
switch (settings.type) {
case ColorType.constant:
return new ConstantColorProcessor(settings);
case ColorType.range:
return new RangeColorProcessor(settings, setting.ctx);
case ColorType.function:
return new FunctionColorProcessor(settings);
case ColorType.gradient:
updateGradientMinMaxValues(settings, setting.minGradientValue, setting.maxGradientValue);
return new GradientColorProcessor(settings, setting.ctx);
default:
return new ConstantColorProcessor(settings);
}
}
color: string;
colorUpdated?: EventEmitter<void>;
protected constructor(protected settings: ColorSettings) {
this.color = settings.color;
}
abstract update(value: any): void;
destroy(): void {};
}
class ConstantColorProcessor extends ColorProcessor {
constructor(protected settings: ColorSettings) {
super(settings);
}
update(value: any): void {}
}
class FunctionColorProcessor extends ColorProcessor {
private readonly colorFunction: ValueColorFunction;
constructor(protected settings: ColorSettings) {
super(settings);
this.colorFunction = parseFunction(settings.colorFunction, ['value']);
}
update(value: any): void {
if (this.colorFunction) {
this.color = this.colorFunction(value) || this.settings.color;
}
}
}
export abstract class AdvancedModeColorProcessor extends ColorProcessor {
protected sourcesSubscription: IWidgetSubscription;
protected advancedMode: boolean;
private currentValue: number;
colorUpdated = new EventEmitter<void>();
protected constructor(protected settings: ColorSettings,
protected ctx: WidgetContext) {
super(settings);
this.advancedMode = this.getCurrentConfig()?.advancedMode;
if (this.advancedMode) {
createValueSubscription(
this.ctx,
this.datasourceConfigs(),
this.onDataUpdated.bind(this)
).subscribe((subscription) => {
this.sourcesSubscription = subscription;
});
}
}
abstract updatedAdvancedData(data: Array<DatasourceData>): void;
abstract datasourceConfigs(): Array<ValueSourceConfig>;
abstract getCurrentConfig(): AdvancedColorMode;
update(value: any) {
if (this.advancedMode) {
this.currentValue = value;
}
}
destroy(): void {
if (this.sourcesSubscription) {
this.ctx.subscriptionApi.removeSubscription(this.sourcesSubscription.id);
}
this.colorUpdated.complete();
this.colorUpdated.unsubscribe();
this.colorUpdated = null;
}
private onDataUpdated(subscription: IWidgetSubscription) {
this.updatedAdvancedData(subscription.data);
if (this.currentValue) {
this.update(this.currentValue);
this.colorUpdated.emit();
}
}
}
class RangeColorProcessor extends AdvancedModeColorProcessor {
constructor(protected settings: ColorSettings,
protected ctx: WidgetContext) {
super(settings, ctx);
}
update(value: any): void {
super.update(value);
this.color = this.computeFromRange(value);
}
updatedAdvancedData(data: Array<DatasourceData>) {
for (const keyData of data) {
if (keyData && keyData.data && keyData.data[0]) {
const attrValue = keyData.data[0][1];
if (isFinite(attrValue)) {
for (const currentIndex of keyData.dataKey.settings.indexes) {
const index = Math.floor(currentIndex / 2);
if (index === currentIndex / 2) {
this.settings.rangeList.rangeAdvanced[index].from.value = attrValue;
} else {
this.settings.rangeList.rangeAdvanced[index].to.value = attrValue;
}
}
}
}
}
}
datasourceConfigs(): Array<ValueSourceConfig> {
const configs: Array<ValueSourceConfig> = [];
for (const range of this.settings.rangeList.rangeAdvanced) {
if (range.from) {
configs.push(range.from);
}
if (range.to) {
configs.push(range.to);
}
}
return configs;
}
getCurrentConfig(): AdvancedColorMode {
return this.settings.rangeList;
}
private computeFromRange(value: any): string {
let rangeList: any = this.settings.rangeList as Array<ColorRange>;
let advancedMode = false;
if (isDefinedAndNotNull(this.settings.rangeList?.advancedMode)) {
advancedMode = this.settings.rangeList.advancedMode;
rangeList = advancedMode ?
this.settings.rangeList.rangeAdvanced as Array<AdvancedColorRange> :
this.settings.rangeList.range as Array<ColorRange>;
}
if (rangeList?.length && isDefinedAndNotNull(value) && isNumeric(value)) {
const num = Number(value);
for (const range of rangeList) {
if (advancedMode ?
(RangeColorProcessor.constantAdvancedRange(range) && range.from.value === num ) :
(RangeColorProcessor.constantRange(range) && range.from === num)
) {
return range.color;
} else if (advancedMode ?
((!isNumber(range.from.value) || num >= range.from.value) && (!isNumber(range.to.value) || num < range.to.value)) :
((!isNumber(range.from) || num >= range.from) && (!isNumber(range.to) || num < range.to))
) {
return range.color;
}
}
}
return this.settings.color;
}
public static constantRange(range: ColorRange): boolean {
return isNumber(range.from) && isNumber(range.to) && range.from === range.to;
}
public static constantAdvancedRange(range: AdvancedColorRange): boolean {
return isNumber(range.from.value) && isNumber(range.to.value) && range.from.value === range.to.value;
}
}
class GradientColorProcessor extends AdvancedModeColorProcessor {
private readonly minValue: number;
private readonly maxValue: number;
constructor(protected settings: ColorSettings,
protected ctx: WidgetContext) {
super(settings, ctx);
this.minValue = isDefinedAndNotNull(settings.gradient.minValue) ? settings.gradient.minValue : 0;
this.maxValue = isDefinedAndNotNull(settings.gradient.maxValue) ? settings.gradient.maxValue : 100;
}
update(value: any): void {
const progress = this.calculateProgress(+value, this.minValue, this.maxValue);
super.update(progress);
this.color = this.getGradientColor(progress,
this.advancedMode ? this.settings.gradient.gradientAdvanced : this.settings.gradient.gradient);
}
updatedAdvancedData(data: Array<DatasourceData>) {
for (const keyData of data) {
if (keyData && keyData.data && keyData.data[0]) {
const attrValue = keyData.data[0][1];
if (isFinite(attrValue)) {
for (const index of keyData.dataKey.settings.indexes) {
this.settings.gradient.gradientAdvanced[index].source.value = attrValue;
}
}
}
}
}
datasourceConfigs(): Array<ValueSourceConfig> {
const configs: Array<ValueSourceConfig> = [];
for (const gradient of this.settings.gradient.gradientAdvanced) {
configs.push(gradient.source);
}
return configs;
}
getCurrentConfig(): AdvancedColorMode {
return this.settings.gradient;
}
private calculateProgress(current: number, min: number, max: number) {
if (current < min) {
return 0;
} else if (current > max) {
return 1;
}
return (current - min) / (max - min);
}
private getGradientColor(progress: number, levelColors: Array<AdvancedGradient | string>): string {
const colorsCount = levelColors.length;
const inc = colorsCount > 1 ? (1 / (colorsCount - 1)) : 1;
const colorsRange = [];
levelColors.forEach((levelColor, i) => {
const color = typeof levelColor === 'string' ? levelColor : levelColor.color;
if (color !== null) {
const tColor = tinycolor(color);
colorsRange.push({
pct: typeof levelColor !== 'string' ?
this.calculateProgress(+levelColor.source.value, this.minValue, this.maxValue) : inc * i,
color: tColor.toRgb(),
alpha: tColor.getAlpha(),
rgbString: tColor.toRgbString()
});
}
});
if (progress === 0 || colorsRange.length === 1) {
return colorsRange[0].rgbString;
}
for (let j = 1; j < colorsRange.length; j++) {
if (progress <= colorsRange[j].pct) {
const lower = colorsRange[j - 1];
const upper = colorsRange[j];
const range = upper.pct - lower.pct;
const rangePct = (progress - lower.pct) / range;
const pctLower = 1 - rangePct;
const pctUpper = rangePct;
const color = tinycolor({
r: Math.floor(lower.color.r * pctLower + upper.color.r * pctUpper),
g: Math.floor(lower.color.g * pctLower + upper.color.g * pctUpper),
b: Math.floor(lower.color.b * pctLower + upper.color.b * pctUpper),
a: (lower.alpha + upper.alpha)/2
});
return color.toRgbString();
}
}
return colorsRange[colorsRange.length - 1].rgbString;
}
}
export type FormatTimeUnit = 'millisecond' | 'second' | 'minute' | 'hour'
| 'day' | 'month' | 'year';
export const formatTimeUnits: FormatTimeUnit[] = [
'year', 'month', 'day', 'hour', 'minute', 'second', 'millisecond'
];
export const formatTimeUnitTranslations = new Map<FormatTimeUnit, string>(
[
['year', 'date.unit-year'],
['month', 'date.unit-month'],
['day', 'date.unit-day'],
['hour', 'date.unit-hour'],
['minute', 'date.unit-minute'],
['second', 'date.unit-second'],
['millisecond', 'date.unit-millisecond']
]
);
export type AutoDateFormatSettings = {
[unit in FormatTimeUnit]?: string;
};
export interface DateFormatSettings {
format?: string;
lastUpdateAgo?: boolean;
custom?: boolean;
auto?: boolean;
hideLastUpdatePrefix?: boolean;
autoDateFormatSettings?: AutoDateFormatSettings;
}
export const simpleDateFormat = (format: string): DateFormatSettings => ({
format,
lastUpdateAgo: false,
custom: false,
auto: false
});
export const lastUpdateAgoDateFormat = (): DateFormatSettings => ({
format: null,
lastUpdateAgo: true,
custom: false,
auto: false
});
export const customDateFormat = (format: string): DateFormatSettings => ({
format,
lastUpdateAgo: false,
custom: true,
auto: false
});
export const defaultAutoDateFormatSettings: AutoDateFormatSettings = {
millisecond: 'MMM dd yyyy HH:mm:ss.SSS',
second: 'MMM dd yyyy HH:mm:ss',
minute: 'MMM dd yyyy HH:mm',
hour: 'MMM dd yyyy HH:mm',
day: 'MMM dd yyyy',
month: 'MMM yyyy',
year: 'yyyy'
};
export const autoDateFormat = (): DateFormatSettings => ({
format: null,
lastUpdateAgo: false,
custom: false,
auto: true,
autoDateFormatSettings: {}
});
export const dateFormats = ['MMM yyyy', 'MMM dd yyyy', 'MMM dd yyyy HH:mm', 'dd MMM yyyy HH:mm', 'dd MMM yyyy HH:mm:ss',
'yyyy MMM dd HH:mm', 'MM/dd/yyyy HH:mm', 'dd/MM/yyyy HH:mm', 'MMM dd yyyy HH:mm:ss', 'yyyy/MM/dd HH:mm:ss', 'yyyy-MM-dd HH:mm:ss',
'MMM dd yyyy HH:mm:ss.SSS', 'yyyy-MM-dd HH:mm:ss.SSS']
.map(f => simpleDateFormat(f)).concat([lastUpdateAgoDateFormat(), customDateFormat('EEE, MMMM dd, yyyy')]);
export const dateFormatsWithAuto = [autoDateFormat()].concat(dateFormats);
export const compareDateFormats = (df1: DateFormatSettings, df2: DateFormatSettings): boolean => {
if (df1 === df2) {
return true;
} else if (df1 && df2) {
if (df1.lastUpdateAgo && df2.lastUpdateAgo) {
return true;
} else if (df1.custom && df2.custom) {
return true;
} else if (df1.auto && df2.auto && !df1.custom && !df2.custom) {
return true;
} else if (!df1.lastUpdateAgo && !df2.lastUpdateAgo && !df1.custom && !df2.custom && !df1.auto && !df2.auto) {
return df1.format === df2.format;
}
}
return false;
};
export abstract class DateFormatProcessor {
static fromSettings($injector: Injector, settings: DateFormatSettings): DateFormatProcessor {
if (settings.lastUpdateAgo) {
return new LastUpdateAgoDateFormatProcessor($injector, settings);
} else if (settings.auto && !settings.custom) {
return new AutoDateFormatProcessor($injector, settings);
} else {
return new SimpleDateFormatProcessor($injector, settings);
}
}
formatted = ' ';
protected constructor(protected $injector: Injector,
protected settings: DateFormatSettings) {
}
abstract update(ts: string | number | Date, interval?: Interval): string;
}
export class SimpleDateFormatProcessor extends DateFormatProcessor {
private datePipe: DatePipe;
constructor(protected $injector: Injector,
protected settings: DateFormatSettings) {
super($injector, settings);
this.datePipe = $injector.get(DatePipe);
}
update(ts: string| number | Date): string {
if (ts) {
this.formatted = this.datePipe.transform(ts, this.settings.format);
} else {
this.formatted = ' ';
}
return this.formatted;
}
}
export class LastUpdateAgoDateFormatProcessor extends DateFormatProcessor {
private dateAgoPipe: DateAgoPipe;
private translate: TranslateService;
constructor(protected $injector: Injector,
protected settings: DateFormatSettings) {
super($injector, settings);
this.dateAgoPipe = $injector.get(DateAgoPipe);
this.translate = $injector.get(TranslateService);
}
update(ts: string| number | Date): string {
if (ts) {
const agoText = this.dateAgoPipe.transform(ts, {applyAgo: true, short: true, textPart: true});
if (this.settings.hideLastUpdatePrefix) {
this.formatted = agoText;
} else {
this.formatted = this.translate.instant('date.last-update-n-ago-text',
{agoText});
}
} else {
this.formatted = ' ';
}
return this.formatted;
}
}
export class AutoDateFormatProcessor extends DateFormatProcessor {
private datePipe: DatePipe;
private readonly autoDateFormatSettings: AutoDateFormatSettings;
constructor(protected $injector: Injector,
protected settings: DateFormatSettings) {
super($injector, settings);
this.datePipe = $injector.get(DatePipe);
this.autoDateFormatSettings = mergeDeep({} as AutoDateFormatSettings,
defaultAutoDateFormatSettings, this.settings.autoDateFormatSettings);
}
update(ts: string| number | Date, interval?: Interval): string {
if (ts) {
const unit = interval ? intervalToFormatTimeUnit(interval) : tsToFormatTimeUnit(ts);
const format = this.autoDateFormatSettings[unit];
if (format) {
this.formatted = this.datePipe.transform(ts, format);
} else {
this.formatted = ' ';
}
} else {
this.formatted = ' ';
}
return this.formatted;
}
}
const intervalToFormatTimeUnit = (interval: Interval): FormatTimeUnit => {
const intervalValue = IntervalMath.numberValue(interval);
if (intervalValue < SECOND) {
return 'millisecond';
} else if (intervalValue < MINUTE) {
return 'second';
} else if (intervalValue < HOUR) {
return 'minute';
} else if (intervalValue < DAY) {
return 'hour';
} else if (intervalValue < AVG_MONTH) {
return 'day';
} else if (intervalValue < YEAR) {
return 'month';
} else {
return 'year';
}
};
export const tsToFormatTimeUnit = (ts: string | number | Date): FormatTimeUnit => {
const date = moment(ts);
const M = date.month() + 1;
const d = date.date();
const h = date.hours();
const m = date.minutes();
const s = date.seconds();
const S = date.milliseconds();
const isSecond = S === 0;
const isMinute = isSecond && s === 0;
const isHour = isMinute && m === 0;
const isDay = isHour && h === 0;
const isMonth = isDay && d === 1;
const isYear = isMonth && M === 1;
if (isYear) {
return 'year';
}
else if (isMonth) {
return 'month';
}
else if (isDay) {
return 'day';
}
else if (isHour) {
return 'hour';
}
else if (isMinute) {
return 'minute';
}
else if (isSecond) {
return 'second';
}
else {
return 'millisecond';
}
};
export enum BackgroundType {
image = 'image',
color = 'color'
}
export const backgroundTypeTranslations = new Map<BackgroundType, string>(
[
[BackgroundType.image, 'widgets.background.background-type-image'],
[BackgroundType.color, 'widgets.background.background-type-color']
]
);
export interface OverlaySettings {
enabled: boolean;
color: string;
blur: number;
}
export interface BackgroundSettings {
type: BackgroundType;
imageUrl?: string;
color?: string;
overlay: OverlaySettings;
}
export const iconStyle = (size: number | string, sizeUnit: cssUnit = 'px'): ComponentStyle => {
const iconSize = typeof size === 'number' ? size + sizeUnit : size;
return {
width: iconSize,
minWidth: iconSize,
height: iconSize,
fontSize: iconSize,
lineHeight: iconSize
};
};
export const textStyle = (font?: Font, letterSpacing = 'normal'): ComponentStyle => {
const style: ComponentStyle = {
letterSpacing
};
if (font?.style) {
style.fontStyle = font.style;
}
if (font?.weight) {
style.fontWeight = font.weight;
}
if (font?.lineHeight) {
style.lineHeight = font.lineHeight;
}
if (font?.size) {
style.fontSize = (font.size + (font.sizeUnit || 'px'));
}
if (font?.family) {
style.fontFamily = font.family +
(font.family !== 'Roboto' ? ', Roboto' : '');
}
return style;
};
export const inlineTextStyle = (font?: Font, letterSpacing = 'normal'): ComponentStyle => {
const style: ComponentStyle = {
letterSpacing
};
if (font?.style) {
style['font-style'] = font.style;
}
if (font?.weight) {
style['font-weight'] = font.weight;
}
if (font?.lineHeight) {
style['line-height'] = font.lineHeight;
}
if (font?.size) {
style['font-size'] = (font.size + (font.sizeUnit || 'px'));
}
if (font?.family) {
style['font-family'] = font.family +
(font.family !== 'Roboto' ? ', Roboto' : '');
}
return style;
};
export const cssTextFromInlineStyle = (styleObj: { [key: string]: string | number }): string => Object.entries(styleObj)
.map(([key, value]) => `${key}: ${value}`)
.join('; ');
export const isFontSet = (font: Font): boolean => (!!font && !!font.style && !!font.weight && !!font.size && !!font.family);
export const isFontPartiallySet = (font: Font): boolean => (!!font && (!!font.style || !!font.weight || !!font.size || !!font.family));
export const validateAndUpdateBackgroundSettings = (background: BackgroundSettings): BackgroundSettings => {
if (background) {
if (background.type === BackgroundType.image && (background as any).imageBase64) {
background.imageUrl = (background as any).imageBase64;
}
if (background.type === 'imageUrl' as any) {
background.type = BackgroundType.image;
}
delete (background as any).imageBase64;
}
return background;
};
export const backgroundStyle = (background: BackgroundSettings, imagePipe: ImagePipe,
sanitizer: DomSanitizer, preview = false): Observable<ComponentStyle> => {
background = validateAndUpdateBackgroundSettings(background);
if (background.type === BackgroundType.color) {
return of({
background: background.color
});
} else {
const imageUrl = background.imageUrl;
if (imageUrl) {
return imagePipe.transform(imageUrl, {asString: true, ignoreLoadingImage: true, preview}).pipe(
map((transformedUrl) => ({
background: sanitizer.bypassSecurityTrustStyle(`url(${transformedUrl}) no-repeat 50% 50% / cover`)
}))
);
} else {
return of({});
}
}
};
export const overlayStyle = (overlay: OverlaySettings): ComponentStyle => (
{
display: overlay.enabled ? 'block' : 'none',
background: overlay.color,
backdropFilter: `blur(${overlay.blur}px)`
}
);
export const getDataKey = (datasources?: Datasource[], index = 0): DataKey => {
if (datasources && datasources.length) {
const dataKeys = datasources[0].dataKeys;
if (dataKeys && dataKeys.length > index) {
return dataKeys[index];
}
}
return null;
};
export const updateDataKeys = (datasources: Datasource[], dataKeys: DataKey[]): void => {
if (datasources && datasources.length) {
datasources[0].dataKeys = dataKeys;
}
};
export const getDataKeyByLabel = (datasources: Datasource[], label: string): DataKey => {
if (datasources && datasources.length) {
const dataKeys = datasources[0].dataKeys;
if (dataKeys && dataKeys.length) {
return dataKeys.find(k => k.label === label);
}
}
return null;
};
export const updateDataKeyByLabel = (datasources: Datasource[], dataKey: DataKey, label: string): void => {
if (datasources && datasources.length) {
let dataKeys = datasources[0].dataKeys;
if (!dataKeys) {
dataKeys = [];
datasources[0].dataKeys = dataKeys;
}
const existingIndex = dataKeys.findIndex(k => k.label === label || k === dataKey);
if (dataKey) {
dataKey.label = label;
if (existingIndex > -1) {
dataKeys[existingIndex] = dataKey;
} else {
dataKeys.push(dataKey);
}
} else if (existingIndex > -1) {
dataKeys.splice(existingIndex, 1);
}
}
};
export const getTargetDeviceFromDatasources = (datasources?: Datasource[]): TargetDevice => {
if (datasources && datasources.length) {
const datasource = datasources[0];
if (datasource?.type === DatasourceType.device) {
return {
type: TargetDeviceType.device,
deviceId: datasource?.deviceId
};
} else if (datasource?.type === DatasourceType.entity) {
return {
type: TargetDeviceType.entity,
entityAliasId: datasource?.entityAliasId
};
}
}
return null;
};
export const getAlarmFilterConfig = (datasources?: Datasource[]): AlarmFilterConfig => {
if (datasources && datasources.length) {
const config = datasources[0].alarmFilterConfig;
if (config) {
return config;
}
}
return { statusList: [ AlarmSearchStatus.ACTIVE ] };
};
export const setAlarmFilterConfig = (config: AlarmFilterConfig, datasources?: Datasource[]): void => {
if (datasources && datasources.length) {
datasources[0].alarmFilterConfig = config;
}
};
export const getLabel = (datasources?: Datasource[]): string => {
const dataKey = getDataKey(datasources);
if (dataKey) {
return dataKey.label;
}
return '';
};
export const setLabel = (label: string, datasources?: Datasource[]): void => {
const dataKey = getDataKey(datasources);
if (dataKey) {
dataKey.label = label;
}
};
export const getSingleTsValue = (data: Array<DatasourceData>): DataEntry => {
if (data.length) {
const dsData = data[0];
if (dsData.data.length) {
return dsData.data[0];
}
}
return null;
};
export const getSingleTsValueByDataKey = (data: Array<DatasourceData>, dataKey: DataKey): DataEntry => {
if (data.length) {
const dsData = data.find(d => d.dataKey === dataKey);
if (dsData?.data?.length) {
return dsData.data[0];
}
}
return null;
};
export const getLatestSingleTsValue = (data: Array<DatasourceData>): DataEntry => {
if (data.length) {
const dsData = data[0];
if (dsData.data.length) {
return dsData.data[dsData.data.length - 1];
}
}
return null;
};
export const createValueSubscription = (ctx: WidgetContext,
datasourceConfigs: ValueSourceConfig[],
onDataUpdated: WidgetSubscriptionCallbacks['onDataUpdated']): Observable<IWidgetSubscription> => {
let datasources: Datasource[] = [];
let index = 0;
datasourceConfigs.forEach(config => {
if (config.type !== ValueSourceType.constant) {
try {
datasources = generateDatasource(ctx, datasources, config, index);
} catch (e) {
return;
}
}
index++;
});
if (datasources.length) {
return subscribeForDatasource(ctx, datasources, onDataUpdated);
}
return EMPTY;
};
const generateDatasource = (ctx: WidgetContext,
datasources: Datasource[],
valueSource: ValueSourceConfig,
index: number): Datasource[] => {
if (valueSource.type === ValueSourceType.latestKey) {
if (ctx.datasources.length && isDefinedAndNotNull(ctx.datasources[0].aliasName)) {
datasources = configureDatasource(ctx, valueSource, ctx.datasources[0].aliasName, datasources, index, true);
} else {
datasources = configureDatasource(ctx, valueSource, '', datasources, index, true);
}
} else if (valueSource.type === ValueSourceType.entity) {
datasources = configureDatasource(ctx, valueSource, valueSource.entityAlias, datasources, index, false);
}
return datasources;
};
const configureDatasource = (ctx: WidgetContext,
valueSource: ValueSourceConfig,
entityAlias: string,
datasources: Datasource[],
index: number,
isLatest: boolean): Datasource[] => {
const indexes = [index];
const entityAliasId = ctx.aliasController.getEntityAliasId(entityAlias);
let datasource = datasources.find(d =>
entityAlias ? (d.entityAliasId === entityAliasId) : (d.deviceId === ctx.datasources[0].deviceId)
);
const dataKey: DataKey = {
type: isLatest ? valueSource.latestKeyType : valueSource.entityKeyType,
name: isLatest ? valueSource.latestKey : valueSource.entityKey,
label: isLatest ? valueSource.latestKey : valueSource.entityKey,
settings: {indexes}
};
if (datasource) {
const findDataKey = datasource.dataKeys.find(dataKeyIteration =>
dataKeyIteration.name === (isLatest ? valueSource.latestKey : valueSource.entityKey));
if (findDataKey) {
findDataKey.settings.indexes.push(index);
} else {
datasource.dataKeys.push(dataKey);
}
} else {
if (entityAlias) {
datasource = {
type: DatasourceType.entity,
name: entityAlias,
aliasName: entityAlias,
entityAliasId,
dataKeys: [dataKey]
};
} else {
datasource = {
type: DatasourceType.device,
name: ctx.datasources[0].name,
deviceName: ctx.datasources[0].name,
deviceId: ctx.datasources[0].deviceId,
dataKeys: [dataKey]
};
}
datasources.push(datasource);
}
return datasources;
};
const subscribeForDatasource = (ctx: WidgetContext,
datasource: Datasource[],
onDataUpdated: WidgetSubscriptionCallbacks['onDataUpdated']): Observable<IWidgetSubscription> => {
if (!datasource.length) {
return EMPTY;
}
const subscriptionOptions: WidgetSubscriptionOptions = {
datasources: datasource,
useDashboardTimewindow: false,
type: widgetType.latest,
callbacks: {
onDataUpdated
}
};
return ctx.subscriptionApi.createSubscription(subscriptionOptions, true);
};