`
- });
+ style="transform: translate(-10px, -10px)
+ rotate(${data.rotationAngle}deg);
+ ${style}">
`
+ }), size: [30, 30]};
} else {
this.options.icon = null;
}
@@ -549,7 +656,7 @@ export default abstract class LeafletMap {
updatedMarkers.push(m);
}
} else {
- m = this.createMarker(data.entityName, data, markersData, this.options as MarkerSettings, updateBounds, callback);
+ m = this.createMarker(data.entityName, data, markersData, this.options, updateBounds, callback);
if (m) {
createdMarkers.push(m);
}
@@ -563,7 +670,7 @@ export default abstract class LeafletMap {
}
});
this.markersData = markersData;
- if ((this.options as MarkerSettings).useClusterMarkers) {
+ if (this.options.useClusterMarkers) {
if (createdMarkers.length) {
this.markersCluster.addLayers(createdMarkers.map(marker => marker.leafletMarker));
}
@@ -577,13 +684,13 @@ export default abstract class LeafletMap {
}
dragMarker = (e, data = {} as FormattedData) => {
- if (e.type !== 'dragend') {
+ if (e === undefined) {
return;
}
- this.saveMarkerLocation({ ...data, ...this.convertToCustomFormat(e.target._latlng) }).subscribe();
+ this.saveLocation(data, this.convertToCustomFormat(e.target._latlng)).subscribe();
}
- private createMarker(key: string, data: FormattedData, dataSources: FormattedData[], settings: MarkerSettings,
+ private createMarker(key: string, data: FormattedData, dataSources: FormattedData[], settings: UnitedMapSettings,
updateBounds = true, callback?): Marker {
const newMarker = new Marker(this, this.convertPosition(data), settings, data, dataSources, this.dragMarker);
if (callback) {
@@ -591,7 +698,7 @@ export default abstract class LeafletMap {
callback(data, true);
});
}
- if (this.bounds && updateBounds && !(this.options as MarkerSettings).useClusterMarkers) {
+ if (this.bounds && updateBounds && !this.options.useClusterMarkers) {
this.fitBounds(this.bounds.extend(newMarker.leafletMarker.getLatLng()));
}
this.markers.set(key, newMarker);
@@ -728,11 +835,15 @@ export default abstract class LeafletMap {
// Polygon
+ isValidPolygonPosition(data: FormattedData): boolean {
+ return data && isDefinedAndNotNull(data[this.options.polygonKeyName]) && !isEmptyStr(data[this.options.polygonKeyName]);
+ }
+
updatePolygons(polyData: FormattedData[], updateBounds = true) {
const keys: string[] = [];
this.polygonsData = deepClone(polyData);
polyData.forEach((data: FormattedData) => {
- if (data && isDefinedAndNotNull(data[this.options.polygonKeyName]) && !isEmptyStr(data[this.options.polygonKeyName])) {
+ if (this.isValidPolygonPosition(data)) {
if (isString((data[this.options.polygonKeyName]))) {
data[this.options.polygonKeyName] = JSON.parse(data[this.options.polygonKeyName]);
}
@@ -758,18 +869,25 @@ export default abstract class LeafletMap {
}
dragPolygonVertex = (e?, data = {} as FormattedData) => {
- if (e === undefined || (e.type !== 'editable:vertex:dragend' && e.type !== 'editable:vertex:deleted')) {
+ if (e === undefined) {
return;
}
- if (this.options.provider !== MapProviders.image) {
- for (const key of Object.keys(e.layer._latlngs[0])) {
- e.layer._latlngs[0][key] = checkLngLat(e.layer._latlngs[0][key], this.southWest, this.northEast);
+ let coordinates = e.layer.getLatLngs();
+ if (coordinates.length === 1) {
+ coordinates = coordinates[0];
+ }
+ if (e.shape === 'Rectangle' && coordinates.length === 1) {
+ // @ts-ignore
+ const bounds: L.LatLngBounds = e.layer.getBounds();
+ const boundsArray = [bounds.getNorthWest(), bounds.getNorthEast(), bounds.getSouthWest(), bounds.getSouthEast()];
+ if (coordinates.every(point => boundsArray.find(boundPoint => boundPoint.equals(point)) !== undefined)) {
+ coordinates = [bounds.getNorthWest(), bounds.getSouthEast()];
}
}
- this.savePolygonLocation({ ...data, ...this.convertPolygonToCustomFormat(e.layer._latlngs) }).subscribe();
+ this.saveLocation(data, this.convertPolygonToCustomFormat(coordinates)).subscribe(() => {});
}
- createPolygon(polyData: FormattedData, dataSources: FormattedData[], settings: PolygonSettings, updateBounds = true) {
+ createPolygon(polyData: FormattedData, dataSources: FormattedData[], settings: UnitedMapSettings, updateBounds = true) {
const polygon = new Polygon(this.map, polyData, dataSources, settings, this.dragPolygonVertex);
if (updateBounds) {
const bounds = polygon.leafletPoly.getBounds();
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps/map-models.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps/map-models.ts
index d9183c1cb6..bbf3194b71 100644
--- a/ui-ngx/src/app/modules/home/components/widget/lib/maps/map-models.ts
+++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps/map-models.ts
@@ -1,5 +1,5 @@
///
-/// Copyright © 2016-2021 The Thingsboard Authors
+/// Copyright © 2016-2022 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.
@@ -17,13 +17,15 @@
import { Datasource } from '@app/shared/models/widget.models';
import { EntityType } from '@shared/models/entity-type.models';
import tinycolor from 'tinycolor2';
+import { BaseIconOptions, Icon } from 'leaflet';
export const DEFAULT_MAP_PAGE_SIZE = 16384;
export const DEFAULT_ZOOM_LEVEL = 8;
export type GenericFunction = (data: FormattedData, dsData: FormattedData[], dsIndex: number) => string;
-export type MarkerImageFunction = (data: FormattedData, dsData: FormattedData[], dsIndex: number) => string;
+export type MarkerImageFunction = (data: FormattedData, dsData: FormattedData[], dsIndex: number) => MarkerImageInfo;
export type PosFuncton = (origXPos, origYPos) => { x, y };
+export type MarkerIconReadyFunction = (icon: MarkerIconInfo) => void;
export type MapSettings = {
draggableMarker: boolean;
@@ -31,6 +33,7 @@ export type MapSettings = {
posFunction: PosFuncton;
defaultZoomLevel?: number;
disableScrollZooming?: boolean;
+ disableZoomControl?: boolean;
minZoomLevel?: number;
useClusterMarkers: boolean;
latKeyName?: string;
@@ -51,12 +54,12 @@ export type MapSettings = {
useDefaultCenterPosition?: boolean;
gmDefaultMapType?: string;
useLabelFunction: boolean;
- icon?: any;
zoomOnClick: boolean,
maxZoom: number,
showCoverageOnHover: boolean,
animate: boolean,
maxClusterRadius: number,
+ spiderfyOnMaxZoom: boolean,
chunkedLoading: boolean,
removeOutsideVisibleBounds: boolean,
useCustomProvider: boolean,
@@ -72,10 +75,22 @@ export enum MapProviders {
tencent = 'tencent-map'
}
+export type MarkerImageInfo = {
+ url: string;
+ size: number;
+ markerOffset?: [number, number];
+ tooltipOffset?: [number, number];
+};
+
+export type MarkerIconInfo = {
+ icon: Icon
;
+ size: [number, number];
+};
+
export type MarkerSettings = {
tooltipPattern?: any;
tooltipAction: { [name: string]: actionsHandler };
- icon?: any;
+ icon?: MarkerIconInfo;
showLabel?: boolean;
label: string;
labelColor: string;
@@ -90,7 +105,7 @@ export type MarkerSettings = {
autocloseTooltip: boolean;
showTooltipAction: string;
useClusterMarkers: boolean;
- currentImage?: string;
+ currentImage?: MarkerImageInfo;
useMarkerImageFunction?: boolean;
markerImages?: string[];
markerImageSize: number;
@@ -103,6 +118,8 @@ export type MarkerSettings = {
markerImageFunction?: MarkerImageFunction;
markerOffsetX: number;
markerOffsetY: number;
+ tooltipOffsetX: number;
+ tooltipOffsetY: number;
};
export interface FormattedData {
@@ -130,6 +147,11 @@ export type PolygonSettings = {
polygonStrokeWeight: number;
polygonStrokeColor: string;
polygonColor: string;
+ showPolygonLabel?: boolean;
+ polygonLabel: string;
+ polygonLabelColor: string;
+ polygonLabelText: string;
+ usePolygonLabelFunction: boolean;
showPolygonTooltip: boolean;
autocloseTooltip: boolean;
showTooltipAction: string;
@@ -138,8 +160,11 @@ export type PolygonSettings = {
usePolygonTooltipFunction: boolean;
polygonClick: { [name: string]: actionsHandler };
usePolygonColorFunction: boolean;
+ usePolygonStrokeColorFunction: boolean;
polygonTooltipFunction: GenericFunction;
polygonColorFunction?: GenericFunction;
+ polygonStrokeColorFunction?: GenericFunction;
+ polygonLabelFunction?: GenericFunction;
editablePolygon: boolean;
};
@@ -168,6 +193,15 @@ export type PolylineSettings = {
strokeWeightFunction: GenericFunction;
};
+export interface EditorSettings {
+ snappable: boolean;
+ initDragMode: boolean;
+ hideAllControlButton: boolean;
+ hideDrawControlButton: boolean;
+ hideEditControlButton: boolean;
+ hideRemoveControlButton: boolean;
+}
+
export interface HistorySelectSettings {
buttonColor: string;
}
@@ -207,13 +241,15 @@ export interface TripAnimationSettings extends PolygonSettings {
export type actionsHandler = ($event: Event, datasource: Datasource) => void;
-export type UnitedMapSettings = MapSettings & PolygonSettings & MarkerSettings & PolylineSettings & TripAnimationSettings;
+export type UnitedMapSettings = MapSettings & PolygonSettings & MarkerSettings & PolylineSettings & TripAnimationSettings & EditorSettings;
export const defaultSettings: any = {
xPosKeyName: 'xPos',
yPosKeyName: 'yPos',
markerOffsetX: 0.5,
markerOffsetY: 1,
+ tooltipOffsetX: 0,
+ tooltipOffsetY: -1,
latKeyName: 'latitude',
lngKeyName: 'longitude',
polygonKeyName: 'coordinates',
@@ -226,8 +262,10 @@ export const defaultSettings: any = {
showPolygon: false,
labelColor: '#000000',
color: '#FE7569',
+ showPolygonLabel: false,
polygonColor: '#0000ff',
polygonStrokeColor: '#fe0001',
+ polygonLabelColor: '#000000',
polygonOpacity: 0.5,
polygonStrokeOpacity: 1,
polygonStrokeWeight: 1,
@@ -243,7 +281,13 @@ export const defaultSettings: any = {
draggableMarker: false,
editablePolygon: false,
fitMapBounds: true,
- mapPageSize: DEFAULT_MAP_PAGE_SIZE
+ mapPageSize: DEFAULT_MAP_PAGE_SIZE,
+ snappable: false,
+ initDragMode: false,
+ hideAllControlButton: false,
+ hideDrawControlButton: false,
+ hideEditControlButton: false,
+ hideRemoveControlButton: false
};
export const hereProviders = [
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps/map-widget.interface.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps/map-widget.interface.ts
index 5a74247f2f..2e26bea53e 100644
--- a/ui-ngx/src/app/modules/home/components/widget/lib/maps/map-widget.interface.ts
+++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps/map-widget.interface.ts
@@ -1,5 +1,5 @@
///
-/// Copyright © 2016-2021 The Thingsboard Authors
+/// Copyright © 2016-2022 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.
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps/map-widget2.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps/map-widget2.ts
index 3ad10a0980..55f68bbb00 100644
--- a/ui-ngx/src/app/modules/home/components/widget/lib/maps/map-widget2.ts
+++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps/map-widget2.ts
@@ -1,5 +1,5 @@
///
-/// Copyright © 2016-2021 The Thingsboard Authors
+/// Copyright © 2016-2022 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.
@@ -14,42 +14,31 @@
/// limitations under the License.
///
-import {
- defaultSettings,
- FormattedData,
- hereProviders,
- MapProviders,
- UnitedMapSettings
-} from './map-models';
+import { defaultSettings, FormattedData, hereProviders, MapProviders, UnitedMapSettings } from './map-models';
import LeafletMap from './leaflet-map';
import {
commonMapSettingsSchema,
+ editorSettingSchema,
mapPolygonSchema,
- mapProviderSchema,
markerClusteringSettingsSchema,
markerClusteringSettingsSchemaLeaflet,
routeMapSettingsSchema
} from './schemes';
import { MapWidgetInterface, MapWidgetStaticInterface } from './map-widget.interface';
-import {
- addCondition,
- addGroupInfo,
- addToSchema,
- initSchema,
- mergeSchemes
-} from '@core/schema-utils';
+import { addCondition, addGroupInfo, addToSchema, initSchema, mergeSchemes } from '@core/schema-utils';
import { WidgetContext } from '@app/modules/home/models/widget-component.models';
import { getDefCenterPosition, getProviderSchema, parseFunction, parseWithTranslation } from './common-maps-utils';
import { Datasource, DatasourceData, JsonSettingsSchema, WidgetActionDescriptor } from '@shared/models/widget.models';
-import { EntityId } from '@shared/models/id/entity-id';
-import { AttributeScope, DataKeyType, LatestTelemetry } from '@shared/models/telemetry/telemetry.models';
-import { AttributeService } from '@core/http/attribute.service';
import { TranslateService } from '@ngx-translate/core';
import { UtilsService } from '@core/services/utils.service';
import { EntityDataPageLink } from '@shared/models/query/query.models';
+import { providerClass } from '@home/components/widget/lib/maps/providers';
import { isDefined } from '@core/utils';
+import L from 'leaflet';
import { forkJoin, Observable, of } from 'rxjs';
-import { providerClass } from '@home/components/widget/lib/maps/providers';
+import { AttributeService } from '@core/http/attribute.service';
+import { EntityId } from '@shared/models/id/entity-id';
+import { AttributeScope, DataKeyType, LatestTelemetry } from '@shared/models/telemetry/telemetry.models';
// @dynamic
export class MapWidgetController implements MapWidgetInterface {
@@ -81,8 +70,10 @@ export class MapWidgetController implements MapWidgetInterface {
}
parseWithTranslation.setTranslate(this.translate);
this.map = new MapClass(this.ctx, $element, this.settings);
- this.map.saveMarkerLocation = this.setMarkerLocation;
- this.map.savePolygonLocation = this.savePolygonLocation;
+ (this.ctx as any).mapInstance = this.map;
+ this.map.saveMarkerLocation = this.setMarkerLocation.bind(this);
+ this.map.savePolygonLocation = this.savePolygonLocation.bind(this);
+ this.map.saveLocation = this.saveLocation.bind(this);
this.pageLink = {
page: 0,
pageSize: this.settings.mapPageSize,
@@ -125,6 +116,8 @@ export class MapWidgetController implements MapWidgetInterface {
`model.useClusterMarkers === true && model.provider !== "image-map"`)]);
addToSchema(schema, clusteringSchema);
addGroupInfo(schema, 'Markers Clustering Settings');
+ addToSchema(schema, addCondition(editorSettingSchema, '(model.editablePolygon === true || model.draggableMarker === true)'));
+ addGroupInfo(schema, 'Editor settings');
}
return schema;
}
@@ -178,111 +171,85 @@ export class MapWidgetController implements MapWidgetInterface {
}, entityName, null, entityLabel);
}
- setMarkerLocation = (e: FormattedData, lat?: number, lng?: number) => {
- const attributeService = this.ctx.$injector.get(AttributeService);
-
- const entityId: EntityId = {
- entityType: e.$datasource.entityType,
- id: e.$datasource.entityId
+ setMarkerLocation(e: FormattedData, lat?: number, lng?: number) {
+ let markerValue;
+ if (isDefined(lat) && isDefined(lng)) {
+ const point = lat != null && lng !== null ? L.latLng(lat, lng) : null;
+ markerValue = this.map.convertToCustomFormat(point);
+ } else if (this.settings.mapProvider !== MapProviders.image) {
+ markerValue = {
+ [this.settings.latKeyName]: e[this.settings.latKeyName],
+ [this.settings.lngKeyName]: e[this.settings.lngKeyName],
};
- const attributes = [];
- const timeseries = [];
+ } else {
+ markerValue = {
+ [this.settings.xPosKeyName]: e[this.settings.xPosKeyName],
+ [this.settings.yPosKeyName]: e[this.settings.yPosKeyName],
+ };
+ }
+ return this.saveLocation(e, markerValue);
+ }
- const latProperties = [this.settings.latKeyName, this.settings.xPosKeyName];
- const lngProperties = [this.settings.lngKeyName, this.settings.yPosKeyName];
- e.$datasource.dataKeys.forEach(key => {
- let value;
- if (latProperties.includes(key.name)) {
- value = {
- key: key.name,
- value: isDefined(lat) ? lat : e[key.name]
- };
- } else if (lngProperties.includes(key.name)) {
- value = {
- key: key.name,
- value: isDefined(lng) ? lng : e[key.name]
- };
- }
- if (value) {
- if (key.type === DataKeyType.attribute) {
- attributes.push(value);
- }
- if (key.type === DataKeyType.timeseries) {
- timeseries.push(value);
- }
- }
- });
- const observables: Observable[] = [];
- if (timeseries.length) {
- observables.push(attributeService.saveEntityTimeseries(
- entityId,
- LatestTelemetry.LATEST_TELEMETRY,
- timeseries
- ));
- }
- if (attributes.length) {
- observables.push(attributeService.saveEntityAttributes(
- entityId,
- AttributeScope.SERVER_SCOPE,
- attributes
- ));
- }
- if (observables.length) {
- return forkJoin(observables);
- } else {
- return of(null);
- }
+ savePolygonLocation(e: FormattedData, coordinates?: Array) {
+ let polygonValue;
+ if (isDefined(coordinates)) {
+ polygonValue = this.map.convertToPolygonFormat(coordinates);
+ } else {
+ polygonValue = {
+ [this.settings.polygonKeyName]: e[this.settings.polygonKeyName]
+ };
+ }
+ return this.saveLocation(e, polygonValue);
}
- savePolygonLocation = (e: FormattedData, coordinates?: Array) => {
- const attributeService = this.ctx.$injector.get(AttributeService);
+ saveLocation(e: FormattedData, values: {[key: string]: any}): Observable {
+ const attributeService = this.ctx.$injector.get(AttributeService);
+ const attributes = [];
+ const timeseries = [];
- const entityId: EntityId = {
- entityType: e.$datasource.entityType,
- id: e.$datasource.entityId
- };
- const attributes = [];
- const timeseries = [];
+ const entityId: EntityId = {
+ entityType: e.$datasource.entityType,
+ id: e.$datasource.entityId
+ };
- const coordinatesProperties = this.settings.polygonKeyName;
- e.$datasource.dataKeys.forEach(key => {
- let value;
- if (coordinatesProperties === key.name) {
- value = {
- key: key.name,
- value: isDefined(coordinates) ? coordinates : e[key.name]
- };
- }
- if (value) {
- if (key.type === DataKeyType.attribute) {
- attributes.push(value);
- }
- if (key.type === DataKeyType.timeseries) {
- timeseries.push(value);
+ for (const dataKeyName of Object.keys(values)) {
+ for (const key of e.$datasource.dataKeys) {
+ if (dataKeyName === key.name) {
+ const value = {
+ key: key.name,
+ value: values[dataKeyName]
+ };
+ if (key.type === DataKeyType.attribute) {
+ attributes.push(value);
+ } else if (key.type === DataKeyType.timeseries) {
+ timeseries.push(value);
+ }
+ break;
+ }
}
}
- });
- const observables: Observable[] = [];
- if (timeseries.length) {
- observables.push(attributeService.saveEntityTimeseries(
- entityId,
- LatestTelemetry.LATEST_TELEMETRY,
- timeseries
- ));
- }
- if (attributes.length) {
- observables.push(attributeService.saveEntityAttributes(
- entityId,
- AttributeScope.SERVER_SCOPE,
- attributes
- ));
- }
- if (observables.length) {
- return forkJoin(observables);
- } else {
- return of(null);
+
+ const observables: Observable[] = [];
+ if (timeseries.length) {
+ observables.push(attributeService.saveEntityTimeseries(
+ entityId,
+ LatestTelemetry.LATEST_TELEMETRY,
+ timeseries
+ ));
+ }
+ if (attributes.length) {
+ observables.push(attributeService.saveEntityAttributes(
+ entityId,
+ AttributeScope.SERVER_SCOPE,
+ attributes
+ ));
+ }
+ if (observables.length) {
+ return forkJoin(observables);
+ } else {
+ return of(null);
+ }
}
- }
initSettings(settings: UnitedMapSettings, isEditMap?: boolean): UnitedMapSettings {
const functionParams = ['data', 'dsData', 'dsIndex'];
@@ -294,17 +261,20 @@ export class MapWidgetController implements MapWidgetInterface {
settings.mapProviderHere = hereProviders[0];
}
}
- const customOptions = {
+ const customOptions: Partial = {
provider: this.provider,
mapUrl: settings?.mapImageUrl,
labelFunction: parseFunction(settings.labelFunction, functionParams),
tooltipFunction: parseFunction(settings.tooltipFunction, functionParams),
colorFunction: parseFunction(settings.colorFunction, functionParams),
colorPointFunction: parseFunction(settings.colorPointFunction, functionParams),
+ polygonLabelFunction: parseFunction(settings.polygonLabelFunction, functionParams),
polygonColorFunction: parseFunction(settings.polygonColorFunction, functionParams),
+ polygonStrokeColorFunction: parseFunction(settings.polygonStrokeColorFunction, functionParams),
polygonTooltipFunction: parseFunction(settings.polygonTooltipFunction, functionParams),
markerImageFunction: parseFunction(settings.markerImageFunction, ['data', 'images', 'dsData', 'dsIndex']),
labelColor: this.ctx.widgetConfig.color,
+ polygonLabelColor: this.ctx.widgetConfig.color,
polygonKeyName: settings.polKeyName ? settings.polKeyName : settings.polygonKeyName,
tooltipPattern: settings.tooltipPattern ||
'${entityName}
Latitude: ${' +
@@ -330,11 +300,12 @@ export class MapWidgetController implements MapWidgetInterface {
}
resize() {
- this.map?.invalidateSize();
- this.map.onResize();
+ this.map.onResize();
+ this.map?.invalidateSize();
}
destroy() {
+ (this.ctx as any).mapInstance = null;
if (this.map) {
this.map.remove();
}
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps/maps-utils.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps/maps-utils.ts
index c76a6de48e..0482f4cec5 100644
--- a/ui-ngx/src/app/modules/home/components/widget/lib/maps/maps-utils.ts
+++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps/maps-utils.ts
@@ -1,5 +1,5 @@
///
-/// Copyright © 2016-2021 The Thingsboard Authors
+/// Copyright © 2016-2022 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.
@@ -56,3 +56,10 @@ export function bindPopupActions(popup: L.Popup, settings: MarkerSettings | Poly
}
});
}
+
+export function isCutPolygon(data): boolean {
+ if (Array.isArray(data[0]) && Array.isArray(data[0][0])) {
+ return true;
+ }
+ return false;
+}
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps/markers.scss b/ui-ngx/src/app/modules/home/components/widget/lib/maps/markers.scss
index 7abf1423c7..2d0740ea0d 100644
--- a/ui-ngx/src/app/modules/home/components/widget/lib/maps/markers.scss
+++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps/markers.scss
@@ -1,5 +1,5 @@
/**
- * Copyright © 2016-2021 The Thingsboard Authors
+ * Copyright © 2016-2022 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.
@@ -29,6 +29,19 @@
box-shadow: none;
}
-.leaflet-container{
+.tb-polygon-label {
+ border: none;
+ background: none;
+ box-shadow: none;
+ &:before {
+ content: none;
+ }
+}
+
+.leaflet-container {
background-color: white;
}
+
+.leaflet-buttons-control-button.pm-disabled {
+ pointer-events: none;
+}
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps/markers.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps/markers.ts
index cd3f19980f..1962828710 100644
--- a/ui-ngx/src/app/modules/home/components/widget/lib/maps/markers.ts
+++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps/markers.ts
@@ -1,5 +1,5 @@
///
-/// Copyright © 2016-2021 The Thingsboard Authors
+/// Copyright © 2016-2022 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.
@@ -14,36 +14,36 @@
/// limitations under the License.
///
-import L, { Icon, LeafletMouseEvent } from 'leaflet';
-import { FormattedData, MarkerSettings } from './map-models';
+import L, { LeafletMouseEvent } from 'leaflet';
import {
- bindPopupActions,
- createTooltip,
-} from './maps-utils';
-import {
- aspectCache,
- fillPattern,
- parseWithTranslation,
- processPattern,
- safeExecute
-} from './common-maps-utils';
+ FormattedData,
+ MarkerIconInfo,
+ MarkerIconReadyFunction,
+ MarkerImageInfo,
+ MarkerSettings,
+ UnitedMapSettings
+} from './map-models';
+import { bindPopupActions, createTooltip } from './maps-utils';
+import { aspectCache, fillPattern, parseWithTranslation, processPattern, safeExecute } from './common-maps-utils';
import tinycolor from 'tinycolor2';
import { isDefined, isDefinedAndNotNull } from '@core/utils';
import LeafletMap from './leaflet-map';
export class Marker {
leafletMarker: L.Marker;
+ labelOffset: L.LatLngTuple;
tooltipOffset: L.LatLngTuple;
markerOffset: L.LatLngTuple;
tooltip: L.Popup;
data: FormattedData;
dataSources: FormattedData[];
- constructor(private map: LeafletMap, private location: L.LatLng, public settings: MarkerSettings,
+ constructor(private map: LeafletMap, private location: L.LatLng, public settings: UnitedMapSettings,
data?: FormattedData, dataSources?, onDragendListener?) {
this.setDataSources(data, dataSources);
this.leafletMarker = L.marker(location, {
- draggable: settings.draggableMarker
+ pmIgnore: !settings.draggableMarker,
+ snapIgnore: !settings.snappable
});
this.markerOffset = [
@@ -51,11 +51,12 @@ export class Marker {
isDefined(settings.markerOffsetY) ? settings.markerOffsetY : 1,
];
- this.createMarkerIcon((iconInfo) => {
- this.leafletMarker.setIcon(iconInfo.icon);
- this.tooltipOffset = [0, -iconInfo.size[1] * this.markerOffset[1] + 10];
- this.updateMarkerLabel(settings);
- });
+ this.tooltipOffset = [
+ isDefined(settings.tooltipOffsetX) ? settings.tooltipOffsetX : 0,
+ isDefined(settings.tooltipOffsetY) ? settings.tooltipOffsetY : -1,
+ ];
+
+ this.updateMarkerIcon(settings);
if (settings.showTooltip) {
this.tooltip = createTooltip(this.leafletMarker, settings, data.$datasource);
@@ -64,16 +65,24 @@ export class Marker {
if (this.settings.markerClick) {
this.leafletMarker.on('click', (event: LeafletMouseEvent) => {
- for (const action in this.settings.markerClick) {
- if (typeof (this.settings.markerClick[action]) === 'function') {
- this.settings.markerClick[action](event.originalEvent, this.data.$datasource);
- }
+ for (const action in this.settings.markerClick) {
+ if (typeof (this.settings.markerClick[action]) === 'function') {
+ this.settings.markerClick[action](event.originalEvent, this.data.$datasource);
}
+ }
});
}
- if (onDragendListener) {
- this.leafletMarker.on('dragend', (e) => onDragendListener(e, this.data));
+ if (settings.draggableMarker && onDragendListener) {
+ this.leafletMarker.on('pm:dragstart', (e) => {
+ (this.leafletMarker.dragging as any)._draggable = { _moved: true };
+ (this.leafletMarker.dragging as any)._enabled = true;
+ });
+ this.leafletMarker.on('pm:dragend', (e) => {
+ onDragendListener(e, this.data);
+ delete (this.leafletMarker.dragging as any)._draggable;
+ delete (this.leafletMarker.dragging as any)._enabled;
+ });
}
}
@@ -113,7 +122,7 @@ export class Marker {
}
settings.labelText = fillPattern(this.map.markerLabelText, this.map.replaceInfoLabelMarker, this.data);
this.leafletMarker.bindTooltip(`${settings.labelText}
`,
- { className: 'tb-marker-label', permanent: true, direction: 'top', offset: this.tooltipOffset });
+ { className: 'tb-marker-label', permanent: true, direction: 'top', offset: this.labelOffset });
}
}
@@ -126,20 +135,22 @@ export class Marker {
updateMarkerIcon(settings: MarkerSettings) {
this.createMarkerIcon((iconInfo) => {
this.leafletMarker.setIcon(iconInfo.icon);
- this.tooltipOffset = [0, -iconInfo.size[1] * this.markerOffset[1] + 10];
+ const anchor = iconInfo.icon.options.iconAnchor;
+ if (anchor && Array.isArray(anchor)) {
+ this.labelOffset = [iconInfo.size[0] / 2 - anchor[0], 10 - anchor[1]];
+ } else {
+ this.labelOffset = [0, -iconInfo.size[1] * this.markerOffset[1] + 10];
+ }
this.updateMarkerLabel(settings);
});
}
- createMarkerIcon(onMarkerIconReady) {
+ private createMarkerIcon(onMarkerIconReady: MarkerIconReadyFunction) {
if (this.settings.icon) {
- onMarkerIconReady({
- size: [30, 30],
- icon: this.settings.icon,
- });
- return;
+ onMarkerIconReady(this.settings.icon);
+ return;
}
- const currentImage = this.settings.useMarkerImageFunction ?
+ const currentImage: MarkerImageInfo = this.settings.useMarkerImageFunction ?
safeExecute(this.settings.markerImageFunction,
[this.data, this.settings.markerImages, this.dataSources, this.data.dsIndex]) : this.settings.currentImage;
let currentColor = this.settings.tinyColor;
@@ -163,13 +174,21 @@ export class Marker {
width = currentImage.size * aspect;
height = currentImage.size;
}
+ let iconAnchor = currentImage.markerOffset;
+ let popupAnchor = currentImage.tooltipOffset;
+ if (!iconAnchor) {
+ iconAnchor = [width * this.markerOffset[0], height * this.markerOffset[1]];
+ }
+ if (!popupAnchor) {
+ popupAnchor = [width * this.tooltipOffset[0], height * this.tooltipOffset[1]];
+ }
const icon = L.icon({
iconUrl: currentImage.url,
iconSize: [width, height],
- iconAnchor: [width * this.markerOffset[0], height * this.markerOffset[1]],
- popupAnchor: [0, -height]
+ iconAnchor,
+ popupAnchor
});
- const iconInfo = {
+ const iconInfo: MarkerIconInfo = {
size: [width, height],
icon
};
@@ -184,8 +203,8 @@ export class Marker {
}
}
- createDefaultMarkerIcon(color: tinycolor.Instance, onMarkerIconReady) {
- let icon: { size: number[], icon: Icon };
+ createDefaultMarkerIcon(color: tinycolor.Instance, onMarkerIconReady: MarkerIconReadyFunction) {
+ let icon: MarkerIconInfo;
if (!tinycolor.equals(color, this.settings.tinyColor)) {
icon = this.createColoredMarkerIcon(color);
} else {
@@ -197,21 +216,26 @@ export class Marker {
onMarkerIconReady(icon);
}
- createColoredMarkerIcon(color: tinycolor.Instance): { size: number[], icon: Icon } {
+ createColoredMarkerIcon(color: tinycolor.Instance): MarkerIconInfo {
return {
- size: [21, 34],
- icon: L.icon({
- iconUrl: 'https://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|' + color.toHex(),
- iconSize: [21, 34],
- iconAnchor: [21 * this.markerOffset[0], 34 * this.markerOffset[1]],
- popupAnchor: [0, -34],
- shadowUrl: 'https://chart.apis.google.com/chart?chst=d_map_pin_shadow',
- shadowSize: [40, 37],
- shadowAnchor: [12, 35]
+ size: [21, 34],
+ icon: L.icon({
+ iconUrl: this.createColorIconURI(color),
+ iconSize: [21, 34],
+ iconAnchor: [21 * this.markerOffset[0], 34 * this.markerOffset[1]],
+ popupAnchor: [0, -34],
+ shadowUrl: 'assets/shadow.png',
+ shadowSize: [40, 37],
+ shadowAnchor: [12, 35]
})
};
}
+ createColorIconURI(color: tinycolor.Instance): string {
+ const svg = ``;
+ return 'data:image/svg+xml;base64,' + btoa(svg);
+ }
+
removeMarker() {
/* this.map$.subscribe(map =>
this.leafletMarker.addTo(map))*/
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps/polygon.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps/polygon.ts
index c7cca2a40b..223522bb0a 100644
--- a/ui-ngx/src/app/modules/home/components/widget/lib/maps/polygon.ts
+++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps/polygon.ts
@@ -1,5 +1,5 @@
///
-/// Copyright © 2016-2021 The Thingsboard Authors
+/// Copyright © 2016-2022 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.
@@ -15,10 +15,15 @@
///
import L, { LatLngExpression, LeafletMouseEvent } from 'leaflet';
-import { createTooltip } from './maps-utils';
-import { functionValueCalculator, parseWithTranslation, safeExecute } from './common-maps-utils';
-import 'leaflet-editable/src/Leaflet.Editable';
-import { FormattedData, PolygonSettings } from './map-models';
+import { createTooltip, isCutPolygon } from './maps-utils';
+import {
+ fillPattern,
+ functionValueCalculator,
+ parseWithTranslation,
+ processPattern,
+ safeExecute
+} from './common-maps-utils';
+import { FormattedData, PolygonSettings, UnitedMapSettings } from './map-models';
export class Polygon {
@@ -27,40 +32,48 @@ export class Polygon {
data: FormattedData;
dataSources: FormattedData[];
- constructor(public map, polyData: FormattedData, dataSources: FormattedData[], private settings: PolygonSettings, onDragendListener?) {
+ constructor(public map, data: FormattedData, dataSources: FormattedData[], private settings: UnitedMapSettings,
+ private onDragendListener?) {
this.dataSources = dataSources;
- this.data = polyData;
+ this.data = data;
const polygonColor = this.getPolygonColor(settings);
- this.leafletPoly = L.polygon(polyData[this.settings.polygonKeyName], {
+ const polygonStrokeColor = this.getPolygonStrokeColor(settings);
+ const polyData = data[this.settings.polygonKeyName];
+ const polyConstructor = isCutPolygon(polyData) || polyData.length > 2 ? L.polygon : L.rectangle;
+ this.leafletPoly = polyConstructor(polyData, {
fill: true,
fillColor: polygonColor,
- color: settings.polygonStrokeColor,
+ color: polygonStrokeColor,
weight: settings.polygonStrokeWeight,
fillOpacity: settings.polygonOpacity,
- opacity: settings.polygonStrokeOpacity
+ opacity: settings.polygonStrokeOpacity,
+ pmIgnore: !settings.editablePolygon,
+ snapIgnore: !settings.snappable
}).addTo(this.map);
- if (settings.editablePolygon) {
- this.leafletPoly.enableEdit(this.map);
- if (onDragendListener) {
- this.leafletPoly.on('editable:vertex:dragend', e => onDragendListener(e, this.data));
- this.leafletPoly.on('editable:vertex:deleted', e => onDragendListener(e, this.data));
- }
- }
+ this.updateLabel(settings);
if (settings.showPolygonTooltip) {
- this.tooltip = createTooltip(this.leafletPoly, settings, polyData.$datasource);
- this.updateTooltip(polyData);
- }
- if (settings.polygonClick) {
- this.leafletPoly.on('click', (event: LeafletMouseEvent) => {
- for (const action in this.settings.polygonClick) {
- if (typeof (this.settings.polygonClick[action]) === 'function') {
- this.settings.polygonClick[action](event.originalEvent, polyData.$datasource);
- }
- }
- });
+ this.tooltip = createTooltip(this.leafletPoly, settings, data.$datasource);
+ this.updateTooltip(data);
}
+ this.createEventListeners();
+ }
+
+ private createEventListeners() {
+ if (this.settings.editablePolygon && this.onDragendListener) {
+ this.leafletPoly.on('pm:edit', (e) => this.onDragendListener(e, this.data));
+ }
+
+ if (this.settings.polygonClick) {
+ this.leafletPoly.on('click', (event: LeafletMouseEvent) => {
+ for (const action in this.settings.polygonClick) {
+ if (typeof (this.settings.polygonClick[action]) === 'function') {
+ this.settings.polygonClick[action](event.originalEvent, this.data.$datasource);
+ }
+ }
+ });
+ }
}
updateTooltip(data: FormattedData) {
@@ -70,19 +83,54 @@ export class Polygon {
this.tooltip.setContent(parseWithTranslation.parseTemplate(pattern, data, true));
}
+ updateLabel(settings: PolygonSettings) {
+ this.leafletPoly.unbindTooltip();
+ if (settings.showPolygonLabel) {
+ if (!this.map.polygonLabelText || settings.usePolygonLabelFunction) {
+ const pattern = settings.usePolygonLabelFunction ?
+ safeExecute(settings.polygonLabelFunction, [this.data, this.dataSources, this.data.dsIndex]) : settings.polygonLabel;
+ this.map.polygonLabelText = parseWithTranslation.prepareProcessPattern(pattern, true);
+ this.map.replaceInfoLabelPolygon = processPattern(this.map.polygonLabelText, this.data);
+ }
+ settings.polygonLabelText = fillPattern(this.map.polygonLabelText, this.map.replaceInfoLabelPolygon, this.data);
+ this.leafletPoly.bindTooltip(`${settings.polygonLabelText}
`,
+ { className: 'tb-polygon-label', permanent: true, sticky: true, direction: 'center' })
+ .openTooltip(this.leafletPoly.getBounds().getCenter());
+ }
+ }
+
updatePolygon(data: FormattedData, dataSources: FormattedData[], settings: PolygonSettings) {
this.data = data;
this.dataSources = dataSources;
- if (settings.editablePolygon) {
- this.leafletPoly.disableEdit();
- }
- this.leafletPoly.setLatLngs(data[this.settings.polygonKeyName]);
- if (settings.editablePolygon) {
- this.leafletPoly.enableEdit(this.map);
+ const polyData = data[this.settings.polygonKeyName];
+ if (isCutPolygon(polyData) || polyData.length > 2) {
+ if (this.leafletPoly instanceof L.Rectangle) {
+ this.map.removeLayer(this.leafletPoly);
+ const polygonColor = this.getPolygonColor(settings);
+ const polygonStrokeColor = this.getPolygonStrokeColor(settings);
+ this.leafletPoly = L.polygon(polyData, {
+ fill: true,
+ fillColor: polygonColor,
+ color: polygonStrokeColor,
+ weight: settings.polygonStrokeWeight,
+ fillOpacity: settings.polygonOpacity,
+ opacity: settings.polygonStrokeOpacity,
+ pmIgnore: !settings.editablePolygon
+ }).addTo(this.map);
+ } else {
+ this.leafletPoly.setLatLngs(polyData);
+ }
+ } else if (polyData.length === 2) {
+ const bounds = new L.LatLngBounds(polyData);
+ // @ts-ignore
+ this.leafletPoly.setBounds(bounds);
}
if (settings.showPolygonTooltip) {
this.updateTooltip(this.data);
}
+ if (settings.showPolygonLabel) {
+ this.updateLabel(settings);
+ }
this.updatePolygonColor(settings);
}
@@ -92,10 +140,11 @@ export class Polygon {
updatePolygonColor(settings: PolygonSettings) {
const polygonColor = this.getPolygonColor(settings);
+ const polygonStrokeColor = this.getPolygonStrokeColor(settings);
const style: L.PathOptions = {
fill: true,
fillColor: polygonColor,
- color: settings.polygonStrokeColor,
+ color: polygonStrokeColor,
weight: settings.polygonStrokeWeight,
fillOpacity: settings.polygonOpacity,
opacity: settings.polygonStrokeOpacity
@@ -116,4 +165,9 @@ export class Polygon {
return functionValueCalculator(settings.usePolygonColorFunction, settings.polygonColorFunction,
[this.data, this.dataSources, this.data.dsIndex], settings.polygonColor);
}
+
+ private getPolygonStrokeColor(settings: PolygonSettings): string | null {
+ return functionValueCalculator(settings.usePolygonStrokeColorFunction, settings.polygonStrokeColorFunction,
+ [this.data, this.dataSources, this.data.dsIndex], settings.polygonStrokeColor);
+ }
}
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps/polyline.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps/polyline.ts
index be319ded3a..0c3b48d68e 100644
--- a/ui-ngx/src/app/modules/home/components/widget/lib/maps/polyline.ts
+++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps/polyline.ts
@@ -1,5 +1,5 @@
///
-/// Copyright © 2016-2021 The Thingsboard Authors
+/// Copyright © 2016-2022 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.
@@ -14,7 +14,8 @@
/// limitations under the License.
///
-import L, { PolylineDecoratorOptions } from 'leaflet';
+// @ts-ignore
+import L, { PolylineDecorator, PolylineDecoratorOptions, Symbol } from 'leaflet';
import 'leaflet-polylinedecorator';
import { FormattedData, PolylineSettings } from './map-models';
@@ -23,7 +24,7 @@ import { functionValueCalculator } from '@home/components/widget/lib/maps/common
export class Polyline {
leafletPoly: L.Polyline;
- polylineDecorator: L.PolylineDecorator;
+ polylineDecorator: PolylineDecorator;
dataSources: FormattedData[];
data: FormattedData;
@@ -36,7 +37,7 @@ export class Polyline {
).addTo(this.map);
if (settings.usePolylineDecorator) {
- this.polylineDecorator = L.polylineDecorator(this.leafletPoly, this.getDecoratorSettings(settings)).addTo(this.map);
+ this.polylineDecorator = new PolylineDecorator(this.leafletPoly, this.getDecoratorSettings(settings)).addTo(this.map);
}
}
@@ -47,7 +48,7 @@ export class Polyline {
offset: settings.decoratorOffset,
endOffset: settings.endDecoratorOffset,
repeat: settings.decoratorRepeat,
- symbol: L.Symbol[settings.decoratorSymbol]({
+ symbol: Symbol[settings.decoratorSymbol]({
pixelSize: settings.decoratorSymbolSize,
polygon: false,
pathOptions: {
@@ -78,7 +79,8 @@ export class Polyline {
opacity: functionValueCalculator(settings.useStrokeOpacityFunction, settings.strokeOpacityFunction,
[this.data, this.dataSources, this.data.dsIndex], settings.strokeOpacity),
weight: functionValueCalculator(settings.useStrokeWeightFunction, settings.strokeWeightFunction,
- [this.data, this.dataSources, this.data.dsIndex], settings.strokeWeight)
+ [this.data, this.dataSources, this.data.dsIndex], settings.strokeWeight),
+ pmIgnore: true
};
}
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps/providers/google-map.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps/providers/google-map.ts
index f3369dd46c..9ac73d2749 100644
--- a/ui-ngx/src/app/modules/home/components/widget/lib/maps/providers/google-map.ts
+++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps/providers/google-map.ts
@@ -1,5 +1,5 @@
///
-/// Copyright © 2016-2021 The Thingsboard Authors
+/// Copyright © 2016-2022 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.
@@ -38,7 +38,7 @@ export class GoogleMap extends LeafletMap {
this.loadGoogle(() => {
const map = L.map($container, {
attributionControl: false,
- editable: !!options.editablePolygon,
+ zoomControl: !this.options.disableZoomControl,
tap: L.Browser.safari && L.Browser.mobile
}).setView(options?.defaultCenterPosition, options?.defaultZoomLevel || DEFAULT_ZOOM_LEVEL);
(L.gridLayer as any).googleMutant({
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps/providers/here-map.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps/providers/here-map.ts
index e15c897c3b..bc261b5c63 100644
--- a/ui-ngx/src/app/modules/home/components/widget/lib/maps/providers/here-map.ts
+++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps/providers/here-map.ts
@@ -1,5 +1,5 @@
///
-/// Copyright © 2016-2021 The Thingsboard Authors
+/// Copyright © 2016-2022 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.
@@ -23,8 +23,8 @@ export class HEREMap extends LeafletMap {
constructor(ctx: WidgetContext, $container, options: UnitedMapSettings) {
super(ctx, $container, options);
const map = L.map($container, {
- editable: !!options.editablePolygon,
- tap: L.Browser.safari && L.Browser.mobile
+ tap: L.Browser.safari && L.Browser.mobile,
+ zoomControl: !this.options.disableZoomControl
}).setView(options?.defaultCenterPosition, options?.defaultZoomLevel || DEFAULT_ZOOM_LEVEL);
const tileLayer = (L.tileLayer as any).provider(options.mapProviderHere || 'HERE.normalDay', options.credentials);
tileLayer.addTo(map);
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps/providers/image-map.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps/providers/image-map.ts
index 272476ea9e..087b9febc8 100644
--- a/ui-ngx/src/app/modules/home/components/widget/lib/maps/providers/image-map.ts
+++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps/providers/image-map.ts
@@ -1,5 +1,5 @@
///
-/// Copyright © 2016-2021 The Thingsboard Authors
+/// Copyright © 2016-2022 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.
@@ -22,7 +22,6 @@ import { filter, map, mergeMap } from 'rxjs/operators';
import {
aspectCache,
calculateNewPointCoordinate,
- checkLngLat,
parseFunction
} from '@home/components/widget/lib/maps/common-maps-utils';
import { WidgetContext } from '@home/models/widget-component.models';
@@ -30,6 +29,7 @@ import { DataSet, DatasourceType, widgetType } from '@shared/models/widget.model
import { DataKeyType } from '@shared/models/telemetry/telemetry.models';
import { WidgetSubscriptionOptions } from '@core/api/widget-api.models';
import { isDefinedAndNotNull, isEmptyStr } from '@core/utils';
+import { EntityDataPageLink } from '@shared/models/query/query.models';
const maxZoom = 4; // ?
@@ -89,6 +89,7 @@ export class ImageMap extends LeafletMap {
let isUpdate = false;
const imageUrlSubscriptionOptions: WidgetSubscriptionOptions = {
datasources,
+ hasDataPageLink: true,
useDashboardTimewindow: false,
type: widgetType.latest,
callbacks: {
@@ -98,7 +99,15 @@ export class ImageMap extends LeafletMap {
}
}
};
- this.ctx.subscriptionApi.createSubscription(imageUrlSubscriptionOptions, true).subscribe(() => { });
+ this.ctx.subscriptionApi.createSubscription(imageUrlSubscriptionOptions, true).subscribe((subscription) => {
+ const pageLink: EntityDataPageLink = {
+ page: 0,
+ pageSize: 1,
+ textSearch: null,
+ dynamic: true
+ };
+ subscription.subscribeAllForPaginatedData(pageLink, null);
+ });
return this.imageFromAlias(result);
}
@@ -155,32 +164,32 @@ export class ImageMap extends LeafletMap {
const southWest = this.pointToLatLng(-padding, h + padding);
const northEast = this.pointToLatLng(w + padding, -padding);
const maxBounds = new L.LatLngBounds(southWest, northEast);
+ (this.map as any)._enforcingBounds = true;
this.map.setMaxBounds(maxBounds);
if (lastCenterPos) {
lastCenterPos.x *= w;
lastCenterPos.y *= h;
const center = this.pointToLatLng(lastCenterPos.x, lastCenterPos.y);
- setTimeout(() => {
- this.map.panTo(center, { animate: false });
- }, 0);
+ this.map.panTo(center, { animate: false });
}
+ (this.map as any)._enforcingBounds = false;
}
onResize(updateImage?: boolean) {
let width = this.$container.clientWidth;
if (width > 0 && this.aspect) {
- let height = width / this.aspect;
+ let height = Math.round(width / this.aspect);
const imageMapHeight = this.$container.clientHeight;
if (imageMapHeight > 0 && height > imageMapHeight) {
height = imageMapHeight;
- width = height * this.aspect;
+ width = Math.round(height * this.aspect);
}
width *= maxZoom;
const prevWidth = this.width;
const prevHeight = this.height;
if (this.width !== width || updateImage) {
this.width = width;
- this.height = width / this.aspect;
+ this.height = Math.round(width / this.aspect);
if (!this.map) {
this.initMap(updateImage);
} else {
@@ -188,7 +197,9 @@ export class ImageMap extends LeafletMap {
lastCenterPos.x /= prevWidth;
lastCenterPos.y /= prevHeight;
this.updateBounds(updateImage, lastCenterPos);
- this.map.invalidateSize(true);
+ (this.map as any)._enforcingBounds = true;
+ this.map.invalidateSize(false);
+ (this.map as any)._enforcingBounds = false;
this.updateMarkers(this.markersData);
if (this.options.draggableMarker && this.addMarkers.length) {
this.addMarkers.forEach((marker) => {
@@ -218,10 +229,10 @@ export class ImageMap extends LeafletMap {
maxZoom,
scrollWheelZoom: !this.options.disableScrollZooming,
center,
+ zoomControl: !this.options.disableZoomControl,
zoom: 1,
crs: L.CRS.Simple,
attributionControl: false,
- editable: !!this.options.editablePolygon,
tap: L.Browser.safari && L.Browser.mobile
});
this.updateBounds(updateImage);
@@ -259,11 +270,17 @@ export class ImageMap extends LeafletMap {
return L.CRS.Simple.pointToLatLng({ x, y } as L.PointExpression, maxZoom - 1);
}
- latLngToPoint(latLng: LatLngLiteral) {
+ latLngToPoint(latLng: LatLngLiteral): L.Point {
return L.CRS.Simple.latLngToPoint(latLng, maxZoom - 1);
}
- convertToCustomFormat(position: L.LatLng, offset = 0, width = this.width, height = this.height): object {
+ convertToCustomFormat(position: L.LatLng, offset = 0, width = this.width, height = this.height): {[key: string]: any} {
+ if (!position) {
+ return {
+ [this.options.xPosKeyName]: null,
+ [this.options.yPosKeyName]: null
+ };
+ }
const point = this.latLngToPoint(position);
const customX = calculateNewPointCoordinate(point.x, width);
const customY = calculateNewPointCoordinate(point.y, height);
@@ -279,13 +296,9 @@ export class ImageMap extends LeafletMap {
point.y = height;
}
- const customLatLng = checkLngLat(this.pointToLatLng(point.x, point.y), this.southWest, this.northEast, offset);
-
return {
[this.options.xPosKeyName]: customX,
- [this.options.yPosKeyName]: customY,
- [this.options.latKeyName]: customLatLng.lat,
- [this.options.lngKeyName]: customLatLng.lng
+ [this.options.yPosKeyName]: customY
};
}
@@ -304,9 +317,10 @@ export class ImageMap extends LeafletMap {
}
}
- convertPolygonToCustomFormat(expression: any[][]): object {
+ convertPolygonToCustomFormat(expression: any[][]): {[key: string]: any} {
+ const coordinate = expression ? this.convertToPolygonFormat(expression) : null;
return {
- [this.options.polygonKeyName] : this.convertToPolygonFormat(expression)
+ [this.options.polygonKeyName]: coordinate
};
}
}
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps/providers/index.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps/providers/index.ts
index 50c0709fb3..e0f7fc37db 100644
--- a/ui-ngx/src/app/modules/home/components/widget/lib/maps/providers/index.ts
+++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps/providers/index.ts
@@ -1,5 +1,5 @@
///
-/// Copyright © 2016-2021 The Thingsboard Authors
+/// Copyright © 2016-2022 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.
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps/providers/openstreet-map.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps/providers/openstreet-map.ts
index 61312aab23..1a27f26931 100644
--- a/ui-ngx/src/app/modules/home/components/widget/lib/maps/providers/openstreet-map.ts
+++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps/providers/openstreet-map.ts
@@ -1,5 +1,5 @@
///
-/// Copyright © 2016-2021 The Thingsboard Authors
+/// Copyright © 2016-2022 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.
@@ -23,7 +23,7 @@ export class OpenStreetMap extends LeafletMap {
constructor(ctx: WidgetContext, $container, options: UnitedMapSettings) {
super(ctx, $container, options);
const map = L.map($container, {
- editable: !!options.editablePolygon,
+ zoomControl: !this.options.disableZoomControl,
tap: L.Browser.safari && L.Browser.mobile
}).setView(options?.defaultCenterPosition, options?.defaultZoomLevel || DEFAULT_ZOOM_LEVEL);
let tileLayer;
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps/providers/tencent-map.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps/providers/tencent-map.ts
index bd34e24331..fb53f15b3e 100644
--- a/ui-ngx/src/app/modules/home/components/widget/lib/maps/providers/tencent-map.ts
+++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps/providers/tencent-map.ts
@@ -1,5 +1,5 @@
///
-/// Copyright © 2016-2021 The Thingsboard Authors
+/// Copyright © 2016-2022 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.
@@ -25,7 +25,7 @@ export class TencentMap extends LeafletMap {
super(ctx, $container, options);
const txUrl = 'http://rt{s}.map.gtimg.com/realtimerender?z={z}&x={x}&y={y}&type=vector&style=0';
const map = L.map($container, {
- editable: !!options.editablePolygon,
+ zoomControl: !this.options.disableZoomControl,
tap: L.Browser.safari && L.Browser.mobile
}).setView(options?.defaultCenterPosition, options?.defaultZoomLevel || DEFAULT_ZOOM_LEVEL);
const txLayer = L.tileLayer(txUrl, {
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps/schemes.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps/schemes.ts
index 4c7e6e61fa..6f972e9d3f 100644
--- a/ui-ngx/src/app/modules/home/components/widget/lib/maps/schemes.ts
+++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps/schemes.ts
@@ -1,5 +1,5 @@
///
-/// Copyright © 2016-2021 The Thingsboard Authors
+/// Copyright © 2016-2022 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.
@@ -269,6 +269,11 @@ export const commonMapSettingsSchema =
type: 'boolean',
default: false
},
+ disableZoomControl: {
+ title: 'Disable zoom control buttons',
+ type: 'boolean',
+ default: false
+ },
latKeyName: {
title: 'Latitude key name',
type: 'string',
@@ -343,15 +348,25 @@ export const commonMapSettingsSchema =
default: 'return {x: origXPos, y: origYPos};'
},
markerOffsetX: {
- title: 'Marker X offset relative to position',
+ title: 'Marker X offset relative to position multiplied by marker width',
type: 'number',
default: 0.5
},
markerOffsetY: {
- title: 'Marker Y offset relative to position',
+ title: 'Marker Y offset relative to position multiplied by marker height',
type: 'number',
default: 1
},
+ tooltipOffsetX: {
+ title: 'Tooltip X offset relative to marker anchor multiplied by marker width',
+ type: 'number',
+ default: 0
+ },
+ tooltipOffsetY: {
+ title: 'Tooltip Y offset relative to marker anchor multiplied by marker height',
+ type: 'number',
+ default: -1
+ },
color: {
title: 'Color',
type: 'string'
@@ -414,6 +429,7 @@ export const commonMapSettingsSchema =
'mapPageSize',
'draggableMarker',
'disableScrollZooming',
+ 'disableZoomControl',
{
key: 'latKeyName',
condition: 'model.provider !== "image-map"'
@@ -482,13 +498,15 @@ export const commonMapSettingsSchema =
condition: 'model.showTooltip === true && model.useTooltipFunction === true'
},
{
- key: 'markerOffsetX',
- condition: 'model.provider === "image-map"'
+ key: 'tooltipOffsetX',
+ condition: 'model.showTooltip === true'
},
{
- key: 'markerOffsetY',
- condition: 'model.provider === "image-map"'
+ key: 'tooltipOffsetY',
+ condition: 'model.showTooltip === true'
},
+ 'markerOffsetX',
+ 'markerOffsetY',
{
key: 'posFunction',
type: 'javascript',
@@ -556,6 +574,25 @@ export const mapPolygonSchema =
type: 'boolean',
default: false
},
+ showPolygonLabel: {
+ title: 'Show polygon label',
+ type: 'boolean',
+ default: false
+ },
+ polygonLabel: {
+ title: 'Polygon label (pattern examples: \'${entityName}\', \'${entityName}: (Text ${keyName} units.)\' )',
+ type: 'string',
+ default: '${entityName}'
+ },
+ usePolygonLabelFunction: {
+ title: 'Use polygon label function',
+ type: 'boolean',
+ default: false
+ },
+ polygonLabelFunction: {
+ title: 'Polygon label function: f(data, dsData, dsIndex)',
+ type: 'string'
+ },
polygonColor: {
title: 'Polygon color',
type: 'string'
@@ -607,6 +644,15 @@ export const mapPolygonSchema =
title: 'Polygon Color function: f(data, dsData, dsIndex)',
type: 'string'
},
+ usePolygonStrokeColorFunction: {
+ title: 'Use polygon stroke color function',
+ type: 'boolean',
+ default: false
+ },
+ polygonStrokeColorFunction: {
+ title: 'Polygon Stroke Color function: f(data, dsData, dsIndex)',
+ type: 'string'
+ }
},
required: []
},
@@ -614,6 +660,21 @@ export const mapPolygonSchema =
'showPolygon',
'polygonKeyName',
'editablePolygon',
+ 'showPolygonLabel',
+ {
+ key: 'usePolygonLabelFunction',
+ condition: 'model.showPolygonLabel === true'
+ },
+ {
+ key: 'polygonLabel',
+ condition: 'model.showPolygonLabel === true && model.usePolygonLabelFunction !== true'
+ },
+ {
+ key: 'polygonLabelFunction',
+ type: 'javascript',
+ helpId: 'widget/lib/map/label_fn',
+ condition: 'model.showPolygonLabel === true && model.usePolygonLabelFunction === true'
+ },
{
key: 'polygonColor',
type: 'color'
@@ -630,6 +691,13 @@ export const mapPolygonSchema =
key: 'polygonStrokeColor',
type: 'color'
},
+ 'usePolygonStrokeColorFunction',
+ {
+ key: 'polygonStrokeColorFunction',
+ helpId: 'widget/lib/map/polygon_color_fn',
+ type: 'javascript',
+ condition: 'model.usePolygonStrokeColorFunction === true'
+ },
'polygonStrokeOpacity',
'polygonStrokeWeight',
'showPolygonTooltip',
@@ -728,6 +796,11 @@ export const markerClusteringSettingsSchemaLeaflet =
type: 'number',
default: 80
},
+ spiderfyOnMaxZoom: {
+ title: 'Spiderfy at the max zoom level (to see all cluster markers)',
+ type: 'boolean',
+ default: false
+ },
chunkedLoading: {
title: 'Use chunks for adding markers so that the page does not freeze',
type: 'boolean',
@@ -747,6 +820,7 @@ export const markerClusteringSettingsSchemaLeaflet =
'showCoverageOnHover',
'animate',
'maxClusterRadius',
+ 'spiderfyOnMaxZoom',
'chunkedLoading',
'removeOutsideVisibleBounds'
]
@@ -1243,3 +1317,61 @@ export const providerSets: { [key: string]: IProvider } = {
name: 'image-map'
}
};
+
+export const editorSettingSchema =
+ {
+ schema: {
+ title: 'Editor settings',
+ type: 'object',
+ properties: {
+ snappable: {
+ title: 'Enable snapping to other vertices for precision drawing',
+ type: 'boolean',
+ default: false
+ },
+ initDragMode: {
+ title: 'Initialize map in draggable mode',
+ type: 'boolean',
+ default: false
+ },
+ hideAllControlButton: {
+ title: 'Hide all edit control buttons',
+ type: 'boolean',
+ default: false
+ },
+ hideDrawControlButton: {
+ title: 'Hide draw buttons',
+ type: 'boolean',
+ default: false
+ },
+ hideEditControlButton: {
+ title: 'Hide edit buttons',
+ type: 'boolean',
+ default: false
+ },
+ hideRemoveControlButton: {
+ title: 'Hide remove button',
+ type: 'boolean',
+ default: false
+ },
+ },
+ required: []
+ },
+ form: [
+ 'snappable',
+ 'initDragMode',
+ 'hideAllControlButton',
+ {
+ key: 'hideDrawControlButton',
+ condition: 'model.hideAllControlButton == false'
+ },
+ {
+ key: 'hideEditControlButton',
+ condition: 'model.hideAllControlButton == false'
+ },
+ {
+ key: 'hideRemoveControlButton',
+ condition: 'model.hideAllControlButton == false'
+ }
+ ]
+ };
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/markdown-widget.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/markdown-widget.component.html
index 46069c15f0..2820a8bade 100644
--- a/ui-ngx/src/app/modules/home/components/widget/lib/markdown-widget.component.html
+++ b/ui-ngx/src/app/modules/home/components/widget/lib/markdown-widget.component.html
@@ -1,6 +1,6 @@
-
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/markdown-widget.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/markdown-widget.component.ts
index fd0197996e..a4d93b98f8 100644
--- a/ui-ngx/src/app/modules/home/components/widget/lib/markdown-widget.component.ts
+++ b/ui-ngx/src/app/modules/home/components/widget/lib/markdown-widget.component.ts
@@ -1,5 +1,5 @@
///
-/// Copyright © 2016-2021 The Thingsboard Authors
+/// Copyright © 2016-2022 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.
@@ -14,7 +14,7 @@
/// limitations under the License.
///
-import { ChangeDetectorRef, Component, HostBinding, Input, OnInit } from '@angular/core';
+import { ChangeDetectorRef, Component, HostBinding, Inject, Input, OnInit, Type } from '@angular/core';
import { PageComponent } from '@shared/components/page.component';
import { WidgetContext } from '@home/models/widget-component.models';
import { Store } from '@ngrx/store';
@@ -32,6 +32,8 @@ import { FormattedData } from '@home/components/widget/lib/maps/map-models';
import { hashCode, isNotEmptyStr } from '@core/utils';
import cssjs from '@core/css/css';
import { UtilsService } from '@core/services/utils.service';
+import { HOME_COMPONENTS_MODULE_TOKEN } from '@home/components/tokens';
+import { EntityDataPageLink } from '@shared/models/query/query.models';
interface MarkdownWidgetSettings {
markdownTextPattern: string;
@@ -62,6 +64,7 @@ export class MarkdownWidgetComponent extends PageComponent implements OnInit {
constructor(protected store: Store,
private utils: UtilsService,
+ @Inject(HOME_COMPONENTS_MODULE_TOKEN) public homeComponentsModule: Type,
private cd: ChangeDetectorRef) {
super(store);
}
@@ -79,6 +82,17 @@ export class MarkdownWidgetComponent extends PageComponent implements OnInit {
cssParser.cssPreviewNamespace = this.markdownClass;
cssParser.createStyleElement(this.markdownClass, cssString);
}
+ const pageLink: EntityDataPageLink = {
+ page: 0,
+ pageSize: 16384,
+ textSearch: null,
+ dynamic: true
+ };
+ if (this.ctx.widgetConfig.datasources.length) {
+ this.ctx.defaultSubscription.subscribeAllForPaginatedData(pageLink, null);
+ } else {
+ this.onDataUpdated();
+ }
}
public onDataUpdated() {
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/multiple-input-widget.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/multiple-input-widget.component.html
index ce0bdc4acd..550f7cde49 100644
--- a/ui-ngx/src/app/modules/home/components/widget/lib/multiple-input-widget.component.html
+++ b/ui-ngx/src/app/modules/home/components/widget/lib/multiple-input-widget.component.html
@@ -1,6 +1,6 @@
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-add-dialog.component.scss b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-add-dialog.component.scss
new file mode 100644
index 0000000000..4958d4efa8
--- /dev/null
+++ b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-add-dialog.component.scss
@@ -0,0 +1,30 @@
+/**
+ * Copyright © 2016-2022 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.
+ */
+:host ::ng-deep {
+ .add-dialog {
+
+ .params-json-editor,
+ .additional-json-editor {
+ .tb-json-object-panel {
+ margin: 0 0 16px;
+ }
+
+ .mat-expansion-panel-body {
+ padding-bottom: 0 !important;
+ }
+ }
+ }
+}
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-add-dialog.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-add-dialog.component.ts
new file mode 100644
index 0000000000..6e81d98ce7
--- /dev/null
+++ b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-add-dialog.component.ts
@@ -0,0 +1,75 @@
+///
+/// Copyright © 2016-2022 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 { Component, OnInit } from '@angular/core';
+import { DialogComponent } from '@shared/components/dialog.component';
+import { Store } from '@ngrx/store';
+import { AppState } from '@core/core.state';
+import { Router } from '@angular/router';
+import { MatDialogRef } from '@angular/material/dialog';
+import { FormBuilder, FormGroup, Validators } from '@angular/forms';
+import { RequestData } from '@shared/models/rpc.models';
+import { TranslateService } from '@ngx-translate/core';
+
+@Component({
+ selector: 'tb-persistent-add-dialog',
+ templateUrl: './persistent-add-dialog.component.html',
+ styleUrls: ['./persistent-add-dialog.component.scss']
+})
+
+export class PersistentAddDialogComponent extends DialogComponent implements OnInit {
+
+ public persistentFormGroup: FormGroup;
+ public rpcMessageTypeText: string;
+
+ private requestData: RequestData = null;
+
+ constructor(protected store: Store,
+ protected router: Router,
+ public dialogRef: MatDialogRef,
+ private fb: FormBuilder,
+ private translate: TranslateService) {
+ super(store, router, dialogRef);
+
+ this.persistentFormGroup = this.fb.group(
+ {
+ method: ['', [Validators.required, Validators.pattern(/^\S+$/)]],
+ oneWayElseTwoWay: [false],
+ retries: [null, [Validators.pattern(/^-?[0-9]+$/), Validators.min(0)]],
+ params: [null],
+ additionalInfo: [null]
+ }
+ );
+ }
+
+ save() {
+ this.requestData = this.persistentFormGroup.value;
+ this.close();
+ }
+
+ ngOnInit(): void {
+ this.rpcMessageTypeText = this.translate.instant('widgets.persistent-table.message-types.false');
+ this.persistentFormGroup.get('oneWayElseTwoWay').valueChanges.subscribe(
+ () => {
+ this.rpcMessageTypeText = this.translate.instant(`widgets.persistent-table.message-types.${this.persistentFormGroup.get('oneWayElseTwoWay').value}`);
+ }
+ );
+ }
+
+ close(): void {
+ this.dialogRef.close(this.requestData);
+ }
+}
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-details-dialog.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-details-dialog.component.html
new file mode 100644
index 0000000000..b9e57b4bbd
--- /dev/null
+++ b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-details-dialog.component.html
@@ -0,0 +1,118 @@
+
+
diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/device/credentials/lwm2m/RPKClientCredentials.java b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-details-dialog.component.scss
similarity index 61%
rename from common/data/src/main/java/org/thingsboard/server/common/data/device/credentials/lwm2m/RPKClientCredentials.java
rename to ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-details-dialog.component.scss
index 4ebe2de71a..9025d6199e 100644
--- a/common/data/src/main/java/org/thingsboard/server/common/data/device/credentials/lwm2m/RPKClientCredentials.java
+++ b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-details-dialog.component.scss
@@ -1,5 +1,5 @@
/**
- * Copyright © 2016-2021 The Thingsboard Authors
+ * Copyright © 2016-2022 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.
@@ -13,12 +13,22 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.thingsboard.server.common.data.device.credentials.lwm2m;
-
-public class RPKClientCredentials extends AbstractLwM2MClientCredentialsWithKey {
+:host ::ng-deep {
+ .rpc-dialog {
+ .mat-expansion-panel-body {
+ padding-bottom: 0 !important;
+ }
- @Override
- public LwM2MSecurityMode getSecurityConfigClientMode() {
- return LwM2MSecurityMode.RPK;
+ .tb-json-object-panel {
+ margin: 0 0 16px 0;
}
+ }
+
+ .tb-audit-log-response-data {
+ width: 100%;
+ min-width: 400px;
+ height: 100%;
+ min-height: 100px;
+ border: 1px solid #c0c0c0;
+ }
}
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-details-dialog.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-details-dialog.component.ts
new file mode 100644
index 0000000000..a072ea312b
--- /dev/null
+++ b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-details-dialog.component.ts
@@ -0,0 +1,126 @@
+///
+/// Copyright © 2016-2022 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 { Component, ElementRef, Inject, OnInit, ViewChild } from '@angular/core';
+import { DialogComponent } from '@shared/components/dialog.component';
+import { Store } from '@ngrx/store';
+import { AppState } from '@core/core.state';
+import { Router } from '@angular/router';
+import { DatePipe } from '@angular/common';
+import { TranslateService } from '@ngx-translate/core';
+import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
+import { FormBuilder, FormGroup } from '@angular/forms';
+import { DeviceService } from '@core/http/device.service';
+import { PersistentRpc, RpcStatus, rpcStatusColors, rpcStatusTranslation } from '@shared/models/rpc.models';
+import { NULL_UUID } from '@shared/models/id/has-uuid';
+import { DialogService } from '@core/services/dialog.service';
+
+export interface PersistentDetailsDialogData {
+ persistentRequest: PersistentRpc;
+ allowDelete: boolean;
+}
+
+@Component({
+ selector: 'tb-persistent-details-dialog',
+ templateUrl: './persistent-details-dialog.component.html',
+ styleUrls: ['./persistent-details-dialog.component.scss']
+})
+
+export class PersistentDetailsDialogComponent extends DialogComponent implements OnInit {
+
+ @ViewChild('responseDataEditor', {static: true})
+ responseDataEditorElmRef: ElementRef;
+
+ public persistentFormGroup: FormGroup;
+ public rpcStatusColorsMap = rpcStatusColors;
+ public rpcStatus = RpcStatus;
+ public allowDelete: boolean;
+
+ private persistentUpdated = false;
+ private responseData: string;
+
+ constructor(protected store: Store,
+ protected router: Router,
+ private datePipe: DatePipe,
+ private translate: TranslateService,
+ @Inject(MAT_DIALOG_DATA) public data: PersistentDetailsDialogData,
+ public dialogRef: MatDialogRef,
+ private dialogService: DialogService,
+ private deviceService: DeviceService,
+ private fb: FormBuilder) {
+ super(store, router, dialogRef);
+
+ this.allowDelete = data.allowDelete;
+
+ this.persistentFormGroup = this.fb.group(
+ {
+ rpcId: [''],
+ createdTime: [''],
+ expirationTime: [''],
+ messageType: [''],
+ status: [''],
+ method: [''],
+ params: [''],
+ retries: [''],
+ response: [''],
+ additionalInfo: ['']
+ }
+ );
+ this.loadPersistentFields(data.persistentRequest);
+ this.responseData = JSON.stringify(data.persistentRequest.response, null, 2);
+ }
+
+ loadPersistentFields(request: PersistentRpc) {
+ this.persistentFormGroup.patchValue({
+ rpcId: this.translate.instant('widgets.persistent-table.details-title') + request.id.id,
+ createdTime: this.datePipe.transform(request.createdTime, 'yyyy-MM-dd HH:mm:ss'),
+ expirationTime: this.datePipe.transform(request.expirationTime, 'yyyy-MM-dd HH:mm:ss'),
+ messageType: this.translate.instant('widgets.persistent-table.message-types.' + request.request.oneway),
+ status: this.translate.instant(rpcStatusTranslation.get(request.status)),
+ method: request.request.body.method,
+ retries: request.request.retries || null,
+ response: request.response || null,
+ params: JSON.parse(request.request.body.params) || null,
+ additionalInfo: request.additionalInfo || null
+ }, {emitEvent: false});
+ }
+
+ ngOnInit(): void {
+ }
+
+ close(): void {
+ this.dialogRef.close(this.persistentUpdated);
+ }
+
+ deleteRpcRequest() {
+ const persistentRpc = this.data.persistentRequest;
+ if (persistentRpc && persistentRpc.id && persistentRpc.id.id !== NULL_UUID) {
+ this.dialogService.confirm(
+ this.translate.instant('widgets.persistent-table.delete-request-title'),
+ this.translate.instant('widgets.persistent-table.delete-request-text'),
+ this.translate.instant('action.no'),
+ this.translate.instant('action.yes')
+ ).subscribe((res) => {
+ if (res) {
+ this.deviceService.deletePersistedRpc(persistentRpc.id.id).subscribe(() => {
+ this.persistentUpdated = true;
+ this.close();
+ });
+ }
+ });
+ }
+ }
+}
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-filter-panel.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-filter-panel.component.html
new file mode 100644
index 0000000000..b3bb295ed2
--- /dev/null
+++ b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-filter-panel.component.html
@@ -0,0 +1,44 @@
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-filter-panel.component.scss b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-filter-panel.component.scss
new file mode 100644
index 0000000000..45ba061843
--- /dev/null
+++ b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-filter-panel.component.scss
@@ -0,0 +1,36 @@
+/**
+ * Copyright © 2016-2022 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.
+ */
+:host {
+ width: 100%;
+ height: 100%;
+ min-width: 300px;
+ overflow: hidden;
+ background: #fff;
+ border-radius: 4px;
+ box-shadow:
+ 0 7px 8px -4px rgba(0, 0, 0, .2),
+ 0 13px 19px 2px rgba(0, 0, 0, .14),
+ 0 5px 24px 4px rgba(0, 0, 0, .12);
+
+ .mat-content {
+ overflow: hidden;
+ background-color: #fff;
+ }
+
+ .mat-padding {
+ padding: 16px;
+ }
+}
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-filter-panel.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-filter-panel.component.ts
new file mode 100644
index 0000000000..e3d46dfca3
--- /dev/null
+++ b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-filter-panel.component.ts
@@ -0,0 +1,67 @@
+///
+/// Copyright © 2016-2022 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 { Component, Inject, InjectionToken } from '@angular/core';
+import { FormBuilder, FormGroup } from '@angular/forms';
+import { OverlayRef } from '@angular/cdk/overlay';
+import { RpcStatus, rpcStatusTranslation } from '@shared/models/rpc.models';
+import { TranslateService } from '@ngx-translate/core';
+
+export const PERSISTENT_FILTER_PANEL_DATA = new InjectionToken('AlarmFilterPanelData');
+
+export interface PersistentFilterPanelData {
+ rpcStatus: RpcStatus;
+}
+
+@Component({
+ selector: 'tb-persistent-filter-panel',
+ templateUrl: './persistent-filter-panel.component.html',
+ styleUrls: ['./persistent-filter-panel.component.scss']
+})
+export class PersistentFilterPanelComponent {
+
+ public persistentFilterFormGroup: FormGroup;
+ public result: PersistentFilterPanelData;
+ public rpcSearchStatusTranslationMap = rpcStatusTranslation;
+ public rpcSearchPlaceholder: string;
+
+ public persistentSearchStatuses = Object.keys(RpcStatus);
+
+ constructor(@Inject(PERSISTENT_FILTER_PANEL_DATA)
+ public data: PersistentFilterPanelData,
+ public overlayRef: OverlayRef,
+ private fb: FormBuilder,
+ private translate: TranslateService) {
+ this.persistentFilterFormGroup = this.fb.group(
+ {
+ rpcStatus: this.data.rpcStatus
+ }
+ );
+ this.rpcSearchPlaceholder = this.translate.instant('widgets.persistent-table.any-status');
+ }
+
+ update() {
+ this.result = {
+ rpcStatus: this.persistentFilterFormGroup.get('rpcStatus').value
+ };
+ this.overlayRef.dispose();
+ }
+
+ cancel() {
+ this.overlayRef.dispose();
+ }
+}
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-table.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-table.component.html
new file mode 100644
index 0000000000..7614d7e0e6
--- /dev/null
+++ b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-table.component.html
@@ -0,0 +1,126 @@
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-table.component.scss b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-table.component.scss
new file mode 100644
index 0000000000..842d53d143
--- /dev/null
+++ b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-table.component.scss
@@ -0,0 +1,53 @@
+/**
+ * Copyright © 2016-2022 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.
+ */
+:host {
+ width: 100%;
+ height: 100%;
+ display: block;
+ .tb-table-widget {
+ .table-container {
+ position: relative;
+ }
+
+ .mat-table {
+ .mat-row {
+ &.invisible {
+ visibility: hidden;
+ }
+ }
+ }
+
+ span.no-data-found {
+ position: absolute;
+ top: 60px;
+ bottom: 0;
+ left: 0;
+ right: 0;
+ }
+
+ .column-id {
+ min-width: 250px;
+ max-width: 250px;
+ width: 250px;
+ }
+
+ .column-time {
+ min-width: 120px;
+ max-width: 120px;
+ width: 120px;
+ }
+ }
+}
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-table.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-table.component.ts
new file mode 100644
index 0000000000..5beef7ea8c
--- /dev/null
+++ b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-table.component.ts
@@ -0,0 +1,582 @@
+///
+/// Copyright © 2016-2022 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 {
+ ChangeDetectorRef,
+ Component,
+ ElementRef,
+ Injector,
+ Input,
+ OnInit,
+ StaticProvider,
+ ViewChild,
+ ViewContainerRef
+} from '@angular/core';
+import { PageComponent } from '@shared/components/page.component';
+import { Store } from '@ngrx/store';
+import { AppState } from '@core/core.state';
+import { WidgetContext } from '@home/models/widget-component.models';
+import { WidgetConfig } from '@shared/models/widget.models';
+import { IWidgetSubscription } from '@core/api/widget-api.models';
+import { BehaviorSubject, merge, Observable, of, ReplaySubject, Subject, throwError } from 'rxjs';
+import { catchError, map, tap } from 'rxjs/operators';
+import {
+ constructTableCssString,
+ noDataMessage,
+ TableCellButtonActionDescriptor,
+ TableWidgetSettings
+} from '@home/components/widget/lib/table-widget.models';
+import cssjs from '@core/css/css';
+import { UtilsService } from '@core/services/utils.service';
+import { TranslateService } from '@ngx-translate/core';
+import { hashCode, isDefined, isNumber } from '@core/utils';
+import { CollectionViewer, DataSource } from '@angular/cdk/collections';
+import { emptyPageData, PageData } from '@shared/models/page/page-data';
+import {
+ PersistentRpc,
+ PersistentRpcData,
+ RequestData,
+ RpcStatus,
+ rpcStatusColors,
+ rpcStatusTranslation
+} from '@shared/models/rpc.models';
+import { PageLink } from '@shared/models/page/page-link';
+import { Direction, SortOrder, sortOrderFromString } from '@shared/models/page/sort-order';
+import { MatPaginator } from '@angular/material/paginator';
+import { MatSort } from '@angular/material/sort';
+import { NULL_UUID } from '@shared/models/id/has-uuid';
+import { DialogService } from '@core/services/dialog.service';
+import { DeviceService } from '@core/http/device.service';
+import { MatDialog } from '@angular/material/dialog';
+import {
+ PersistentDetailsDialogComponent,
+ PersistentDetailsDialogData
+} from '@home/components/widget/lib/rpc/persistent-details-dialog.component';
+import { ConnectedPosition, Overlay, OverlayConfig, OverlayRef } from '@angular/cdk/overlay';
+import { ComponentPortal } from '@angular/cdk/portal';
+import {
+ PERSISTENT_FILTER_PANEL_DATA,
+ PersistentFilterPanelComponent,
+ PersistentFilterPanelData
+} from '@home/components/widget/lib/rpc/persistent-filter-panel.component';
+import { PersistentAddDialogComponent } from '@home/components/widget/lib/rpc/persistent-add-dialog.component';
+import { ResizeObserver } from '@juggle/resize-observer';
+import { hidePageSizePixelValue } from '@shared/models/constants';
+import { HttpErrorResponse } from '@angular/common/http';
+
+interface PersistentTableWidgetSettings extends TableWidgetSettings {
+ defaultSortOrder: string;
+ defaultPageSize: number;
+ displayPagination: boolean;
+ enableStickyAction: boolean;
+ enableStickyHeader: boolean;
+ enableFilter: boolean;
+ displayColumns: string[];
+ displayDetails: boolean;
+ allowDelete: boolean;
+ allowSendRequest: boolean;
+}
+
+interface PersistentTableWidgetActionDescriptor extends TableCellButtonActionDescriptor {
+ details?: boolean;
+ delete?: boolean;
+}
+
+@Component({
+ selector: 'tb-persistent-table-widget',
+ templateUrl: './persistent-table.component.html',
+ styleUrls: ['./persistent-table.component.scss' , '../table-widget.scss']
+})
+
+export class PersistentTableComponent extends PageComponent implements OnInit {
+
+ @Input()
+ ctx: WidgetContext;
+
+ @ViewChild(MatPaginator) paginator: MatPaginator;
+ @ViewChild(MatSort) sort: MatSort;
+
+ private settings: PersistentTableWidgetSettings;
+ private widgetConfig: WidgetConfig;
+ private subscription: IWidgetSubscription;
+ private enableFilterAction = true;
+ private allowSendRequest = true;
+ private defaultPageSize = 10;
+ private defaultSortOrder = '-createdTime';
+ private rpcStatusFilter: RpcStatus;
+ private displayDetails = true;
+ private allowDelete = true;
+ private displayTableColumns: string[];
+ private widgetResize$: ResizeObserver;
+
+ public persistentDatasource: PersistentDatasource;
+ public noDataDisplayMessageText: string;
+ public rpcStatusColor = rpcStatusColors;
+ public rpcStatusTranslation = rpcStatusTranslation;
+ public displayPagination = true;
+ public enableStickyHeader = true;
+ public enableStickyAction = true;
+ public pageLink: PageLink;
+ public pageSizeOptions;
+ public actionCellButtonAction: PersistentTableWidgetActionDescriptor[] = [];
+ public displayedColumns: string[];
+ public hidePageSize = false;
+ hasData = false;
+
+ constructor(protected store: Store,
+ private elementRef: ElementRef,
+ private overlay: Overlay,
+ private viewContainerRef: ViewContainerRef,
+ private utils: UtilsService,
+ private translate: TranslateService,
+ private dialogService: DialogService,
+ private deviceService: DeviceService,
+ private dialog: MatDialog,
+ private cd: ChangeDetectorRef) {
+ super(store);
+ }
+
+ ngOnInit() {
+ this.ctx.$scope.persistentTableWidget = this;
+ this.settings = this.ctx.settings;
+ this.widgetConfig = this.ctx.widgetConfig;
+ this.subscription = this.ctx.defaultSubscription;
+ this.initializeConfig();
+ this.hasData = this.ctx.defaultSubscription.hasResolvedData;
+ this.ctx.updateWidgetParams();
+ if (this.displayPagination) {
+ this.widgetResize$ = new ResizeObserver(() => {
+ const showHidePageSize = this.elementRef.nativeElement.offsetWidth < hidePageSizePixelValue;
+ if (showHidePageSize !== this.hidePageSize) {
+ this.hidePageSize = showHidePageSize;
+ this.cd.markForCheck();
+ }
+ });
+ this.widgetResize$.observe(this.elementRef.nativeElement);
+ }
+ }
+
+ ngOnDestroy() {
+ if (this.widgetResize$) {
+ this.widgetResize$.disconnect();
+ }
+ }
+
+ ngAfterViewInit(): void {
+ if (this.displayPagination) {
+ this.sort.sortChange.subscribe(() => this.paginator.pageIndex = 0);
+ }
+ ((this.displayPagination ? merge(this.sort.sortChange, this.paginator.page) : this.sort.sortChange) as Observable)
+ .pipe(
+ tap(() => this.updateData())
+ )
+ .subscribe();
+ this.updateData();
+ }
+
+ private initializeConfig() {
+
+ this.displayPagination = isDefined(this.settings.displayPagination) ? this.settings.displayPagination : true;
+ this.enableStickyHeader = isDefined(this.settings.enableStickyHeader) ? this.settings.enableStickyHeader : true;
+ this.displayTableColumns = isDefined(this.settings.displayColumns) ? this.settings.displayColumns : [];
+ this.enableStickyAction = isDefined(this.settings.enableStickyAction) ? this.settings.enableStickyAction : true;
+ this.enableFilterAction = isDefined(this.settings.enableFilter) ? this.settings.enableFilter : true;
+ this.displayDetails = isDefined(this.settings.displayDetails) ? this.settings.displayDetails : true;
+ this.allowDelete = isDefined(this.settings.allowDelete) ? this.settings.allowDelete : true;
+ this.allowSendRequest = isDefined(this.settings.allowSendRequest) ? this.settings.allowSendRequest : true;
+
+ this.noDataDisplayMessageText =
+ noDataMessage(this.widgetConfig.noDataDisplayMessage, 'widgets.persistent-table.no-request-prompt', this.utils, this.translate);
+
+ this.displayedColumns = [...this.displayTableColumns];
+
+ const pageSize = this.settings.defaultPageSize;
+ if (isDefined(pageSize) && isNumber(pageSize) && pageSize > 0) {
+ this.defaultPageSize = pageSize;
+ }
+ this.pageSizeOptions = [this.defaultPageSize, this.defaultPageSize * 2, this.defaultPageSize * 3];
+ if (this.settings.defaultSortOrder && this.settings.defaultSortOrder.length) {
+ this.defaultSortOrder = this.settings.defaultSortOrder;
+ }
+ const sortOrder: SortOrder = sortOrderFromString(this.defaultSortOrder);
+ this.pageLink = new PageLink(this.defaultPageSize, 0, null, sortOrder);
+ this.pageLink.pageSize = this.displayPagination ? this.defaultPageSize : 1024;
+
+
+ this.ctx.widgetActions = [
+ {
+ name: 'widgets.persistent-table.add',
+ show: this.allowSendRequest,
+ icon: 'add',
+ onAction: $event => this.addPersistentRpcRequest($event)
+ },
+ {
+ name: 'widgets.persistent-table.refresh',
+ show: true,
+ icon: 'refresh',
+ onAction: () => this.reloadPersistentRequests()
+ },
+ {
+ name: 'widgets.persistent-table.filter',
+ show: this.enableFilterAction,
+ icon: 'filter_list',
+ onAction: $event => this.editFilter($event)
+ }
+ ];
+
+ if (this.settings.displayDetails) {
+ this.actionCellButtonAction.push(
+ {
+ displayName: this.translate.instant('widgets.persistent-table.details'),
+ icon: 'more_horiz',
+ details: true
+ } as PersistentTableWidgetActionDescriptor
+ );
+ }
+ if (this.settings.allowDelete) {
+ this.actionCellButtonAction.push(
+ {
+ displayName: this.translate.instant('widgets.persistent-table.delete'),
+ icon: 'delete',
+ delete: true
+ } as PersistentTableWidgetActionDescriptor
+ );
+ }
+ if (this.actionCellButtonAction.length) {
+ this.displayedColumns.push('actions');
+ }
+
+ this.persistentDatasource = new PersistentDatasource(this.translate, this.subscription, this.ctx);
+
+ const cssString = constructTableCssString(this.widgetConfig);
+ const cssParser = new cssjs();
+ cssParser.testMode = false;
+ const namespace = 'persistent-table-' + hashCode(cssString);
+ cssParser.cssPreviewNamespace = namespace;
+ cssParser.createStyleElement(namespace, cssString);
+ $(this.elementRef.nativeElement).addClass(namespace);
+ }
+
+ private updateData() {
+ if (this.displayPagination) {
+ this.pageLink.page = this.paginator.pageIndex;
+ this.pageLink.pageSize = this.paginator.pageSize;
+ } else {
+ this.pageLink.page = 0;
+ }
+ if (this.settings.defaultSortOrder && this.settings.defaultSortOrder.length) {
+ this.defaultSortOrder = this.utils.customTranslation(this.settings.defaultSortOrder, this.settings.defaultSortOrder);
+ }
+ this.pageLink.sortOrder.property = this.sort.active;
+ this.pageLink.sortOrder.direction = Direction[this.sort.direction.toUpperCase()];
+ this.persistentDatasource.loadPersistent(this.pageLink, this.rpcStatusFilter);
+ this.ctx.detectChanges();
+ }
+
+ public onDataUpdated() {
+ this.ctx.detectChanges();
+ }
+
+ reloadPersistentRequests() {
+ if (this.displayPagination) {
+ this.paginator.pageIndex = 0;
+ }
+ this.updateData();
+ }
+
+ deleteRpcRequest($event: Event, persistentRpc: PersistentRpc) {
+ if ($event) {
+ $event.stopPropagation();
+ }
+ if (persistentRpc && persistentRpc.id && persistentRpc.id.id !== NULL_UUID) {
+ this.dialogService.confirm(
+ this.translate.instant('widgets.persistent-table.delete-request-title'),
+ this.translate.instant('widgets.persistent-table.delete-request-text'),
+ this.translate.instant('action.no'),
+ this.translate.instant('action.yes')
+ ).subscribe((res) => {
+ if (res) {
+ this.deviceService.deletePersistedRpc(persistentRpc.id.id).subscribe(() => {
+ this.reloadPersistentRequests();
+ });
+ }
+ });
+ }
+ }
+
+ openRequestDetails($event: Event, persistentRpc: PersistentRpc) {
+ if ($event) {
+ $event.stopPropagation();
+ }
+ if (persistentRpc && persistentRpc.id && persistentRpc.id.id !== NULL_UUID) {
+ this.dialog.open
+ (PersistentDetailsDialogComponent,
+ {
+ disableClose: true,
+ panelClass: ['tb-dialog', 'tb-fullscreen-dialog'],
+ data: {
+ persistentRequest: persistentRpc,
+ allowDelete: this.allowDelete
+ }
+ }).afterClosed().subscribe(
+ (res) => {
+ if (res) {
+ this.reloadPersistentRequests();
+ }
+ }
+ );
+ }
+ }
+
+ addPersistentRpcRequest($event: Event){
+ if ($event) {
+ $event.stopPropagation();
+ }
+ this.dialog.open
+ (PersistentAddDialogComponent,
+ {
+ disableClose: true,
+ panelClass: ['tb-dialog', 'tb-fullscreen-dialog']
+ }).afterClosed().subscribe(
+ (requestData) => {
+ if (requestData) {
+ this.sendRequests(requestData);
+ }
+ }
+ );
+ }
+
+ private sendRequests(requestData: RequestData) {
+ let commandPromise;
+ if (requestData.oneWayElseTwoWay) {
+ commandPromise = this.ctx.controlApi.sendOneWayCommand(
+ requestData.method,
+ requestData.params, null,
+ true, null,
+ requestData.retries,
+ requestData.additionalInfo
+ );
+ } else {
+ commandPromise = this.ctx.controlApi.sendTwoWayCommand(
+ requestData.method,
+ requestData.params,
+ null,
+ true, null,
+ requestData.retries,
+ requestData.additionalInfo
+ );
+ }
+ commandPromise.subscribe(
+ () => {
+ this.reloadPersistentRequests();
+ }
+ );
+ }
+
+ public onActionButtonClick($event: Event, persistentRpc: PersistentRpc, actionDescriptor: PersistentTableWidgetActionDescriptor) {
+ if (actionDescriptor.details) {
+ this.openRequestDetails($event, persistentRpc);
+ }
+ if (actionDescriptor.delete) {
+ this.deleteRpcRequest($event, persistentRpc);
+ }
+ }
+
+ private editFilter($event: Event) {
+ if ($event) {
+ $event.stopPropagation();
+ }
+ const target = $event.target || $event.srcElement || $event.currentTarget;
+ const config = new OverlayConfig();
+ config.backdropClass = 'cdk-overlay-transparent-backdrop';
+ config.hasBackdrop = true;
+ const connectedPosition: ConnectedPosition = {
+ originX: 'end',
+ originY: 'bottom',
+ overlayX: 'end',
+ overlayY: 'top'
+ };
+ config.positionStrategy = this.overlay.position().flexibleConnectedTo(target as HTMLElement)
+ .withPositions([connectedPosition]);
+
+ const overlayRef = this.overlay.create(config);
+ overlayRef.backdropClick().subscribe(() => {
+ overlayRef.dispose();
+ });
+ const providers: StaticProvider[] = [
+ {
+ provide: PERSISTENT_FILTER_PANEL_DATA,
+ useValue: {
+ rpcStatus: this.rpcStatusFilter
+ } as PersistentFilterPanelData
+ },
+ {
+ provide: OverlayRef,
+ useValue: overlayRef
+ }
+ ];
+ const injector = Injector.create({parent: this.viewContainerRef.injector, providers});
+ const componentRef = overlayRef.attach(new ComponentPortal(PersistentFilterPanelComponent,
+ this.viewContainerRef, injector));
+ componentRef.onDestroy(() => {
+ if (componentRef.instance.result) {
+ const result = componentRef.instance.result;
+ this.rpcStatusFilter = result.rpcStatus;
+ this.reloadPersistentRequests();
+ }
+ });
+ this.ctx.detectChanges();
+ }
+}
+
+class PersistentDatasource implements DataSource {
+
+ private persistentSubject = new BehaviorSubject([]);
+ private pageDataSubject = new BehaviorSubject>(emptyPageData());
+
+ private rpcErrorText: string;
+ private executingSubjects: Array>;
+ private executingRpcRequest = false;
+
+ public dataLoading = true;
+ public pageData$ = this.pageDataSubject.asObservable();
+
+ constructor(private translate: TranslateService,
+ private subscription: IWidgetSubscription,
+ private ctx: WidgetContext) {
+ }
+
+ connect(collectionViewer: CollectionViewer): Observable> {
+ return this.persistentSubject.asObservable();
+ }
+
+ disconnect(collectionViewer: CollectionViewer): void {
+ this.persistentSubject.complete();
+ this.pageDataSubject.complete();
+ }
+
+ reset() {
+ const pageData = emptyPageData();
+ this.persistentSubject.next(pageData.data);
+ this.pageDataSubject.next(pageData);
+ }
+
+ loadPersistent(pageLink: PageLink, rpcStatusFilter: RpcStatus) {
+ this.dataLoading = true;
+
+ const result = new ReplaySubject>();
+ this.fetchEntities(pageLink, rpcStatusFilter).pipe(
+ catchError(() => of(emptyPageData())),
+ ).subscribe(
+ (pageData) => {
+ this.persistentSubject.next(pageData.data);
+ this.pageDataSubject.next(pageData);
+ result.next(pageData);
+ this.dataLoading = false;
+ }
+ );
+ return result;
+ }
+
+ fetchEntities(pageLink: PageLink, rpcStatusFilter: RpcStatus): Observable> {
+ if (!this.subscription.rpcEnabled) {
+ return throwError(new Error('Rpc disabled!'));
+ } else if (!this.subscription.targetDeviceId) {
+ return throwError(new Error('Target device is not set!'));
+ }
+ const rpcSubject: Subject = new Subject();
+
+ this.ctx.deviceService.getPersistedRpcRequests(this.subscription.targetDeviceId, pageLink, rpcStatusFilter).subscribe(
+ (responseBody) => {
+ rpcSubject.next(responseBody);
+ rpcSubject.complete();
+ },
+ (rejection: HttpErrorResponse) => {
+ this.rpcErrorText = null;
+ this.executingSubjects = [];
+
+ const index = this.executingSubjects.indexOf(rpcSubject);
+ if (index >= 0) {
+ this.executingSubjects.splice(index, 1);
+ }
+ this.executingRpcRequest = this.executingSubjects.length > 0;
+ this.subscription.options.callbacks.rpcStateChanged(this.subscription);
+ if (!this.executingRpcRequest || rejection.status === 504) {
+ this.subscription.rpcRejection = rejection;
+ if (rejection.status === 504) {
+ this.subscription.rpcErrorText = 'Request Timeout.';
+ } else {
+ this.subscription.rpcErrorText = 'Error : ' + rejection.status + ' - ' + rejection.statusText;
+ const error = this.extractRejectionErrorText(rejection);
+ if (error) {
+ this.subscription.rpcErrorText += '';
+ this.subscription.rpcErrorText += error.message || '';
+ }
+ }
+ this.subscription.callbacks.onRpcFailed(this.subscription);
+ }
+ rpcSubject.error(rejection);
+ }
+ );
+ return rpcSubject.asObservable();
+ }
+
+ extractRejectionErrorText(rejection: HttpErrorResponse) {
+ let error = null;
+ if (rejection.error) {
+ error = rejection.error;
+ try {
+ error = rejection.error ? JSON.parse(rejection.error) : null;
+ } catch (e) {}
+ }
+ if (error && !error.message) {
+ error = this.prepareMessageFromData(error);
+ } else if (error && error.message) {
+ error = error.message;
+ }
+ return error;
+ }
+
+ prepareMessageFromData(data) {
+ if (typeof data === 'object' && data.constructor === ArrayBuffer) {
+ const msg = String.fromCharCode.apply(null, new Uint8Array(data));
+ try {
+ const msgObj = JSON.parse(msg);
+ if (msgObj.message) {
+ return msgObj.message;
+ } else {
+ return msg;
+ }
+ } catch (e) {
+ return msg;
+ }
+ } else {
+ return data;
+ }
+ }
+
+ isEmpty(): Observable {
+ return this.persistentSubject.pipe(
+ map((requests) => !requests.length)
+ );
+ }
+
+ total(): Observable {
+ return this.pageDataSubject.pipe(
+ map((pageData) => pageData.totalElements)
+ );
+ }
+}
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/rpc/round-switch.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/round-switch.component.html
index a7b1306133..425f7ee37a 100644
--- a/ui-ngx/src/app/modules/home/components/widget/lib/rpc/round-switch.component.html
+++ b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/round-switch.component.html
@@ -1,6 +1,6 @@
- = new EventEmitter
();
+ private cssClass: string;
+
constructor(protected store: Store,
- private cd: ChangeDetectorRef) {
+ private cd: ChangeDetectorRef,
+ private renderer: Renderer2,
+ @Inject(DOCUMENT) private document: Document) {
super(store);
}
ngOnInit(): void {
this.widget.widgetContext.containerChangeDetector = this.cd;
+ const cssString = this.widget.widget.config.widgetCss;
+ if (isNotEmptyStr(cssString)) {
+ const cssParser = new cssjs();
+ cssParser.testMode = false;
+ this.cssClass = 'tb-widget-css-' + guid();
+ this.renderer.addClass(this.gridsterItem.el, this.cssClass);
+ cssParser.cssPreviewNamespace = this.cssClass;
+ cssParser.createStyleElement(this.cssClass, cssString);
+ }
+ }
+
+ ngOnDestroy(): void {
+ if (this.cssClass) {
+ const el = this.document.getElementById(this.cssClass);
+ if (el) {
+ el.parentNode.removeChild(el);
+ }
+ }
}
isHighlighted(widget: DashboardWidget) {
@@ -105,6 +141,11 @@ export class WidgetContainerComponent extends PageComponent implements OnInit {
}
onFullscreenChanged(expanded: boolean) {
+ if (expanded) {
+ this.renderer.addClass(this.tbWidgetElement.nativeElement, this.cssClass);
+ } else {
+ this.renderer.removeClass(this.tbWidgetElement.nativeElement, this.cssClass);
+ }
this.widgetFullscreenChanged.emit(expanded);
}
diff --git a/ui-ngx/src/app/modules/home/components/widget/widget.component.html b/ui-ngx/src/app/modules/home/components/widget/widget.component.html
index fcaede8fc9..0d20c1de2b 100644
--- a/ui-ngx/src/app/modules/home/components/widget/widget.component.html
+++ b/ui-ngx/src/app/modules/home/components/widget/widget.component.html
@@ -1,6 +1,6 @@
-
+
{{section.icon}}
{{section.name | translate}}
diff --git a/ui-ngx/src/app/modules/home/menu/menu-link.component.scss b/ui-ngx/src/app/modules/home/menu/menu-link.component.scss
index 3abcc4c738..da8df4b469 100644
--- a/ui-ngx/src/app/modules/home/menu/menu-link.component.scss
+++ b/ui-ngx/src/app/modules/home/menu/menu-link.component.scss
@@ -1,5 +1,5 @@
/**
- * Copyright © 2016-2021 The Thingsboard Authors
+ * Copyright © 2016-2022 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.
diff --git a/ui-ngx/src/app/modules/home/menu/menu-link.component.ts b/ui-ngx/src/app/modules/home/menu/menu-link.component.ts
index 58724b89f9..cae14d32b6 100644
--- a/ui-ngx/src/app/modules/home/menu/menu-link.component.ts
+++ b/ui-ngx/src/app/modules/home/menu/menu-link.component.ts
@@ -1,5 +1,5 @@
///
-/// Copyright © 2016-2021 The Thingsboard Authors
+/// Copyright © 2016-2022 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.
diff --git a/ui-ngx/src/app/modules/home/menu/menu-toggle.component.html b/ui-ngx/src/app/modules/home/menu/menu-toggle.component.html
index 0a41e75657..0635205581 100644
--- a/ui-ngx/src/app/modules/home/menu/menu-toggle.component.html
+++ b/ui-ngx/src/app/modules/home/menu/menu-toggle.component.html
@@ -1,6 +1,6 @@
+ routerLinkActive="tb-active" [routerLinkActiveOptions]="{paths: 'exact', queryParams: 'ignored', matrixParams: 'ignored', fragment: 'ignored'}" routerLink="{{section.path}}">
{{section.icon}}
{{section.name | translate}}
diff --git a/ui-ngx/src/app/modules/home/menu/menu-toggle.component.scss b/ui-ngx/src/app/modules/home/menu/menu-toggle.component.scss
index 87899b02b5..a076fa77d6 100644
--- a/ui-ngx/src/app/modules/home/menu/menu-toggle.component.scss
+++ b/ui-ngx/src/app/modules/home/menu/menu-toggle.component.scss
@@ -1,5 +1,5 @@
/**
- * Copyright © 2016-2021 The Thingsboard Authors
+ * Copyright © 2016-2022 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.
diff --git a/ui-ngx/src/app/modules/home/menu/menu-toggle.component.ts b/ui-ngx/src/app/modules/home/menu/menu-toggle.component.ts
index 6bbc5414fe..76a818c16b 100644
--- a/ui-ngx/src/app/modules/home/menu/menu-toggle.component.ts
+++ b/ui-ngx/src/app/modules/home/menu/menu-toggle.component.ts
@@ -1,5 +1,5 @@
///
-/// Copyright © 2016-2021 The Thingsboard Authors
+/// Copyright © 2016-2022 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.
diff --git a/ui-ngx/src/app/modules/home/menu/side-menu.component.html b/ui-ngx/src/app/modules/home/menu/side-menu.component.html
index 91275719e9..8a9f07f3c9 100644
--- a/ui-ngx/src/app/modules/home/menu/side-menu.component.html
+++ b/ui-ngx/src/app/modules/home/menu/side-menu.component.html
@@ -1,6 +1,6 @@