100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Improved asset selection on Insights UI for scaling to larger instances (#2286)
Martin Peeters5befc37dee63
diff --git a/ui/app/shared/locales/en/or.json b/ui/app/shared/locales/en/or.jsonindex 472b430d1..afec07468 100644--- a/ui/app/shared/locales/en/or.json+++ b/ui/app/shared/locales/en/or.json@@ -7,6 +7,7 @@"asset": "Asset","asset_plural": "Assets","assets": "Assets",+ "allAssets": "All assets","allAssetsofType": "All assets of this type","attribute": "Attribute","attributes": "Attributes",diff --git a/ui/app/shared/locales/nl/or.json b/ui/app/shared/locales/nl/or.jsonindex ef1dea821..f95f7cb72 100644--- a/ui/app/shared/locales/nl/or.json+++ b/ui/app/shared/locales/nl/or.json@@ -7,6 +7,7 @@"asset": "Asset","asset_plural": "Assets","assets": "Assets",+ "allAssets": "Alle assets","allAssetsofType": "Alle assets van dit type","attribute": "Attribuut","attributes": "Attributen",diff --git a/ui/component/or-asset-tree/src/index.ts b/ui/component/or-asset-tree/src/index.tsindex 414531f65..b86f6fb82 100644--- a/ui/component/or-asset-tree/src/index.ts+++ b/ui/component/or-asset-tree/src/index.ts@@ -264,7 +264,7 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {public readonly rootAssetIds?: string[];@property({type: Object})- public readonly dataProvider?: () => Promise<Asset[]>;+ public readonly dataProvider?: (offset: number, limit: number, parentId?: string) => Promise<Asset[]>;@property({type: Boolean})public readonly readonly: boolean = false;@@ -287,6 +287,9 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {@property({type: Boolean})public showFilter: boolean = true;+ @property({type: Boolean})+ public showFilterIcon: boolean = true;+@property({type: String})public sortBy?: string = "name";@@ -488,34 +491,35 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {this._onFilterInput(this._filterInput.nativeValue);}, 200)}"></or-mwc-input>- <or-icon id="filterSettingsIcon" icon="${this._filterSettingOpen ? "window-close" : "tune"}" title="${i18next.t(this._filterSettingOpen ? "filter.close" : "filter.open")}" @click="${() => {- if (this._filterSettingOpen) {- this._filterSettingOpen = false;- } else {- this._filterSettingOpen = true;- // Avoid to build again the types- if (this._assetTypes.length === 0) {- let usedTypes: string[] = [];- const types = this._getAllowedChildTypes(this._selectedNodes[0]);- this._assetTypes = types.filter((t) => t.descriptorType === "asset");- }+ ${when(this.showFilterIcon, () => html`+ <or-icon id="filterSettingsIcon" icon="${this._filterSettingOpen ? "window-close" : "tune"}" title="${i18next.t(this._filterSettingOpen ? "filter.close" : "filter.open")}" @click="${() => {+ if (this._filterSettingOpen) {+ this._filterSettingOpen = false;+ } else {+ this._filterSettingOpen = true;+ // Avoid to build again the types+ if (this._assetTypes.length === 0) {+ const types = this._getAllowedChildTypes(this._selectedNodes[0]);+ this._assetTypes = types.filter((t) => t.descriptorType === "asset");+ }- if (this._filter.attribute.length > 0) {- this._attributeNameFilter.value = this._filter.attribute[0];- }+ if (this._filter.attribute.length > 0) {+ this._attributeNameFilter.value = this._filter.attribute[0];+ }- if (this._filter.attributeValue.length > 0 && this._filter.attribute.length > 0) {- this._attributeValueFilter.disabled = false;- this._attributeValueFilter.value = this._filter.attributeValue[0];- }+ if (this._filter.attributeValue.length > 0 && this._filter.attribute.length > 0) {+ this._attributeValueFilter.disabled = false;+ this._attributeValueFilter.value = this._filter.attributeValue[0];+ }- if (this._filter.assetType.length > 0) {- this._assetTypeFilter = this._filter.assetType[0];- } else {- this._assetTypeFilter = '';+ if (this._filter.assetType.length > 0) {+ this._assetTypeFilter = this._filter.assetType[0];+ } else {+ this._assetTypeFilter = '';+ }}- }- }}"></or-icon>+ }}"></or-icon>+ `)}</div><div id="asset-tree-filter-setting" class="${this._filterSettingOpen ? "visible" : ""}"><div class="advanced-filter">@@ -1750,7 +1754,7 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {this._loading = true;if(this.dataProvider) {- this.dataProvider().then(assets => {+ this.dataProvider(offset, this.queryLimit, parentId).then(assets => {this._loading = false;this._buildTreeNodes(assets);if(this._filterInput?.value) {diff --git a/ui/component/or-dashboard-builder/src/panels/assettypes-panel.ts b/ui/component/or-dashboard-builder/src/panels/assettypes-panel.tsindex 18b59430a..6c5205575 100644--- a/ui/component/or-dashboard-builder/src/panels/assettypes-panel.ts+++ b/ui/component/or-dashboard-builder/src/panels/assettypes-panel.ts@@ -1,11 +1,11 @@import {css, html, LitElement, PropertyValues, TemplateResult} from "lit";import {customElement, property, state} from "lit/decorators.js";-import {Asset, AssetDescriptor, AssetModelUtil, AssetQuery, AssetTypeInfo} from "@openremote/model";+import {AssetDescriptor, AssetModelUtil, AssetTypeInfo} from "@openremote/model";import {getContentWithMenuTemplate} from "@openremote/or-mwc-components/or-mwc-menu";import {i18next} from "@openremote/or-translate";import {ListItem} from "@openremote/or-mwc-components/or-mwc-list";import {InputType, OrInputChangedEvent} from "@openremote/or-mwc-components/or-mwc-input";-import manager, {Util} from "@openremote/core";+import {Util} from "@openremote/core";import {when} from "lit/directives/when.js";import {createRef, Ref, ref} from 'lit/directives/ref.js';import {AssetTreeConfig, OrAssetTree} from "@openremote/or-asset-tree";@@ -179,9 +179,10 @@ export class AssettypesPanel extends LitElement {<!-- Select one or more assets -->${when(this.config.assets?.enabled, () => {const assetIds = (typeof this.assetIds === 'string') ? [this.assetIds] : this.assetIds;+ const label = this.allOfType ? i18next.t("allAssets") : ((this.assetIds?.length || 0) + ' ' + i18next.t('assets'));return html`<div>- <or-mwc-input .type="${InputType.BUTTON}" .label="${(this.assetIds?.length || 0) + ' ' + i18next.t('assets')}" .disabled="${!this.assetType || this.allOfType}" fullWidth outlined comfortable style="width: 100%;"+ <or-mwc-input .type="${InputType.BUTTON}" label="${label}" .disabled="${!this.assetType || this.allOfType}" fullWidth outlined comfortable style="width: 100%;"@or-mwc-input-changed="${(ev: OrInputChangedEvent) => this._openAssetSelector(this.assetType!, assetIds, this.config.assets?.multi)}"></or-mwc-input></div>@@ -294,11 +295,16 @@ export class AssettypesPanel extends LitElement {} as AssetTreeConfigconst dialog = showDialog(new OrMwcDialog().setHeading(i18next.t("linkedAssets"))+ .setStyles(html`<style>+ or-asset-tree {+ min-height: 400px;+ max-height: 50vh;+ }+ </style>`).setContent(html`<div style="width: 400px;">- <or-asset-tree ${ref(assetTreeRef)} .dataProvider="${this.assetTreeDataProvider}" expandAllNodes- id="chart-asset-tree" readonly .config="${config}" .selectedIds="${assetIds}"- .showSortBtn="${false}" .showFilter="${false}" .checkboxes="${multi}"+ <or-asset-tree ${ref(assetTreeRef)} id="chart-asset-tree" readonly disableSubscribe .config="${config}" .selectedIds="${assetIds}"+ .showSortBtn="${false}" .showFilterIcon="${false}" .checkboxes="${multi}"></or-asset-tree></div>`)@@ -324,27 +330,7 @@ export class AssettypesPanel extends LitElement {}]).setDismissAction({- actionName: "cancel",+ actionName: "cancel"}));}-- protected assetTreeDataProvider = async (): Promise<Asset[]> => {- const assetQuery: AssetQuery = {- realm: {- name: manager.displayRealm- },- select: { // Just need the basic asset info- attributes: []- }- };- // At first, just fetch all accessible assets without attribute info...- const assets = (await manager.rest.api.AssetResource.queryAssets(assetQuery)).data;-- // After fetching, narrow down the list to assets with the same assetType.- // Since it is a tree, we also include the parents of those assets, based on the 'asset.path' variable.- const pathsOfAssetType = assets.filter(a => a.type === this.assetType).map(a => a.path!);- const filteredAssetIds = [...new Set([].concat(...pathsOfAssetType as any[]))] as string[];- return assets.filter(a => filteredAssetIds.includes(a.id!));- }-}diff --git a/ui/component/or-dashboard-builder/src/settings/map-settings.ts b/ui/component/or-dashboard-builder/src/settings/map-settings.tsindex 684831163..807d5fd91 100644--- a/ui/component/or-dashboard-builder/src/settings/map-settings.ts+++ b/ui/component/or-dashboard-builder/src/settings/map-settings.ts@@ -102,7 +102,7 @@ export class MapSettings extends AssetWidgetSettings {</settings-panel><!-- List of customizable thresholds -->- ${when(this.widgetConfig.assetIds.length > 0, () => html`+ ${when(this.widgetConfig.assetIds.length > 0 || this.widgetConfig.allOfType, () => html`<settings-panel displayName="thresholds" expanded="${true}"><thresholds-panel .thresholds="${this.widgetConfig.thresholds}".boolColors="${this.widgetConfig.boolColors}"@@ -175,19 +175,21 @@ export class MapSettings extends AssetWidgetSettings {realm: { name: manager.displayRealm },select: { attributes: [attrName, 'location'] },types: [this.widgetConfig.assetType!],- ids: ids+ ids: ids,+ limit: ids?.length ?? 1});- this.widgetConfig.assetIds = response.data.map((a) => a.id!);+ this.widgetConfig.assetIds = ids?.length ? response.data.map((a) => a.id!) : [];this.widgetConfig.valueType = response.data.length ? response.data[0].attributes![attrName].type : "text";if (!response.data[0].attributes![attrName].type) {- throw new TypeError("Data does not contain property 'attributes' or 'type'.")}+ throw new TypeError("Data does not contain property 'attributes' or 'type'.")+ }} catch (reason) {console.error(reason);if (reason instanceof TypeError) {showSnackbar(undefined, "noAttributesToShow");} else {showSnackbar(undefined, "errorOccurred");- }+ }}};diff --git a/ui/component/or-dashboard-builder/src/widgets/map-widget.ts b/ui/component/or-dashboard-builder/src/widgets/map-widget.tsindex 9d0b9d278..032efa675 100644--- a/ui/component/or-dashboard-builder/src/widgets/map-widget.ts+++ b/ui/component/or-dashboard-builder/src/widgets/map-widget.ts@@ -1,20 +1,14 @@import {html, PropertyValues, TemplateResult} from "lit";-import {customElement} from "lit/decorators.js";+import {customElement, query, state} from "lit/decorators.js";import {OrAssetWidget} from "../util/or-asset-widget";import {OrWidget, WidgetManifest} from "../util/or-widget";import {WidgetSettings} from "../util/widget-settings";import {MapSettings} from "../settings/map-settings";import {AssetWidgetConfig} from "../util/widget-config";-import {Asset, AssetDescriptor, Attribute, GeoJSONPoint, WellknownAttributes, WellknownMetaItems} from "@openremote/model";-import {- LngLatLike,- AttributeMarkerColours,- RangeAttributeMarkerColours,- AttributeMarkerColoursRange,- MapMarkerColours, MapMarkerAssetConfig,-} from "@openremote/or-map";-import {when} from "lit/directives/when.js";-import manager, {Util} from "@openremote/core";+import {Asset, AssetDescriptor} from "@openremote/model";+import {LngLatLike, MapMarkerColours, MapMarkerAssetConfig, Util as MapUtil, OrMap, AssetWithLocation, OrMapMarkersChangedEvent, MapMarkerConfig} from "@openremote/or-map";+import {map} from "lit/directives/map.js";+import manager from "@openremote/core";import { showSnackbar } from "@openremote/or-mwc-components/or-mwc-snackbar";import "@openremote/or-map";@@ -64,7 +58,13 @@ function getDefaultWidgetConfig(): MapWidgetConfig {@customElement("map-widget")export class MapWidget extends OrAssetWidget {- protected widgetConfig!: MapWidgetConfig+ protected widgetConfig!: MapWidgetConfig;++ @state()+ protected _assetsOnScreen: AssetWithLocation[] = [];++ @query("or-map")+ protected _map?: OrMap;private markers: MapMarkerAssetConfig = {};@@ -83,131 +83,128 @@ export class MapWidget extends OrAssetWidget {getDefaultConfig(): MapWidgetConfig {return getDefaultWidgetConfig();}- }+ };+ }++ connectedCallback() {+ this.addEventListener(OrMapMarkersChangedEvent.NAME, this._onMapMarkersChanged);+ return super.connectedCallback();+ }++ disconnectedCallback() {+ this.removeEventListener(OrMapMarkersChangedEvent.NAME, this._onMapMarkersChanged);+ return super.disconnectedCallback();}refreshContent(force: boolean): void {- this.loadAssets();+ this._loadAssets();}protected updated(changedProps: PropertyValues) {if(changedProps.has('widgetConfig') && this.widgetConfig) {- this.loadAssets();+ this._loadAssets();+ }+ if(changedProps.has("loadedAssets") && this.loadedAssets) {+ this._loadMarkers();}}- protected async loadAssets() {- if(this.widgetConfig.assetType && this.widgetConfig.attributeName && this.widgetConfig.allOfType) {- this.fetchAssetsByType([this.widgetConfig.assetType], this.widgetConfig.attributeName).then((assets) => {- this.loadedAssets = assets;- });- } else if(this.widgetConfig.assetType && this.widgetConfig.attributeName && !this.widgetConfig.allOfType) {- this.fetchAssetsById([this.widgetConfig.assetType], this.widgetConfig.attributeName, this.widgetConfig.assetIds).then((assets) => {- this.loadedAssets = assets;- });- }+ protected _loadAssets() {+ if(!this.widgetConfig.assetType || !this.widgetConfig.attributeName) {+ console.debug("Could not load assets for Map widget, as the configuration is not complete! (no asset type, or no attribute)");+ return;+ }+ this._fetchAssets([this.widgetConfig.assetType], this.widgetConfig.attributeName, this.widgetConfig.allOfType ? undefined : this.widgetConfig.assetIds).then(assets => {+ this.loadedAssets = assets;+ });}- protected async fetchAssetsById(assetTypes: string[], attributeName: string, assetIds: string[]) {+ protected async _fetchAssets(assetTypes: string[], attributeName: string, assetIds?: string[]): Promise<Asset[]> {let assets: Asset[] = [];- await manager.rest.api.AssetResource.queryAssets({- realm: {- name:manager.displayRealm- },- select: {- attributes: [attributeName, 'location']- },- types: assetTypes,- ids: assetIds,-- }).then(response => {- assets = response.data;- this.markers = {};- }).catch((reason) => {- console.error(reason);- showSnackbar(undefined, "errorOccurred");+ try {+ const response = await manager.rest.api.AssetResource.queryAssets({+ realm: {+ name: manager.displayRealm+ },+ select: {+ attributes: [attributeName, "location"]+ },+ types: assetTypes,+ ids: assetIds?.length ? assetIds : undefined});- return assets;- }-- protected async fetchAssetsByType(assetTypes: string[], attributeName: string) {- let assets: Asset[] = [];- await manager.rest.api.AssetResource.queryAssets({- realm: {- name: manager.displayRealm- },- select: {- attributes: [attributeName, 'location']- },- types: assetTypes,-- }).then(response => {assets = response.data;- this.markers = {};- }).catch((reason) => {++ } catch (reason) {console.error(reason);showSnackbar(undefined, "errorOccurred");- });+ }return assets;}-protected render(): TemplateResult {return html`<div style="height: 100%; display: flex; flex-direction: column; overflow: hidden;"><or-map id="miniMap" class="or-map" .zoom="${this.widgetConfig.zoom}" .center="${this.widgetConfig.center}" .showGeoJson="${this.widgetConfig.showGeoJson}" style="flex: 1;">- ${when(this.loadedAssets, () => {- return this.getMarkerTemplates();- })}+ ${map(this._assetsOnScreen, (asset) => html`+ <or-map-marker-asset .asset="${asset}" .config="${this.markers}"></or-map-marker-asset>+ `)}</or-map></div>`;}- protected getMarkerTemplates(): TemplateResult[] {- return this.loadedAssets.filter((asset: Asset) => {- if (!asset.attributes) {- return false;- }- const attr = asset.attributes[WellknownAttributes.LOCATION] as Attribute<GeoJSONPoint>;- return !attr || !attr.meta || !attr.meta.hasOwnProperty(WellknownMetaItems.SHOWONDASHBOARD) || !!Util.getMetaValue(WellknownMetaItems.SHOWONDASHBOARD, attr);- }).map(asset => {- if (this.markers) {- // Configure map marker asset settings- this.markers[asset.type!] = {attributeName: this.widgetConfig.attributeName!};- this.markers[asset.type!].showUnits = this.widgetConfig.showUnits;- this.markers[asset.type!].showLabel = this.widgetConfig.showLabels;- if (this.widgetConfig.valueType == 'boolean') {- (this.widgetConfig.boolColors as any).true = (this.widgetConfig.boolColors as any).true.replace("#", "");- (this.widgetConfig.boolColors as any).false = (this.widgetConfig.boolColors as any).false.replace("#", "");- this.markers[asset.type!].colours = this.widgetConfig.boolColors;- } else if (this.widgetConfig.valueType == 'text') {- var colors: AttributeMarkerColours = {type: 'string',};- (this.widgetConfig.textColors as [string, string][]).map((threshold) => {- colors[threshold[0] as string] = (threshold[1] as string).replace('#', '');- })- this.markers[asset.type!].colours = colors;- } else {- var ranges: AttributeMarkerColoursRange[] = [];- (this.widgetConfig.thresholds as [number, string][]).sort((x, y) => (x[0] > y[0]) ? -1 : 1).map((threshold, index) => {- var range: AttributeMarkerColoursRange = {- min: threshold[0],- colour: threshold[1].replace('#', '')- }- ranges.push(range);- })- var colorsNum: RangeAttributeMarkerColours = {- type: 'range',- ranges: ranges+ protected _onMapMarkersChanged(e: OrMapMarkersChangedEvent) {+ this._assetsOnScreen = e.detail;+ }++ protected _loadMarkers(): void {+ this.markers = {};++ // Loop through each asset type, and configure the marker+ for (const assetType of new Set(this.loadedAssets.map(a => a.type).filter(Boolean))) {+ const marker: MapMarkerConfig = {+ attributeName: this.widgetConfig.attributeName!,+ showUnits: this.widgetConfig.showUnits,+ showLabel: this.widgetConfig.showLabels+ };+ switch (this.widgetConfig.valueType) {+ case "boolean": {+ const boolColors = this.widgetConfig.boolColors as any;+ marker.colours = {+ type: "boolean",+ true: boolColors.true.replace("#", ""),+ false: boolColors.false.replace("#", "")+ };+ break;+ }+ case "text": {+ marker.colours = this.widgetConfig.textColors.reduce((colors: any, [key, val]) => {+ colors[key] = val.replace("#", "");+ return colors;+ }, { type: "string" });+ break;+ }+ default: {+ marker.colours = {+ type: "range",+ ranges: this.widgetConfig.thresholds+ .sort((a, b) => b[0] - a[0])+ .map(([min, colour]) => ({min, colour: colour.replace('#', '')}))};- this.markers[asset.type!].colours = colorsNum;+ break;}}- return html`- <or-map-marker-asset .asset="${asset}" .config="${this.markers}"></or-map-marker-asset>- `- })+ this.markers[assetType!] = marker;+ }+ // Load the markers onto the map+ if (this._map) {+ this._map.cleanUpAssetMarkers();+ const assetType = this.widgetConfig.allOfType ? undefined : this.widgetConfig.assetType;+ this.loadedAssets+ .filter(asset => MapUtil.isAssetWithLocation(asset) && (!assetType || asset.type === assetType))+ .forEach((asset: Asset) => this._map!.addAssetMarker(asset as AssetWithLocation));++ this._map?.reload();+ }}--}