diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/circles-data-layer.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/circles-data-layer.ts index e92a4503f2..95c845b164 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/circles-data-layer.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/circles-data-layer.ts @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 import { CirclesDataLayerSettings, defaultBaseCirclesDataLayerSettings, @@ -9,9 +10,9 @@ import { } from '@shared/models/widget/maps/map.models'; import L from 'leaflet'; import { DataKey, FormattedData } from '@shared/models/widget.models'; -import { ShapeStyleInfo, TbShapesDataLayer } from '@home/components/widget/lib/maps/data-layer/shapes-data-layer'; +import { isSameShapeStyle, ShapeStyleInfo, TbShapesDataLayer } from '@home/components/widget/lib/maps/data-layer/shapes-data-layer'; import { TbMap } from '@home/components/widget/lib/maps/map'; -import { Observable } from 'rxjs'; +import { Observable, Subscription } from 'rxjs'; import { isNotEmptyStr } from '@core/utils'; import { TbLatestDataLayerItem, @@ -23,6 +24,8 @@ class TbCircleDataLayerItem extends TbLatestDataLayerItem, @@ -41,6 +44,7 @@ class TbCircleDataLayerItem extends TbLatestDataLayerItem { + this.styleSubscription = this.dataLayer.getShapeStyle(data, dsData, this.circleStyleInfo?.patternId).subscribe((styleInfo) => { this.circleStyleInfo = styleInfo; if (this.circle) { this.circle.setStyle(this.circleStyleInfo.style); @@ -77,12 +81,16 @@ class TbCircleDataLayerItem extends TbLatestDataLayerItem, dsData: FormattedData[]): void { - this.dataLayer.getShapeStyle(data, dsData, this.circleStyleInfo?.patternId).subscribe((styleInfo) => { + this.styleSubscription?.unsubscribe(); + this.styleSubscription = this.dataLayer.getShapeStyle(data, dsData, this.circleStyleInfo?.patternId).subscribe((styleInfo) => { + const styleChanged = !isSameShapeStyle(this.circleStyleInfo, styleInfo); this.circleStyleInfo = styleInfo; - this.updateCircleShape(data); + const geometryChanged = this.updateCircleShape(data); this.updateTooltip(data, dsData); - this.updateLabel(data, dsData); - this.circle.setStyle(this.circleStyleInfo.style); + this.updateLabel(data, dsData, geometryChanged); + if (styleChanged) { + this.circle.setStyle(this.circleStyleInfo.style); + } }); } @@ -154,20 +162,28 @@ class TbCircleDataLayerItem extends TbLatestDataLayerItem) { + private updateCircleShape(data: FormattedData): boolean { if (this.editing) { - return; + this.markDataStale(); + return false; } + let changed = this.geometryDirty; + this.geometryDirty = false; const circleData = this.dataLayer.extractCircleCoordinates(data); const center = new L.LatLng(circleData.latitude, circleData.longitude); if (!this.circle.getLatLng().equals(center)) { this.circle.setLatLng(center); + changed = true; } if (this.circle.getRadius() !== circleData.radius) { this.circle.setRadius(circleData.radius); + changed = true; } + return changed; } } diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/data-layer-utils.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/data-layer-utils.ts index ea6d461e92..c9df3ac061 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/data-layer-utils.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/data-layer-utils.ts @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 import { DataLayerTooltipSettings, DataLayerTooltipTrigger, processTooltipTemplate, @@ -10,6 +11,14 @@ import { FormattedData } from '@shared/models/widget.models'; import L from 'leaflet'; import { DataLayerPatternProcessor } from '@home/components/widget/lib/maps/data-layer/map-data-layer'; +interface TooltipState { + processor: DataLayerPatternProcessor; + data: FormattedData; + content?: string; +} + +const tooltipStates = new WeakMap(); + export const createTooltip = (map: TbMap, layer: L.Layer, settings: DataLayerTooltipSettings, @@ -17,6 +26,13 @@ export const createTooltip = (map: TbMap, canOpen: () => boolean): L.Popup => { const tooltip = L.popup({autoClose: settings.autoclose, closeOnClick: false}); (tooltip as any)._source = layer; + const open = (beforeOpen?: () => void) => { + if ((tooltip as any)._prepareOpen((layer as any)._latlng)) { + beforeOpen?.(); + renderTooltip(tooltip, map.getData()); + tooltip.openOn(map.getMap()); + } + }; layer.on('move', (e) => { tooltip.setLatLng((e as any).latlng); }); @@ -29,18 +45,13 @@ export const createTooltip = (map: TbMap, if (tooltip.isOpen()) { tooltip.close(); } else if (canOpen()) { - if ((tooltip as any)._prepareOpen((layer as any)._latlng)) { - map.deselectItem(); - tooltip.openOn(map.getMap()); - } + open(() => map.deselectItem()); } }); } else if (settings.trigger === DataLayerTooltipTrigger.hover) { layer.on('mouseover', () => { if (canOpen()) { - if ((tooltip as any)._prepareOpen((layer as any)._latlng)) { - tooltip.openOn(map.getMap()); - } + open(); } }); layer.on('mousemove', (e) => { @@ -51,7 +62,7 @@ export const createTooltip = (map: TbMap, }); } layer.on('popupopen', () => { - bindTooltipActions(map, tooltip, settings, data); + bindTooltipActions(map, tooltip, settings, tooltipStates.get(tooltip)?.data ?? data); }); return tooltip; } @@ -62,12 +73,26 @@ export const updateTooltip = (map: TbMap, processor: DataLayerPatternProcessor, data: FormattedData, dsData: FormattedData[]): void => { - let tooltipTemplate = processor.processPattern(data, dsData); - tooltipTemplate = processTooltipTemplate(tooltipTemplate); - tooltip.setContent(tooltipTemplate); - if (tooltip.isOpen() && tooltip.getElement()) { - bindTooltipActions(map, tooltip, settings, data); + tooltipStates.set(tooltip, {processor, data, content: tooltipStates.get(tooltip)?.content}); + if (tooltip.isOpen()) { + if (renderTooltip(tooltip, dsData) && tooltip.getElement()) { + bindTooltipActions(map, tooltip, settings, data); + } + } +} + +const renderTooltip = (tooltip: L.Popup, dsData: FormattedData[]): boolean => { + const state = tooltipStates.get(tooltip); + let changed = false; + if (state) { + const content = processTooltipTemplate(state.processor.processPattern(state.data, dsData)); + if (content !== state.content) { + state.content = content; + tooltip.setContent(content); + changed = true; + } } + return changed; } const bindTooltipActions = (map: TbMap, tooltip: L.Popup, settings: DataLayerTooltipSettings, data: FormattedData): void => { @@ -80,7 +105,7 @@ const bindTooltipActions = (map: TbMap, tooltip: L.Popup, settings: DataLay if (action) { element.onclick = ($event) => { - map.dataItemClick($event, action, data); + map.dataItemClick($event, action, tooltipStates.get(tooltip)?.data ?? data); return false; }; } diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/latest-map-data-layer.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/latest-map-data-layer.ts index 541ae0201a..9cb6e89ac6 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/latest-map-data-layer.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/latest-map-data-layer.ts @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 import { DataLayerEditAction, MapDataLayerSettings, @@ -12,12 +13,25 @@ import L from 'leaflet'; import { createTooltip, updateTooltip } from './data-layer-utils'; import { TbDataLayerItem, TbMapDataLayer } from '@home/components/widget/lib/maps/data-layer/map-data-layer'; +const isSameFormattedData = (a: FormattedData, b: FormattedData): boolean => { + if (a === b) { + return true; + } + if (!a || !b) { + return false; + } + const aKeys = Object.keys(a); + return aKeys.length === Object.keys(b).length && aKeys.every(key => a[key] === b[key]); +}; + export abstract class TbLatestDataLayerItem = TbLatestMapDataLayer, L extends L.Layer = L.Layer> extends TbDataLayerItem { protected tooltip: L.Popup; + protected labelContent: string; protected data: FormattedData; protected selected = false; + private dataStale = false; protected constructor(data: FormattedData, dsData: FormattedData[], @@ -35,8 +49,10 @@ export abstract class TbLatestDataLayerItem, dsData: FormattedData[]): void { - this.data = data; - this.doUpdate(data, dsData); + public update(data: FormattedData, dsData: FormattedData[]): boolean { + if (!this.dataStale && this.dataLayer.canSkipUnchangedItems() && isSameFormattedData(this.data, data)) { + return false; + } else { + this.dataStale = false; + this.data = data; + this.doUpdate(data, dsData); + return true; + } } public remove() { @@ -130,6 +152,15 @@ export abstract class TbLatestDataLayerItem { @@ -182,16 +213,23 @@ export abstract class TbLatestDataLayerItem, dsData: FormattedData[]) { + protected updateLabel(data: FormattedData, dsData: FormattedData[], force = true) { if (this.settings.label.show) { - this.unbindLabel(); - const label = this.dataLayer.dataLayerLabelProcessor.processPattern(data, dsData); - const labelColor = this.dataLayer.getCtx().widgetConfig.color; - const content: L.Content = `
${label}
`; - this.bindLabel(content); + const content = this.createLabelContent(data, dsData); + if (force || content !== this.labelContent) { + this.unbindLabel(); + this.bindLabel(content); + this.labelContent = content; + } } } + protected createLabelContent(data: FormattedData, dsData: FormattedData[]): string { + const label = this.dataLayer.dataLayerLabelProcessor.processPattern(data, dsData); + const labelColor = this.dataLayer.getCtx().widgetConfig.color; + return `
${label}
`; + } + protected canDeselect(cancel = false): boolean { return true; } @@ -311,15 +349,18 @@ export abstract class TbLatestMapDataLayer d.$datasource.mapDataIds.includes(this.mapDataId)); const toDelete = new Set(Array.from(this.layerItems.keys())); const updatedItems: TbLatestDataLayerItem[] = []; + const createdItems: TbLatestDataLayerItem[] = []; layerData.forEach((data) => { if (this.isValidLayerData(data)) { let layerItem = this.layerItems.get(data.entityId); if (layerItem) { - layerItem.update(data, dsData); - updatedItems.push(layerItem); + if (layerItem.update(data, dsData)) { + updatedItems.push(layerItem); + } } else { layerItem = this.createLayerItem(data, dsData); this.layerItems.set(data.entityId, layerItem); + createdItems.push(layerItem); } toDelete.delete(data.entityId); } else { @@ -332,6 +373,9 @@ export abstract class TbLatestMapDataLayer { this.removeItem(key); }); + if (createdItems.length) { + this.addItemsToContainer(createdItems); + } if (updatedItems.length) { this.layerItemsUpdated(updatedItems); } @@ -388,6 +432,7 @@ export abstract class TbLatestMapDataLayer[]): void { } + protected addItemsToContainer(items: TbLatestDataLayerItem[]): void { + const container = this.getDataLayerContainer(); + for (const item of items) { + try { + container.addLayer(item.getLayer()); + } catch (e) { + console.warn(e); + } + } + items.forEach(item => item.onAddedToContainer()); + } + private prepareUnplacedItems(): UnplacedMapDataItem[] { const div = document.createElement('div'); for (const item of this.unplacedItems) { diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/map-data-layer.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/map-data-layer.ts index 08e0ef583c..e355820d42 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/map-data-layer.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/map-data-layer.ts @@ -14,7 +14,7 @@ import { TbMapDatasource } from '@shared/models/widget/maps/map.models'; import { - createLabelFromPattern, + fillDataPattern, guid, isDefined, isDefinedAndNotNull, @@ -28,21 +28,79 @@ import L from 'leaflet'; import { CompiledTbFunction } from '@shared/models/js-function.models'; import { forkJoin, Observable, of } from 'rxjs'; import { map } from 'rxjs/operators'; -import { DataKey, DatasourceType, FormattedData } from '@shared/models/widget.models'; +import { DataKey, DatasourceType, FormattedData, ReplaceInfo } from '@shared/models/widget.models'; import { CustomTranslatePipe } from '@shared/pipe/custom-translate.pipe'; import { TbMap } from '@home/components/widget/lib/maps/map'; import { WidgetContext } from '@home/models/widget-component.models'; import { ColorRange } from '@shared/models/widget-settings.models'; +const additionalDataArgsRegex = /\b(dsData|ctx|arguments|Date|moment|performance)\b/; + +export const tbFunctionUsesAdditionalData = (value: any): boolean => { + const body = typeof value === 'string' ? value : value?.body; + const hasModules = !!value?.modules && Object.keys(value.modules).length > 0; + return typeof body === 'string' && (hasModules || additionalDataArgsRegex.test(body)); +}; + +const settingsUseAdditionalData = (value: any, key?: string): boolean => { + if (key?.endsWith('Function')) { + return tbFunctionUsesAdditionalData(value); + } + if (value && typeof value === 'object') { + return Object.keys(value).some(k => settingsUseAdditionalData(value[k], k)); + } + return false; +}; + +interface ParsedPatternVariable { + variable: string; + label: string; + valDec: number; + keyIndex?: number; +} + +const patternVariableRegex = /\${([^}]*)}/g; + +const parsePatternVariables = (pattern: string): ParsedPatternVariable[] => { + const variables: ParsedPatternVariable[] = []; + if (typeof pattern === 'string') { + for (const match of pattern.matchAll(patternVariableRegex)) { + let label = match[1]; + let valDec = 2; + const splitValues = label.split(':'); + if (splitValues.length > 1) { + label = splitValues[0]; + valDec = parseFloat(splitValues[1]); + } + const variable: ParsedPatternVariable = {variable: match[0], label, valDec}; + if (label.startsWith('#')) { + const keyIndexStr = label.substring(1); + const n = Math.floor(Number(keyIndexStr)); + variable.label = ''; + if (String(n) === keyIndexStr && n >= 0) { + variable.keyIndex = n; + } + } + variables.push(variable); + } + } + return variables; +}; + export class DataLayerPatternProcessor { + private static readonly PARSED_PATTERN_CACHE_SIZE = 100; + private patternFunction: CompiledTbFunction; private pattern: string; + private customTranslate: CustomTranslatePipe; + private parsedPatterns = new Map(); constructor(private dataLayer: TbMapDataLayer, private settings: DataLayerPatternSettings) {} public setup(): Observable { + this.customTranslate = this.dataLayer.getCtx().$injector.get(CustomTranslatePipe); if (this.settings.type === DataLayerPatternType.function) { return parseTbFunction(this.dataLayer.getCtx().http, this.settings.patternFunction, ['data', 'dsData', 'ctx']).pipe( map((parsed) => { @@ -63,9 +121,31 @@ export class DataLayerPatternProcessor { } else { pattern = this.pattern; } - const text = createLabelFromPattern(pattern, data); - const customTranslate = this.dataLayer.getCtx().$injector.get(CustomTranslatePipe); - return customTranslate.transform(text); + const replaceInfo: ReplaceInfo[] = []; + for (const v of this.getParsedPattern(pattern)) { + let dataKeyName = v.label; + if (v.keyIndex !== undefined) { + const dataKey = data.$datasource?.dataKeys?.[v.keyIndex]; + if (!dataKey) { + break; + } + dataKeyName = dataKey.label; + } + replaceInfo.push({variable: v.variable, valDec: v.valDec, dataKeyName}); + } + return this.customTranslate.transform(fillDataPattern(pattern, replaceInfo, data)); + } + + private getParsedPattern(pattern: string): ParsedPatternVariable[] { + let parsed = this.parsedPatterns.get(pattern); + if (!parsed) { + parsed = parsePatternVariables(pattern); + if (this.parsedPatterns.size >= DataLayerPatternProcessor.PARSED_PATTERN_CACHE_SIZE) { + this.parsedPatterns.delete(this.parsedPatterns.keys().next().value); + } + this.parsedPatterns.set(pattern, parsed); + } + return parsed; } } @@ -171,12 +251,15 @@ export abstract class TbMapDataLayer, inputSettings: S) { this.settings = mergeDeepIgnoreArray({} as S, this.defaultBaseSettings(map) as S, inputSettings); + this.itemsUseAdditionalData = settingsUseAdditionalData(this.settings); if (this.settings.groups?.length) { this.settings.groups.forEach((group) => { this.groupsState[group] = true; @@ -222,6 +305,10 @@ export abstract class TbMapDataLayer item.invalidateCoordinates()); } + public canSkipUnchangedItems(): boolean { + return !this.itemsUseAdditionalData; + } + public getCtx(): WidgetContext { return this.map.getCtx(); } diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/markers-data-layer.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/markers-data-layer.ts index 0cfc7df437..0a9cda5083 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/markers-data-layer.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/markers-data-layer.ts @@ -25,17 +25,18 @@ import { } from '@shared/models/widget/maps/map.models'; import L, { FeatureGroup } from 'leaflet'; import { DataKey, FormattedData } from '@shared/models/widget.models'; -import { forkJoin, Observable, of } from 'rxjs'; +import { forkJoin, Observable, of, Subscription, throwError } from 'rxjs'; import { CompiledTbFunction } from '@shared/models/js-function.models'; import { deepClone, isDefined, isDefinedAndNotNull, isEmptyStr, + isEqual, parseTbFunction, plainColorFromVariable, safeExecuteTbFunction } from '@core/utils'; -import { catchError, map, switchMap } from 'rxjs/operators'; +import { catchError, map, shareReplay, switchMap } from 'rxjs/operators'; import tinycolor from 'tinycolor2'; import { ImagePipe } from '@shared/pipe/image.pipe'; import { TbMap } from '@home/components/widget/lib/maps/map'; @@ -57,8 +58,12 @@ import { DataLayerColorProcessor, TbMapDataLayer } from '@home/components/widget export class MarkerDataProcessor { + private static readonly MARKER_ICON_CACHE_SIZE = 256; + private positionFunction: CompiledTbFunction; private markerIconProcessor: MarkerIconProcessor; + private markerIconCache = new Map(); + private markerAssetCache = new Map>(); constructor(public dataLayer: TbMapDataLayer, private settings: S, @@ -129,54 +134,116 @@ export class MarkerDataProcessor { - return createColorMarkerShapeURI(this.dataLayer.getCtx().$injector.get(MatIconRegistry), this.dataLayer.getCtx().$injector.get(DomSanitizer), shape, color).pipe( - map((iconUrl) => { - let icon: L.Icon; - if (rotationAngle === 0) { - icon = L.icon({ - iconUrl, - iconSize: [size, size], - iconAnchor: [size * this.markerOffset[0], size * this.markerOffset[1]], - popupAnchor: [size * this.tooltipOffset[0], size * this.tooltipOffset[1]] - }); - } else { - const style = `background-image: url(${iconUrl}); transform: rotate(${rotationAngle}deg); height: ${size}px; width: ${size}px;`; - icon = L.divIcon({ - html: `
`, - className: 'tb-marker-div-icon', - iconSize: [size, size], - iconAnchor: [size * this.markerOffset[0], size * this.markerOffset[1]], - popupAnchor: [size * this.tooltipOffset[0], size * this.tooltipOffset[1]] - }); - } - return { - size: [size, size], - icon - } - }) - ); + const assetKey = `shape|${shape}|${color.toHex8()}`; + return this.cachedMarkerIcon(assetKey, rotationAngle, size, + () => createColorMarkerShapeURI(this.dataLayer.getCtx().$injector.get(MatIconRegistry), + this.dataLayer.getCtx().$injector.get(DomSanitizer), shape, color), + (iconUrl: string) => this.buildColoredMarkerShape(iconUrl, rotationAngle, size)); } public createColoredMarkerIcon(iconContainer: MarkerIconContainer, icon: string, color: tinycolor.Instance, rotationAngle = 0, size = 34): Observable { - return createColorMarkerIconElement(this.dataLayer.getCtx().$injector.get(MatIconRegistry), this.dataLayer.getCtx().$injector.get(DomSanitizer), - iconContainer, icon, color).pipe( - map((element) => { - if (rotationAngle !== 0) { - element.style.transform = `rotate(${rotationAngle}deg)`; - } - return { - size: [size, size], - icon: L.divIcon({ - html: element.outerHTML, - className: 'tb-marker-div-icon', - iconSize: [size, size], - iconAnchor: [size * this.markerOffset[0], size * this.markerOffset[1]], - popupAnchor: [size * this.tooltipOffset[0], size * this.tooltipOffset[1]] - }) - }; + const assetKey = `icon|${iconContainer}|${icon}|${color.toHex8()}`; + return this.cachedMarkerIcon(assetKey, rotationAngle, size, + () => createColorMarkerIconElement(this.dataLayer.getCtx().$injector.get(MatIconRegistry), + this.dataLayer.getCtx().$injector.get(DomSanitizer), iconContainer, icon, color), + (element: SVGElement) => this.buildColoredMarkerIcon(element, rotationAngle, size)); + } + + private cachedMarkerIcon(assetKey: string, rotationAngle: number, size: number, + loadAsset: () => Observable, + buildIcon: (asset: T) => MarkerIconInfo): Observable { + const iconKey = `${assetKey}|${size}`; + const cachedIcon = rotationAngle === 0 ? this.lruGet(this.markerIconCache, iconKey) : undefined; + let result: Observable; + if (cachedIcon) { + result = of(cachedIcon); + } else { + let asset$ = this.lruGet(this.markerAssetCache, assetKey) as Observable; + if (!asset$) { + const shared$: Observable = loadAsset().pipe( + catchError((error) => { + if (this.markerAssetCache.get(assetKey) === shared$) { + this.markerAssetCache.delete(assetKey); + } + return throwError(() => error); + }), + shareReplay({bufferSize: 1, refCount: false}) + ); + this.lruSet(this.markerAssetCache, assetKey, shared$); + asset$ = shared$; + } + result = asset$.pipe( + map((asset) => { + const iconInfo = buildIcon(asset); + if (rotationAngle === 0) { + this.lruSet(this.markerIconCache, iconKey, iconInfo); + } + return iconInfo; + }) + ); + } + return result; + } + + private lruGet(cache: Map, key: string): V | undefined { + const value = cache.get(key); + if (value !== undefined) { + cache.delete(key); + cache.set(key, value); + } + return value; + } + + private lruSet(cache: Map, key: string, value: V) { + cache.set(key, value); + if (cache.size > MarkerDataProcessor.MARKER_ICON_CACHE_SIZE) { + cache.delete(cache.keys().next().value); + } + } + + private buildColoredMarkerShape(iconUrl: string, rotationAngle: number, size: number): MarkerIconInfo { + let icon: L.Icon; + if (rotationAngle === 0) { + icon = L.icon({ + iconUrl, + iconSize: [size, size], + iconAnchor: [size * this.markerOffset[0], size * this.markerOffset[1]], + popupAnchor: [size * this.tooltipOffset[0], size * this.tooltipOffset[1]] + }); + } else { + const style = `background-image: url(${iconUrl}); transform: rotate(${rotationAngle}deg); height: ${size}px; width: ${size}px;`; + icon = L.divIcon({ + html: `
`, + className: 'tb-marker-div-icon', + iconSize: [size, size], + iconAnchor: [size * this.markerOffset[0], size * this.markerOffset[1]], + popupAnchor: [size * this.tooltipOffset[0], size * this.tooltipOffset[1]] + }); + } + return { + size: [size, size], + icon + }; + } + + private buildColoredMarkerIcon(sourceElement: SVGElement, rotationAngle: number, size: number): MarkerIconInfo { + let html = sourceElement.outerHTML; + if (rotationAngle !== 0) { + const element = sourceElement.cloneNode(true) as SVGElement; + element.style.transform = `rotate(${rotationAngle}deg)`; + html = element.outerHTML; + } + return { + size: [size, size], + icon: L.divIcon({ + html, + className: 'tb-marker-div-icon', + iconSize: [size, size], + iconAnchor: [size * this.markerOffset[0], size * this.markerOffset[1]], + popupAnchor: [size * this.tooltipOffset[0], size * this.tooltipOffset[1]] }) - ); + }; } } @@ -377,12 +444,33 @@ class ImageMarkerIconProcessor extends MarkerIconProcessor } } +export const createPlaceholderMarkerIcon = (): L.DivIcon => + L.divIcon({ html: '', className: 'tb-marker-div-icon', iconSize: [0, 0] }); + +export const isSameMarkerIcon = (applied: MarkerIconInfo, next: MarkerIconInfo): boolean => + !!applied && (applied === next || ( + applied.icon.constructor === next.icon.constructor && + isEqual(applied.size, next.size) && + isEqual(applied.icon.options, next.icon.options) + )); + +const rotationFreeIconOptions = (options: L.DivIconOptions): L.DivIconOptions => + typeof options.html === 'string' ? {...options, html: options.html.replace(/rotate\([^)]*\)/, 'rotate()')} : options; + +export const isRotationOnlyIconChange = (applied: MarkerIconInfo, next: MarkerIconInfo): boolean => + !!applied && applied.icon instanceof L.DivIcon && next.icon instanceof L.DivIcon && + isEqual(applied.size, next.size) && + isEqual(rotationFreeIconOptions(applied.icon.options), rotationFreeIconOptions(next.icon.options)); + class TbMarkerDataLayerItem extends TbLatestDataLayerItem { private marker: L.Marker; private labelOffset: L.PointTuple; + private boundLabelOffset: L.PointTuple; + private appliedIconInfo: MarkerIconInfo; private iconClassList: string[]; private moving = false; + private markerIconSubscription: Subscription; private dragStart: () => void; private dragEnd: () => void; @@ -401,12 +489,18 @@ class TbMarkerDataLayerItem extends TbLatestDataLayerItem, dsData: FormattedData[]): L.Marker { this.iconClassList = []; const location = this.dataLayer.dataProcessor.extractLocation(data, dsData); this.dragStart = this._dragStart.bind(this); this.dragEnd = this._dragEnd.bind(this); this.marker = L.marker(location, { + icon: createPlaceholderMarkerIcon(), tbMarkerData: data, snapIgnore: !this.dataLayer.isSnappable(), bubblingMouseEvents: !this.dataLayer.isEditMode(), @@ -424,6 +518,23 @@ class TbMarkerDataLayerItem extends TbLatestDataLayerItem, dsData: FormattedData[]) { + if (this.settings.label.show) { + const content = this.createLabelContent(data, dsData); + const offsetChanged = !isEqual(this.boundLabelOffset, this.labelOffset); + if (this.marker.getTooltip() && !offsetChanged) { + if (content !== this.labelContent) { + this.marker.setTooltipContent(content); + } + } else { + this.unbindLabel(); + this.bindLabel(content); + } + this.labelContent = content; + this.boundLabelOffset = this.labelOffset; + } + } + protected doUpdate(data: FormattedData, dsData: FormattedData[]): void { this.marker.options.tbMarkerData = data; this.updateMarkerLocation(data, dsData); @@ -501,6 +612,7 @@ class TbMarkerDataLayerItem extends TbLatestDataLayerItem, dsData: FormattedData[]) { @@ -511,25 +623,29 @@ class TbMarkerDataLayerItem extends TbLatestDataLayerItem, dsData: FormattedData[]) { - this.dataLayer.dataProcessor.createMarkerIcon(data, dsData).subscribe( + this.markerIconSubscription?.unsubscribe(); + this.markerIconSubscription = this.dataLayer.dataProcessor.createMarkerIcon(data, dsData).subscribe( (iconInfo) => { - let icon: L.Icon | L.DivIcon; - const options = deepClone(iconInfo.icon.options); - options.className = this.updateIconClasses(options.className); - if (iconInfo.icon instanceof L.DivIcon) { - icon = L.divIcon(options); - } else { - icon = L.icon(options as L.IconOptions); - } - this.marker.setIcon(icon); - const anchor = 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.dataLayer.markerOffset[1] + 10]; + if (!isSameMarkerIcon(this.appliedIconInfo, iconInfo)) { + let icon: L.Icon | L.DivIcon; + const options = deepClone(iconInfo.icon.options); + options.className = this.updateIconClasses(options.className); + if (iconInfo.icon instanceof L.DivIcon) { + icon = L.divIcon(options); + } else { + icon = L.icon(options as L.IconOptions); + } + this.marker.setIcon(icon); + this.appliedIconInfo = iconInfo; + const anchor = 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.dataLayer.markerOffset[1] + 10]; + } + this.editModeUpdated(); } this.updateLabel(data, dsData); - this.editModeUpdated(); } ); } @@ -562,6 +678,8 @@ export class TbMarkersDataLayer extends TbLatestMapDataLayer(); + private removedPendingClusterLayers = new Set(); private clusterMarkerColorFunction: CompiledTbFunction; private readonly markersPane: string; @@ -679,6 +797,54 @@ export class TbMarkersDataLayer extends TbLatestMapDataLayer { + if (!this.removedPendingClusterLayers.has(layer)) { + result.extend((layer as L.Marker).getLatLng()); + } + }); + bounds = result; + } + return bounds; + } + + protected addItemsToContainer(items: TbLatestDataLayerItem[]): void { + if (this.settings.markerClustering?.enable) { + const layers = items.map(item => item.getLayer()); + if (this.settings.markerClustering.chunkedLoad && this.map.getMap().hasLayer(this.markersClusterContainer)) { + layers.forEach(layer => this.pendingClusterLayers.add(layer)); + } + try { + this.markersClusterContainer.addLayers(layers); + } catch (e) { + console.warn(e); + } + items.forEach(item => item.onAddedToContainer()); + } else { + super.addItemsToContainer(items); + } + } + + private onClusterLayerAdded(layer: L.Layer) { + if (this.pendingClusterLayers.delete(layer) && this.removedPendingClusterLayers.delete(layer)) { + Promise.resolve().then(() => this.markersClusterContainer.removeLayer(layer)); + } + } + private createMarkersClusterContainer(): L.FeatureGroup { const markerClusterOptions: L.MarkerClusterGroupOptions = { spiderfyOnMaxZoom: this.settings.markerClustering?.spiderfyOnMaxZoom, @@ -729,6 +895,7 @@ export class TbMarkersDataLayer extends TbLatestMapDataLayer this.onClusterLayerAdded(e.layer)); return this.markersClusterContainer; } diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/polygons-data-layer.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/polygons-data-layer.ts index 061825d758..0942e0dcdb 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/polygons-data-layer.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/polygons-data-layer.ts @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 import { defaultBasePolygonsDataLayerSettings, isCutPolygon, isJSON, MapDataLayerType, @@ -8,9 +9,9 @@ import { } from '@shared/models/widget/maps/map.models'; import L from 'leaflet'; import { DataKey, FormattedData } from '@shared/models/widget.models'; -import { ShapeStyleInfo, TbShapesDataLayer } from '@home/components/widget/lib/maps/data-layer/shapes-data-layer'; +import { isSameShapeStyle, ShapeStyleInfo, TbShapesDataLayer } from '@home/components/widget/lib/maps/data-layer/shapes-data-layer'; import { TbMap } from '@home/components/widget/lib/maps/map'; -import { Observable } from 'rxjs'; +import { Observable, Subscription } from 'rxjs'; import { isNotEmptyStr, isString } from '@core/utils'; import { TbLatestDataLayerItem, @@ -23,7 +24,10 @@ class TbPolygonDataLayerItem extends TbLatestDataLayerItem, dsData: FormattedData[], @@ -41,6 +45,7 @@ class TbPolygonDataLayerItem extends TbLatestDataLayerItem, dsData: FormattedData[]): L.Layer { const polyData = this.dataLayer.extractPolygonCoordinates(data); + this.appliedGeometryKey = this.geometryKey(data); const polyConstructor = isCutPolygon(polyData) || polyData.length !== 2 ? L.polygon : L.rectangle; this.polygon = polyConstructor(polyData as (TbPolygonRawCoordinates & L.LatLngTuple[]), { noClip: true, @@ -56,7 +62,7 @@ class TbPolygonDataLayerItem extends TbLatestDataLayerItem { + this.styleSubscription = this.dataLayer.getShapeStyle(data, dsData, this.polygonStyleInfo?.patternId).subscribe((styleInfo) => { this.polygonStyleInfo = styleInfo; if (this.polygon) { this.polygon.setStyle(this.polygonStyleInfo.style); @@ -80,19 +86,21 @@ class TbPolygonDataLayerItem extends TbLatestDataLayerItem, dsData: FormattedData[]): void { - this.dataLayer.getShapeStyle(data, dsData, this.polygonStyleInfo?.patternId).subscribe((styleInfo) => { + this.styleSubscription?.unsubscribe(); + this.styleSubscription = this.dataLayer.getShapeStyle(data, dsData, this.polygonStyleInfo?.patternId).subscribe((styleInfo) => { + const styleChanged = !isSameShapeStyle(this.polygonStyleInfo, styleInfo); this.polygonStyleInfo = styleInfo; - this.updatePolygonShape(data); + const geometryChanged = this.updatePolygonShape(data); this.updateTooltip(data, dsData); - this.updateLabel(data, dsData); - if (!this.editing || !this.dataLayer.getMap().getMap().pm.globalCutModeEnabled()) { + this.updateLabel(data, dsData, geometryChanged); + if (styleChanged && (!this.editing || !this.dataLayer.getMap().getMap().pm.globalCutModeEnabled())) { this.polygon.setStyle(this.polygonStyleInfo.style); } }); } protected doInvalidateCoordinates(data: FormattedData, dsData: FormattedData[]): void { - this.updatePolygonShape(data); + this.updatePolygonShape(data, true); this.updateLabel(data, dsData); } @@ -130,6 +138,7 @@ class TbPolygonDataLayerItem extends TbLatestDataLayerItem): string { + const rawPolyData = data[this.settings.polygonKey.label]; + return isString(rawPolyData) ? rawPolyData : JSON.stringify(rawPolyData); } - private updatePolygonShape(data: FormattedData) { + private updatePolygonShape(data: FormattedData, force = false): boolean { if (this.editing) { - return; + this.pendingGeometryUpdate = true; + this.markDataStale(); + return false; + } + const geometryKey = this.geometryKey(data); + if (!force && geometryKey === this.appliedGeometryKey) { + return false; } + this.appliedGeometryKey = geometryKey; const polyData = this.dataLayer.extractPolygonCoordinates(data) as TbPolyData; if (isCutPolygon(polyData) || polyData.length !== 2) { if (this.polygon instanceof L.Rectangle) { @@ -354,6 +387,7 @@ class TbPolygonDataLayerItem extends TbLatestDataLayerItem, dsData: FormattedData[], @@ -46,6 +50,7 @@ class TbPolylineDataLayerItem extends TbLatestDataLayerItem, dsData: FormattedData[]): L.Layer { const polyData = this.dataLayer.extractPolylineCoordinates(data); + this.appliedGeometryKey = this.geometryKey(data); const polyConstructor = L.polyline; this.polyline = polyConstructor(polyData as (TbPolylineRawCoordinates & L.LatLngTuple[]), { noClip: true, @@ -61,7 +67,7 @@ class TbPolylineDataLayerItem extends TbLatestDataLayerItem { + this.styleSubscription = this.dataLayer.getStrokeStyle(data, dsData, this.polylineStyleInfo?.patternId).subscribe((styleInfo) => { this.polylineStyleInfo = styleInfo; if (this.polyline) { this.polyline.setStyle(this.polylineStyleInfo.style); @@ -85,20 +91,23 @@ class TbPolylineDataLayerItem extends TbLatestDataLayerItem, dsData: FormattedData[]): void { - this.dataLayer.getStrokeStyle(data, dsData, this.polylineStyleInfo?.patternId).subscribe((styleInfo) => { + this.styleSubscription?.unsubscribe(); + this.styleSubscription = this.dataLayer.getStrokeStyle(data, dsData, this.polylineStyleInfo?.patternId).subscribe((styleInfo) => { + const styleChanged = !isSameShapeStyle(this.polylineStyleInfo, styleInfo); this.polylineStyleInfo = styleInfo; - this.updatePolylineShape(data); + const geometryChanged = this.updatePolylineShape(data); this.updateTooltip(data, dsData); - this.updateLabel(data, dsData); + this.updateLabel(data, dsData, geometryChanged); - if (!this.editing || !this.dataLayer.getMap().getMap().pm.globalCutModeEnabled()) { + if (styleChanged && (!this.editing || !this.dataLayer.getMap().getMap().pm.globalCutModeEnabled())) { this.polyline.setStyle(this.polylineStyleInfo.style); } }); } - protected doInvalidateCoordinates(data: FormattedData, _dsData: FormattedData[]): void { - this.updatePolylineShape(data); + protected doInvalidateCoordinates(data: FormattedData, dsData: FormattedData[]): void { + this.updatePolylineShape(data, true); + this.updateLabel(data, dsData); } protected addItemClass(clazz: string): void { @@ -135,6 +144,7 @@ class TbPolylineDataLayerItem extends TbLatestDataLayerItem): string { + const rawPolyData = data[this.settings.polylineKey.label]; + return isString(rawPolyData) ? rawPolyData : JSON.stringify(rawPolyData); } - private updatePolylineShape(data: FormattedData) { + private updatePolylineShape(data: FormattedData, force = false): boolean { if (this.editing) { - return; + this.pendingGeometryUpdate = true; + this.markDataStale(); + return false; } + const geometryKey = this.geometryKey(data); + if (!force && geometryKey === this.appliedGeometryKey) { + return false; + } + this.appliedGeometryKey = geometryKey; const polyData = this.dataLayer.extractPolylineCoordinates(data) as TbPolylineData; if (this.polyline instanceof L.Polyline && !(this.polyline instanceof L.Rectangle)) { @@ -376,6 +410,7 @@ class TbPolylineDataLayerItem extends TbLatestDataLayerItem { + if (!a || !b) { + return false; + } + if (a === b) { + return true; + } + if (a.patternId !== b.patternId) { + return false; + } + const aKeys = Object.keys(a.style); + const bKeys = Object.keys(b.style); + return aKeys.length === bKeys.length && aKeys.every(key => a.style[key] === b.style[key]); +}; + abstract class ShapePatternProcessor { static fromSettings(dataLayer: TbMapDataLayer, diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/trips-data-layer.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/trips-data-layer.ts index 0883049517..a8fb0d7647 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/trips-data-layer.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps/data-layer/trips-data-layer.ts @@ -7,15 +7,16 @@ import { defaultBaseTripsDataLayerSettings, findRotationAngle, interpolateLineSegment, - MapDataLayerType, MarkerType, + MapBooleanFunction, + MapDataLayerType, MarkerIconInfo, MarkerType, TbMapDatasource, TripsDataLayerSettings } from '@shared/models/widget/maps/map.models'; -import { forkJoin, Observable } from 'rxjs'; +import { forkJoin, Observable, Subscription } from 'rxjs'; import { DataKey, FormattedData, WidgetActionType } from '@shared/models/widget.models'; import { map } from 'rxjs/operators'; import L from 'leaflet'; -import { deepClone, isDefined, isUndefined, plainColorFromVariable } from '@core/utils'; +import { deepClone, isDefined, isEqual, isUndefined, plainColorFromVariable } from '@core/utils'; import { TbMap } from '@home/components/widget/lib/maps/map'; import { DataKeyType } from '@shared/models/telemetry/telemetry.models'; import moment from 'moment/moment'; @@ -27,7 +28,13 @@ import { TbDataLayerItem, TbMapDataLayer } from '@home/components/widget/lib/maps/data-layer/map-data-layer'; -import { MarkerDataProcessor } from '@home/components/widget/lib/maps/data-layer/markers-data-layer'; +import { + createPlaceholderMarkerIcon, + isRotationOnlyIconChange, + isSameMarkerIcon, + MarkerDataProcessor +} from '@home/components/widget/lib/maps/data-layer/markers-data-layer'; +import { CompiledTbFunction } from '@shared/models/js-function.models'; type TripRouteData = {[time: number]: FormattedData}; @@ -39,13 +46,19 @@ export interface PointItem { class TbTripDataItem extends TbDataLayerItem { private tripRouteData: TripRouteData; + private timePoints: number[]; private marker: L.Marker; private markerTooltip: L.Popup; + private markerIconSubscription: Subscription; + private appliedIconInfo: MarkerIconInfo; private labelOffset: L.PointTuple; + private labelContent: string; + private boundLabelOffset: L.PointTuple; private polyline: L.Polyline; private polylineDecorator: L.PolylineDecorator; + private appliedPathColor: string; private pointsContainer: L.FeatureGroup; private points = new Map(); @@ -102,7 +115,7 @@ class TbTripDataItem extends TbDataLayerItem this.dataLayer.getMap().getLocationSnapFilterFunction().execute(data[1], dsData)) - .map(data => parseInt(data[0], 10)); + public calculateAnchors(snapFilter: CompiledTbFunction, + dsData: FormattedData[]): number[] { + return this.timePoints.filter(time => snapFilter.execute(this.tripRouteData[time], dsData)); } private create() { @@ -157,6 +169,7 @@ class TbTripDataItem extends TbDataLayerItem, dsData: FormattedData[]) { if (this.settings.showMarker && this.marker) { - this.dataLayer.dataProcessor.createMarkerIcon(data, dsData, data.rotationAngle).subscribe( + this.markerIconSubscription?.unsubscribe(); + this.markerIconSubscription = this.dataLayer.dataProcessor.createMarkerIcon(data, dsData, data.rotationAngle).subscribe( (iconInfo) => { - const options = deepClone(iconInfo.icon.options); - this.marker.setIcon(iconInfo.icon); - const anchor = 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.dataLayer.markerOffset[1] + 10]; + if (!isSameMarkerIcon(this.appliedIconInfo, iconInfo)) { + const rotatedElement = this.marker.getElement()?.firstElementChild as HTMLElement; + if (rotatedElement && isRotationOnlyIconChange(this.appliedIconInfo, iconInfo)) { + rotatedElement.style.transform = `rotate(${data.rotationAngle}deg)`; + this.marker.options.icon = iconInfo.icon; + } else { + const options = deepClone(iconInfo.icon.options); + this.marker.setIcon(iconInfo.icon); + const anchor = 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.dataLayer.markerOffset[1] + 10]; + } + } + this.appliedIconInfo = iconInfo; } this.updateMarkerLabel(data, dsData); } @@ -329,11 +356,20 @@ class TbTripDataItem extends TbDataLayerItem, dsData: FormattedData[]) { if (this.settings.label.show) { - this.marker.unbindTooltip(); const label = this.dataLayer.dataLayerLabelProcessor.processPattern(data, dsData); const labelColor = this.dataLayer.getCtx().widgetConfig.color; - const content: L.Content = `
${label}
`; - this.marker.bindTooltip(content, { className: 'tb-marker-label', permanent: true, direction: 'top', offset: this.labelOffset }); + const content = `
${label}
`; + const offsetChanged = !isEqual(this.boundLabelOffset, this.labelOffset); + if (this.marker.getTooltip() && !offsetChanged) { + if (content !== this.labelContent) { + this.marker.setTooltipContent(content); + } + } else { + this.marker.unbindTooltip(); + this.marker.bindTooltip(content, { className: 'tb-marker-label', permanent: true, direction: 'top', offset: this.labelOffset }); + } + this.labelContent = content; + this.boundLabelOffset = this.labelOffset; } } @@ -386,6 +422,7 @@ class TbTripDataItem extends TbDataLayerItem a - b); return result; } @@ -394,19 +431,17 @@ class TbTripDataItem extends TbDataLayerItem parseInt(item, 10)); - for (let i = 1; i < timePoints.length; i++) { - if (timePoints[i - 1] < this.currentTime && timePoints[i] > this.currentTime) { - const beforePosition = this.tripRouteData[timePoints[i - 1]]; - const afterPosition = this.tripRouteData[timePoints[i]]; - const ratio = calculateInterpolationRatio(timePoints[i - 1], timePoints[i], this.currentTime); - currentPosition = { - ...beforePosition, - time: this.currentTime, - ...interpolateLineSegment(beforePosition, afterPosition, this.settings.xKey.label, this.settings.yKey.label, ratio) - }; - break; - } + const timePoints = this.timePoints; + const i = this.findLastTimePointBefore(this.currentTime); + if (i >= 0 && i + 1 < timePoints.length && timePoints[i + 1] > this.currentTime) { + const beforePosition = this.tripRouteData[timePoints[i]]; + const afterPosition = this.tripRouteData[timePoints[i + 1]]; + const ratio = calculateInterpolationRatio(timePoints[i], timePoints[i + 1], this.currentTime); + currentPosition = { + ...beforePosition, + time: this.currentTime, + ...interpolateLineSegment(beforePosition, afterPosition, this.settings.xKey.label, this.settings.yKey.label, ratio) + }; } } if (!currentPosition) { @@ -416,6 +451,22 @@ class TbTripDataItem extends TbDataLayerItem> 1; + if (this.timePoints[mid] < time) { + result = mid; + low = mid + 1; + } else { + high = mid - 1; + } + } + return result; + } + } export class TbTripsDataLayer extends TbMapDataLayer { @@ -430,7 +481,7 @@ export class TbTripsDataLayer extends TbMapDataLayer[][]; - private latestTripsData: FormattedData[]; + private latestTripsDataByEntity = new Map>(); constructor(protected map: TbMap, inputSettings: TripsDataLayerSettings) { @@ -451,7 +502,7 @@ export class TbTripsDataLayer extends TbMapDataLayer !!d.length && d[0].$datasource.mapDataIds.includes(this.mapDataId)).map( item => this.clearIncorrectFirsLastDatapoint(item)).filter(arr => arr.length); - this.latestTripsData = tripsLatestData.filter(d => d.$datasource.mapDataIds.includes(this.mapDataId)); + this.setLatestTripsData(tripsLatestData); this.rawTripsData.forEach((dataSource) => { minTime = Math.min(dataSource[0].time, minTime); maxTime = Math.max(dataSource[dataSource.length - 1].time, maxTime); @@ -467,7 +518,7 @@ export class TbTripsDataLayer extends TbMapDataLayer d.entityId === entityId); + const latestData = this.latestTripsDataByEntity.get(entityId); tripItem = new TbTripDataItem(rawTripData, latestData, this.settings, this); this.layerItems.set(entityId, tripItem); } @@ -479,10 +530,9 @@ export class TbTripsDataLayer extends TbMapDataLayer[]) { - this.latestTripsData = tripsLatestData.filter(d => d.$datasource.mapDataIds.includes(this.mapDataId)); + this.setLatestTripsData(tripsLatestData); this.layerItems.forEach((item, entityId) => { - const latestData = this.latestTripsData.find(d => d.entityId === entityId); - item.updateLatestData(latestData); + item.updateLatestData(this.latestTripsDataByEntity.get(entityId)); }); } @@ -499,12 +549,13 @@ export class TbTripsDataLayer extends TbMapDataLayer(); + const snapFilter = this.map.getLocationSnapFilterFunction(); + const dsData = this.map.getData(); this.layerItems.forEach(item => { - const tripAnchors = item.calculateAnchors(); - anchors = [...new Set([...anchors, ...tripAnchors])]; + item.calculateAnchors(snapFilter, dsData).forEach(anchor => anchors.add(anchor)); }); - return anchors; + return [...anchors]; } public getPathStyle(data: FormattedData, dsData: FormattedData[]): L.PolylineOptions { @@ -616,6 +667,15 @@ export class TbTripsDataLayer extends TbMapDataLayer null)); } + private setLatestTripsData(tripsLatestData: FormattedData[]) { + this.latestTripsDataByEntity.clear(); + for (const data of tripsLatestData) { + if (data.$datasource.mapDataIds.includes(this.mapDataId) && !this.latestTripsDataByEntity.has(data.entityId)) { + this.latestTripsDataByEntity.set(data.entityId, data); + } + } + } + private clearIncorrectFirsLastDatapoint(dataSource: FormattedData[]): FormattedData[] { const firstValidIndex = dataSource.findIndex(this.hasValidLocation); if (firstValidIndex === -1) { diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps/leaflet/leaflet-tb.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps/leaflet/leaflet-tb.ts index e364ee804e..8750833cc4 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/maps/leaflet/leaflet-tb.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps/leaflet/leaflet-tb.ts @@ -5,7 +5,7 @@ import L, { TB } from 'leaflet'; import { guid, isDefinedAndNotNull, isNotEmptyStr } from '@core/utils'; import 'leaflet-providers'; import { GestureHandling } from 'leaflet-gesture-handling'; -import { Map as MapLibreGLMap, setWorkerUrl } from 'maplibre-gl'; +import { LngLat, Map as MapLibreGLMap, setWorkerUrl } from 'maplibre-gl'; import '@geoman-io/leaflet-geoman-free'; import 'leaflet.markercluster'; import { MatIconRegistry } from '@angular/material/icon'; @@ -1094,7 +1094,11 @@ const chinaProvider = (type: string, options?: L.TileLayerOptions): L.TB.TileLay setWorkerUrl(new URL('assets/maplibre-gl/maplibre-gl-worker.mjs', document.baseURI).href); // Same as MapLibre's own default maxZoom -const MAP_LIBRE_GL_DEFAULT_MAX_ZOOM = 22; +const mapLibreGlDefaultMaxZoom = 22; +// Web Mercator latitude limit +const mapLibreGlMaxLatitude = 85.051129; +// MapLibre renders the world plus 3 copies on each side; longitude limit in degrees +const mapLibreGlMaxLongitude = 180 + 3 * 360; class MapLibreGLLayer extends L.Layer implements TB.MapLibreGL.MapLibreGLLayer { @@ -1107,11 +1111,13 @@ class MapLibreGLLayer extends L.Layer implements TB.MapLibreGL.MapLibreGLLayer { private _offset: L.Point; private _zooming: boolean; private _glError = false; + private _ownMaxBounds: L.LatLngBounds; + private _prevMaxBoundsViscosity: number; constructor(options: TB.MapLibreGL.LeafletMapLibreGLMapOptions) { super(); options = { - maxZoom: MAP_LIBRE_GL_DEFAULT_MAX_ZOOM, + maxZoom: mapLibreGlDefaultMaxZoom, ...options, updateInterval: 32, padding: 0.1, @@ -1125,28 +1131,26 @@ class MapLibreGLLayer extends L.Layer implements TB.MapLibreGL.MapLibreGLLayer { } beforeAdd(map: L.Map): this { - map._addZoomLimit(this); + if (!this.options.overlay) { + map._addZoomLimit(this); + } return this; } onAdd(map: L.Map): this { - let update = false; if (!this._container) { this._initContainer(); - } else { - update = true; } const paneName = this.getPaneName(); map.getPane(paneName).appendChild(this._container); this._initGL(); + this._limitPan(map); this._offset = this._map.containerPointToLayerPoint([0, 0]); if ((this._map as any)._proxy && map.options.zoomAnimation) { L.DomEvent.on((map as any)._proxy, L.DomUtil.TRANSITION_END, this._transitionEnd, this); } - if (update) { - this._update(); - } + this._update(); return this; } @@ -1157,6 +1161,7 @@ class MapLibreGLLayer extends L.Layer implements TB.MapLibreGL.MapLibreGLLayer { const paneName = this.getPaneName(); map.getPane(paneName).removeChild(this._container); map._removeZoomLimit(this); + this._releasePan(map); if (this._glMap) { this._glMap.remove(); @@ -1221,13 +1226,16 @@ class MapLibreGLLayer extends L.Layer implements TB.MapLibreGL.MapLibreGLLayer { } private _initGL() { - const center = this._map.getCenter(); const options = L.extend({}, this.options, { container: this._container, - center: [center.lng, center.lat], + center: this._getGLCenter(), zoom: this._map.getZoom() - 1, - attributionControl: false + attributionControl: false, + transformConstrain: (lngLat: LngLat, zoom: number) => ({center: lngLat, zoom}) }); + delete options.minZoom; + delete options.maxZoom; + delete options.overlay; this._glError = false; try { this._glMap = new MapLibreGLMap(options); @@ -1276,30 +1284,68 @@ class MapLibreGLLayer extends L.Layer implements TB.MapLibreGL.MapLibreGLLayer { offset = this._map.getSize().multiplyBy(this.options.padding), topLeft = this._map.containerPointToLayerPoint([0, 0]).subtract(offset); - L.DomUtil.setPosition(container, this._roundPoint(topLeft)); - - this._transformGL(gl); - if (container.clientWidth !== size.x || container.clientHeight !== size.y) { container.style.width = size.x + 'px'; container.style.height = size.y + 'px'; gl.resize(); } + + this._transformGL(gl); + + L.DomUtil.setPosition(container, this._roundPoint(topLeft.add([0, this._getGLCenterOffsetY()]))); } private _transformGL(gl: MapLibreGLMap) { - const center = this._map.getCenter(); gl.jumpTo({ - center: [center.lng, center.lat], + center: this._getGLCenter(), zoom: this._map.getZoom() - 1 }); } + private _getGLCenter(): LngLat { + const center = this._map.getCenter(); + const lat = Math.max(-mapLibreGlMaxLatitude, Math.min(mapLibreGlMaxLatitude, center.lat)); + return new LngLat(center.lng, lat); + } + + private _getGLCenterOffsetY(): number { + const glCenter = this._getGLCenter(); + const centerPoint = this._map.containerPointToLayerPoint(this._map.getSize().divideBy(2)); + const glCenterPoint = this._map.latLngToLayerPoint([glCenter.lat, glCenter.lng]); + const offsetY = glCenterPoint.y - centerPoint.y; + return Number.isFinite(offsetY) ? offsetY : 0; + } + + private _limitPan(map: L.Map) { + if (!this.options.overlay && !map.options.maxBounds) { + this._ownMaxBounds = L.latLngBounds([-mapLibreGlMaxLatitude, -mapLibreGlMaxLongitude], + [mapLibreGlMaxLatitude, mapLibreGlMaxLongitude]); + this._prevMaxBoundsViscosity = map.options.maxBoundsViscosity; + map.options.maxBoundsViscosity = 1; + map.setMaxBounds(this._ownMaxBounds); + } + } + + private _releasePan(map: L.Map) { + if (this._ownMaxBounds && map.options.maxBounds === this._ownMaxBounds) { + map.setMaxBounds(null); + map.options.maxBoundsViscosity = this._prevMaxBoundsViscosity; + let handedOff = false; + map.eachLayer((layer) => { + if (!handedOff && layer !== this && layer instanceof MapLibreGLLayer && !layer.options.overlay) { + layer._limitPan(map); + handedOff = true; + } + }); + } + this._ownMaxBounds = null; + } + private _pinchZoom() { if (!this._glReady()) { return; } this._glMap.jumpTo({ zoom: this._map.getZoom() - 1, - center: this._map.getCenter() + center: this._getGLCenter() }); } @@ -1345,7 +1391,7 @@ class MapLibreGLLayer extends L.Layer implements TB.MapLibreGL.MapLibreGLLayer { L.Util.requestAnimFrame(() => { if (!this._glReady()) { return; } const zoom = this._map.getZoom(); - const center = this._map.getCenter(); + const center = this._getGLCenter(); const offset = this._map.latLngToContainerPoint( this._map.getBounds().getNorthWest() ); diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps/map-layer.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps/map-layer.ts index 08590427a2..b38caf6ca7 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/maps/map-layer.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps/map-layer.ts @@ -250,8 +250,7 @@ export abstract class TbMapLayer { } return L.TB.MapLibreGL.mapLibreGLLayer({ style: this.referenceLayerStyle(spec), - // The reference layer is drawn over a raster base, so the base layer's zoom limit applies - maxZoom: undefined + overlay: true }); }) ); diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps/map.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps/map.ts index 68000d04b3..3fb99275bc 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/maps/map.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps/map.ts @@ -68,7 +68,7 @@ import { MapTimelinePanelComponent } from '@home/components/widget/lib/maps/pane import { ComponentRef } from '@angular/core'; import { TbTripsDataLayer } from '@home/components/widget/lib/maps/data-layer/trips-data-layer'; import { CompiledTbFunction } from '@shared/models/js-function.models'; -import { TbMapDataLayer } from '@home/components/widget/lib/maps/data-layer/map-data-layer'; +import { TbMapDataLayer, tbFunctionUsesAdditionalData } from '@home/components/widget/lib/maps/data-layer/map-data-layer'; import { EntityType } from '@shared/models/entity-type.models'; import { ShapePatternStorage } from '@home/components/widget/lib/maps/data-layer/shapes-data-layer'; import { TbPolylineDataLayer } from '@home/components/widget/lib/maps/data-layer/polylines-data-layer'; @@ -122,6 +122,7 @@ export abstract class TbMap { protected timeLineComponentRef: ComponentRef; protected timeLineComponent: MapTimelinePanelComponent; protected locationSnapFilterFunction: CompiledTbFunction; + private locationSnapFilterUsesAdditionalData = false; protected addMarkerDataLayers: TbLatestMapDataLayer[]; protected addPolygonDataLayers: TbLatestMapDataLayer[]; @@ -223,6 +224,7 @@ export abstract class TbMap { } const setup = [this.doSetupControls()]; if (this.timeline && this.settings.tripTimeline.snapToRealLocation) { + this.locationSnapFilterUsesAdditionalData = tbFunctionUsesAdditionalData(this.settings.tripTimeline.locationSnapFilter); setup.push(parseTbFunction(this.getCtx().http, this.settings.tripTimeline.locationSnapFilter, ['data', 'dsData']).pipe( map((parsed) => { this.locationSnapFilterFunction = parsed; @@ -964,7 +966,9 @@ export abstract class TbMap { undefined, undefined, el => el.datasource.entityId + el.datasource.mapDataIds[0]); this.latestDataLayers.forEach(dl => dl.updateData(this.dsData)); this.updateTripsAppearance(); - this.updateTripsAnchors(); + if (this.locationSnapFilterUsesAdditionalData) { + this.updateTripsAnchors(); + } this.updateBounds(); this.updateEditButtonsStates(); this.ctx.updateLabelPatterns(); @@ -1010,7 +1014,7 @@ export abstract class TbMap { } private updateTripsAppearance() { - this.tripDataLayers.forEach(dl => dl.updateAppearance()); + this.tripDataLayers.filter(dl => !dl.canSkipUnchangedItems()).forEach(dl => dl.updateAppearance()); } private updateTripsTime() { @@ -1021,13 +1025,12 @@ export abstract class TbMap { if (this.timeline) { if (this.settings.tripTimeline.snapToRealLocation) { // Recalculate anchors only for enabled layers - let anchors: number[] = []; + const anchorSet = new Set(); const enableTrips = this.tripDataLayers.filter(dl => dl.isEnabled()); for (const tripsDataLayer of enableTrips) { - const tripsAnchors = tripsDataLayer.calculateAnchors(); - anchors = [...new Set([...anchors, ...tripsAnchors])]; + tripsDataLayer.calculateAnchors().forEach(anchor => anchorSet.add(anchor)); } - anchors.sort((a, b) => a - b); + const anchors = [...anchorSet].sort((a, b) => a - b); this.timeLineComponent.anchors = anchors; } } diff --git a/ui-ngx/src/app/shared/models/widget/maps/map.models.ts b/ui-ngx/src/app/shared/models/widget/maps/map.models.ts index 9e61f525ee..4ddf681430 100644 --- a/ui-ngx/src/app/shared/models/widget/maps/map.models.ts +++ b/ui-ngx/src/app/shared/models/widget/maps/map.models.ts @@ -26,7 +26,7 @@ import { materialColors } from '@shared/models/material.models'; import type L from 'leaflet'; import { TbFunction } from '@shared/models/js-function.models'; import { Observable, Observer, of, switchMap } from 'rxjs'; -import { map } from 'rxjs/operators'; +import { finalize, map, shareReplay } from 'rxjs/operators'; import { ImagePipe } from '@shared/pipe/image.pipe'; import { MarkerIconContainer, MarkerShape } from '@shared/models/widget/maps/marker-shape.models'; import { ColorRange, DateFormatSettings, simpleDateFormat } from '@shared/models/widget-settings.models'; @@ -1561,28 +1561,40 @@ const mergeMapDatasource = (target: TbMapDatasource, source: TbMapDatasource): T } const imageAspectMap: {[key: string]: ImageWithAspect} = {}; +const imageAspectLoading: {[key: string]: Observable} = {}; -const imageLoader = (imageUrl: string): Observable => new Observable((observer: Observer) => { - const image = document.createElement('img'); // support IE +const measureAttachedImage = (image: HTMLImageElement): [number, number] => { image.style.position = 'absolute'; image.style.left = '-99999px'; image.style.top = '-99999px'; - image.onload = () => { - observer.next(image); - document.body.removeChild(image); - observer.complete(); - }; - image.onerror = err => { - observer.error(err); - document.body.removeChild(image); - observer.complete(); - }; document.body.appendChild(image); - image.src = imageUrl; -}); + const size: [number, number] = [image.width, image.height]; + image.remove(); + return size; +}; export const loadImageSize = (imageUrl: string): Observable<[number, number]> => - imageLoader(imageUrl).pipe(map(image => [image.width, image.height])); + new Observable((observer: Observer<[number, number]>) => { + const image = new Image(); + image.onload = () => { + if (image.naturalWidth > 0 && image.naturalHeight > 0) { + observer.next([image.naturalWidth, image.naturalHeight]); + } else { + observer.next(measureAttachedImage(image)); + } + observer.complete(); + }; + image.onerror = err => { + observer.error(err); + }; + image.src = imageUrl; + return () => { + image.remove(); + if (!image.complete) { + image.removeAttribute('src'); + } + }; + }); export interface ImageWithAspect { url: string; @@ -1592,32 +1604,37 @@ export interface ImageWithAspect { } export const loadImageWithAspect = (imagePipe: ImagePipe, imageUrl: string): Observable => { - if (imageUrl?.length) { - const hash = hashCode(imageUrl); - let imageWithAspect = imageAspectMap[hash]; - if (imageWithAspect) { - return of(imageWithAspect); - } else { - return imagePipe.transform(imageUrl, {asString: true, ignoreLoadingImage: true}).pipe( + if (!imageUrl?.length) { + return of(null); + } + const hash = hashCode(imageUrl); + const imageWithAspect = imageAspectMap[hash]; + if (imageWithAspect) { + return of(imageWithAspect); + } else { + let loading$ = imageAspectLoading[hash]; + if (!loading$) { + loading$ = imagePipe.transform(imageUrl, {asString: true, ignoreLoadingImage: true}).pipe( switchMap((res) => { const url = res as string; return loadImageSize(url).pipe( - map((size) => { - imageWithAspect = { - url, - width: size[0], - height: size[1], - aspect: size[0]/size[1] - }; + map(([width, height]) => { + const imageWithAspect: ImageWithAspect = {url, width, height, aspect: width / height}; imageAspectMap[hash] = imageWithAspect; return imageWithAspect; }) ); - }) + }), + finalize(() => { + if (imageAspectLoading[hash] === loading$) { + delete imageAspectLoading[hash]; + } + }), + shareReplay({bufferSize: 1, refCount: false}) ); + imageAspectLoading[hash] = loading$; } - } else { - return of(null); + return loading$; } }; diff --git a/ui-ngx/src/typings/leaflet-extend-tb.d.ts b/ui-ngx/src/typings/leaflet-extend-tb.d.ts index 34c2890b8c..afc264c17d 100644 --- a/ui-ngx/src/typings/leaflet-extend-tb.d.ts +++ b/ui-ngx/src/typings/leaflet-extend-tb.d.ts @@ -301,6 +301,7 @@ declare module 'leaflet' { interface LeafletMapLibreGLMapOptions extends L.InteractiveLayerOptions, Omit { updateInterval?: number; + overlay?: boolean; padding?: number; className?: string; }