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
UI updates: Insights Map Widget Created (#895)
NinaBianca0b0efbb4f8f0
diff --git a/manager/src/web/shared/locales/en/or.json b/manager/src/web/shared/locales/en/or.jsonindex 04a0358c0..99dfec88f 100644--- a/manager/src/web/shared/locales/en/or.json+++ b/manager/src/web/shared/locales/en/or.json@@ -548,6 +548,7 @@"screen": "Screen","uploadFile" : "Upload file","thresholds": "Thresholds",+ "threshold": "Threshold","noDashboardSelected": "Please select a dashboard on the left","noDashboardFound": "No dashboard could be found.","noDashboardWriteAccess": "You don't have access to edit this dashboard.",@@ -593,7 +594,11 @@"showValueAs": "Show value as","deleteWidget": "Delete widget","myDashboards": "My dashboards",- "createdByOthers": "Created by others"+ "createdByOthers": "Created by others",+ "showUnits": "Show units",+ "showLabels": "Show labels",+ "zoom": "Zoom",+ "center": "Center"},"appearance": "Appearance","configuration": {diff --git a/manager/src/web/shared/locales/nl/or.json b/manager/src/web/shared/locales/nl/or.jsonindex 96905139b..3f2f1e39e 100644--- a/manager/src/web/shared/locales/nl/or.json+++ b/manager/src/web/shared/locales/nl/or.json@@ -548,6 +548,7 @@"screen": "Scherm","uploadFile" : "Uploaden bestand","thresholds": "Drempelwaardes",+ "threshold": "Drempelwaarde","noDashboardSelected": "Selecteer een dashboard aan de linkerkant","noDashboardFound": "Geen dashboard gevonden.","noDashboardWriteAccess": "U heeft geen rechten om dit dashboard aan te passen.",@@ -593,7 +594,11 @@"showValueAs": "Laat waarde zien als","deleteWidget": "Verwijder widget","myDashboards": "Mijn dashboards",- "createdByOthers": "Gemaakt door anderen"+ "createdByOthers": "Gemaakt door anderen",+ "showUnits": "Toon eenheden",+ "showLabels": "Toon labels",+ "zoom": "Zoom",+ "center": "Middelpunt"},"appearance": "Weergave","configuration": {diff --git a/ui/component/core/src/util.ts b/ui/component/core/src/util.tsindex 85c728504..97a312626 100644--- a/ui/component/core/src/util.ts+++ b/ui/component/core/src/util.ts@@ -635,7 +635,7 @@ export function getValueAsString(value: any, formatProvider: () => ValueFormat |// Assume UNIX timestamp in msconst offset = (new Date()).getTimezoneOffset() * 60000;value = new Date(value - offset);- }+ }} else if (typeof(value) === "boolean" && format.asNumber) {value = value ? 1 : 0;}diff --git a/ui/component/or-dashboard-builder/src/index.ts b/ui/component/or-dashboard-builder/src/index.tsindex dc29a4cb3..faf1dae21 100644--- a/ui/component/or-dashboard-builder/src/index.ts+++ b/ui/component/or-dashboard-builder/src/index.ts@@ -32,6 +32,7 @@ import {OrWidgetEntity} from "./widgets/or-base-widget";import {OrChartWidget} from "./widgets/or-chart-widget";import { OrKpiWidget } from "./widgets/or-kpi-widget";import { OrGaugeWidget } from "./widgets/or-gauge-widget";+import {OrMapWidget} from "./widgets/or-map-widget";// language=CSSconst styling = css`@@ -283,6 +284,7 @@ export class OrDashboardBuilder extends LitElement {this.registerWidgetType("linechart", new OrChartWidget());this.registerWidgetType("kpi", new OrKpiWidget());this.registerWidgetType("gauge", new OrGaugeWidget());+ this.registerWidgetType("map", new OrMapWidget());this.updateComplete.then(async () => {await this.updateDashboards(this.realm!);diff --git a/ui/component/or-dashboard-builder/src/or-dashboard-settingspanel.ts b/ui/component/or-dashboard-builder/src/or-dashboard-settingspanel.tsindex 9fb9defd3..e0668c9a4 100644--- a/ui/component/or-dashboard-builder/src/or-dashboard-settingspanel.ts+++ b/ui/component/or-dashboard-builder/src/or-dashboard-settingspanel.ts@@ -1,16 +1,24 @@-import manager, { DefaultColor5, Util } from "@openremote/core";-import {Asset, AssetModelUtil, AttributeRef} from "@openremote/model";+import manager, {DefaultColor5, Util} from "@openremote/core";+import {+ Asset, AssetModelUtil, AttributeRef, AssetQuery, WellknownAssets,+ AssetDescriptor, WellknownMetaItems, GeoJSONPoint, WellknownAttributes,+ Attribute, AssetQueryOrderBy$Property, AssetTypeInfo,+} from "@openremote/model";import {OrAttributePicker, OrAttributePickerPickedEvent} from "@openremote/or-attribute-picker";import {getAssetDescriptorIconTemplate} from "@openremote/or-icon";+import "@openremote/or-mwc-components/or-mwc-menu";+import {getContentWithMenuTemplate} from "@openremote/or-mwc-components/or-mwc-menu";import {showDialog} from "@openremote/or-mwc-components/or-mwc-dialog";-import {InputType} from "@openremote/or-mwc-components/or-mwc-input";+import {InputType, OrInputChangedEvent} from "@openremote/or-mwc-components/or-mwc-input";+import {ListItem} from "@openremote/or-mwc-components/or-mwc-list";import {showSnackbar} from "@openremote/or-mwc-components/or-mwc-snackbar";import {i18next} from "@openremote/or-translate";-import {css, html, LitElement, unsafeCSS} from "lit";+import {css, html, LitElement, unsafeCSS, TemplateResult} from "lit";import {customElement, property, state} from "lit/decorators.js";-import { until } from "lit/directives/until.js";+import {until} from "lit/directives/until.js";import {OrWidgetConfig} from "./widgets/or-base-widget";import {style} from "./style";+import {ifDefined} from 'lit/directives/if-defined.js';//language=cssexport const widgetSettingsStyling = css`@@ -91,10 +99,9 @@ export const widgetSettingsStyling = css``export enum SettingsPanelType {- SINGLE_ATTRIBUTE, MULTI_ATTRIBUTE, THRESHOLDS,+ SINGLE_ATTRIBUTE, MULTI_ATTRIBUTE, THRESHOLDS, ASSETTYPES,}-@customElement('or-dashboard-settingspanel')export class OrDashboardSettingsPanel extends LitElement {@@ -103,6 +110,7 @@ export class OrDashboardSettingsPanel extends LitElement {@property()private readonly widgetConfig: OrWidgetConfig | any;+private _config?: OrWidgetConfig | any; // local duplicate that does not update parent. Sent back in dispatchEvent() only.@property({type: Boolean}) // used for SINGLE_ATTRIBUTE and MULTI_ATTRIBUTE types.@@ -115,16 +123,22 @@ export class OrDashboardSettingsPanel extends LitElement {return [style, widgetSettingsStyling];}+ @state()+ protected _loadedAssetTypes: AssetDescriptor[] = [];++ protected _allowedValueTypes: string[] = ["boolean", "number", "positiveInteger", "positiveNumber",+ "negativeInteger", "negativeNumber", "text"];+/* ---------------------------- */// Setting local duplicate config before triggering update,// and fetching assets if any of the AttributeRefs are not pulled yet.willUpdate(changedProperties: Map<string, any>) {- if(changedProperties.has("widgetConfig")) {- if(!this._config || (changedProperties.get("widgetConfig") != this._config) && this.widgetConfig.attributeRefs) {+ if (changedProperties.has("widgetConfig")) {+ if (!this._config || (changedProperties.get("widgetConfig") != this._config) && this.widgetConfig.attributeRefs) {const loadedRefs: AttributeRef[] = this.widgetConfig.attributeRefs.filter((attrRef: AttributeRef) => this.isAttributeRefLoaded(attrRef));- if(loadedRefs.length != this.widgetConfig.attributeRefs.length) {+ if (loadedRefs.length != this.widgetConfig.attributeRefs.length) {this.fetchAssets(this.widgetConfig).then(assets => {this.loadedAssets = assets;});@@ -150,6 +164,16 @@ export class OrDashboardSettingsPanel extends LitElement {`;}}+ case SettingsPanelType.ASSETTYPES: {+ if (!this._config.assetTypes) {+ return html`<span>${i18next.t('errorOccurred')}</span>`;+ } else {+ return html`+ ${until(this.getAssettypesHTML(this._config), html`${i18next.t('loading')}`)}+ `;+ }+ }+case SettingsPanelType.THRESHOLDS: {if (!this._config.thresholds) {return html`<span>${i18next.t('errorOccurred')}</span>`;@@ -184,7 +208,7 @@ export class OrDashboardSettingsPanel extends LitElement {const asset = this.loadedAssets?.find((x: Asset) => {return x.id == attributeRef.id;}) as Asset;- if(asset) {+ if (asset) {const attribute = asset.attributes![attributeRef.name!];const descriptors = AssetModelUtil.getAttributeAndValueDescriptors(asset.type, attributeRef.name, attribute);const label = Util.getAttributeLabel(attribute, descriptors[0], asset.type, true);@@ -195,7 +219,8 @@ export class OrDashboardSettingsPanel extends LitElement {<span>${asset.name}</span><span style="font-size:14px; color:grey;">${label}</span></div>- <button class="button-clear" @click="${() => this.removeWidgetAttribute(attributeRef)}">+ <button class="button-clear"+ @click="${() => this.removeWidgetAttribute(attributeRef)}"><or-icon icon="close-circle"></or-icon></button></div>@@ -271,64 +296,340 @@ export class OrDashboardSettingsPanel extends LitElement {}-/* ---------------------------------------------------- */async getThresholdsHTML(config: OrWidgetConfig | any) {- if(config.thresholds) {+ if (config.thresholds && config.valueType) {return html`<div id="thresholds-list" style="padding: 0 14px 12px 14px;">- ${(config.thresholds as [number, string][]).sort((x, y) => (x[0] < y[0]) ? -1 : 1).map((threshold, index) => {- return html`- <div class="threshold-list-item" style="padding: 8px 0; display: flex; flex-direction: row; align-items: center;">- <div style="height: 100%; padding: 8px 14px 8px 0;">- <or-mwc-input type="${InputType.COLOUR}" value="${threshold[1]}" style="width: 32px; height: 32px;"+ ${(config.valueType === 'number' || config.valueType === 'positiveInteger'+ || config.valueType === 'positiveNumber' || config.valueType === 'negativeInteger'+ || config.valueType === 'negativeNumber') ? html`+ ${(config.thresholds as [number, string][]).sort((x, y) => (x[0] < y[0]) ? -1 : 1).map((threshold, index) => {+ return html`+ <div class="threshold-list-item"+ style="padding: 8px 0; display: flex; flex-direction: row; align-items: center;">+ <div style="height: 100%; padding: 8px 14px 8px 0;">+ <or-mwc-input type="${InputType.COLOUR}" value="${threshold[1]}"+ style="width: 32px; height: 32px;"+ @or-mwc-input-changed="${(event: CustomEvent) => {+ this._config.thresholds[index][1] = event.detail.value;+ this.updateParent(new Map<string, any>([["config", this._config]]));+ }}"+ ></or-mwc-input>+ </div>+ <or-mwc-input type="${InputType.NUMBER}" comfortable .value="${threshold[0]}"+ ?disabled="${index === 0 && config.max}"+ .min="${ifDefined(config.min)}" .max="${ifDefined(config.max)}"@or-mwc-input-changed="${(event: CustomEvent) => {- this._config.thresholds[index][1] = event.detail.value;- this.updateParent(new Map<string, any>([["config", this._config]]));+ if ((!config.min || event.detail.value >= config.min) && (!config.max || event.detail.value <= config.max)) {+ this._config.thresholds[index][0] = event.detail.value;+ this.updateParent(new Map<string, any>([["config", this._config]]));+ }}}"></or-mwc-input>+ <button class="button-clear"+ style="margin-left: 8px; ${index == 0 ? 'visibility: hidden;' : undefined}"+ @click="${() => {+ this.removeThreshold(this._config, threshold);+ }}">+ <or-icon icon="close-circle"></or-icon>+ </button></div>- <or-mwc-input type="${InputType.NUMBER}" comfortable .value="${threshold[0]}" ?disabled="${index == 0}"- .min="${config.min}" .max="${config.max}"+ `+ })}+ <or-mwc-input .type="${InputType.BUTTON}" label="${i18next.t('threshold')}" icon="plus"+ style="margin-top: 24px; margin-left: -7px;"+ @or-mwc-input-changed="${() => this.addNewThreshold(this._config)}">+ </or-mwc-input>+ ` : null}+ ${(config.valueType === 'boolean') ? html`+ <div class="threshold-list-item"+ style="padding: 8px 0; display: flex; flex-direction: row; align-items: center;">+ <div style="height: 100%; padding: 8px 14px 8px 0;">+ <or-mwc-input type="${InputType.COLOUR}" value="${config.boolColors.true}"+ style="width: 32px; height: 32px;"@or-mwc-input-changed="${(event: CustomEvent) => {- if(event.detail.value >= config.min && event.detail.value <= config.max) {- this._config.thresholds[index][0] = event.detail.value;- this.updateParent(new Map<string, any>([["config", this._config]]));- }+ this._config.boolColors.true = event.detail.value;+ this.updateParent(new Map<string, any>([["config", this._config]]));}}"></or-mwc-input>- <button class="button-clear" style="margin-left: 8px; ${index == 0 ? 'visibility: hidden;' : undefined}"- @click="${() => { this.removeThreshold(this._config, threshold); }}">- <or-icon icon="close-circle"></or-icon>- </button></div>- `- })}- <or-mwc-input .type="${InputType.BUTTON}" label="${i18next.t('threshold')}" icon="plus"- style="margin-top: 24px; margin-left: -7px;"- @or-mwc-input-changed="${() => this.addNewThreshold(this._config)}">- </or-mwc-input>- </div>- `+ <or-mwc-input type="${InputType.TEXT}" comfortable .value="${'True'}" .readonly="${true}"+ ></or-mwc-input>+ </div>+ <div class="threshold-list-item"+ style="padding: 8px 0; display: flex; flex-direction: row; align-items: center;">+ <div style="height: 100%; padding: 8px 14px 8px 0;">+ <or-mwc-input type="${InputType.COLOUR}" value="${config.boolColors.false}"+ style="width: 32px; height: 32px;"+ @or-mwc-input-changed="${(event: CustomEvent) => {+ this._config.boolColors.false = event.detail.value;+ this.updateParent(new Map<string, any>([["config", this._config]]));+ }}"+ ></or-mwc-input>+ </div>+ <or-mwc-input type="${InputType.TEXT}" comfortable .value="${'False'}" .readonly="${true}"+ ></or-mwc-input>+ </div>+ ` : null}+ ${(config.valueType === 'text' && config.textColors) ? html`+ ${(config.textColors as [string, string][]).map((threshold, index) => {+ return html`+ <div class="threshold-list-item"+ style="padding: 8px 0; display: flex; flex-direction: row; align-items: center;">+ <div style="height: 100%; padding: 8px 14px 8px 0;">+ <or-mwc-input type="${InputType.COLOUR}" value="${threshold[1]}"+ style="width: 32px; height: 32px;"+ @or-mwc-input-changed="${(event: CustomEvent) => {+ this._config.textColors[index][1] = event.detail.value;+ this.updateParent(new Map<string, any>([["config", this._config]]));+ }}"+ ></or-mwc-input>+ </div>+ <or-mwc-input type="${InputType.TEXT}" comfortable .value="${threshold[0]}"+ @or-mwc-input-changed="${(event: OrInputChangedEvent) => {+ this._config.textColors[index][0] = event.detail.value;+ this.updateParent(new Map<string, any>([["config", this._config]]));+ }}"++ ></or-mwc-input>+ <button class="button-clear"+ style="margin-left: 8px; ${index == 0 ? 'visibility: hidden;' : undefined}"+ @click="${() => {+ this.removeThreshold(this._config, threshold);+ }}">+ <or-icon icon="close-circle"></or-icon>+ </button>+ </div>+ `+ })}+ <or-mwc-input .type="${InputType.BUTTON}" label="${i18next.t('threshold')}" icon="plus"+ style="margin-top: 24px; margin-left: -7px;"+ @or-mwc-input-changed="${() => this.addNewThreshold(this._config)}">+ </or-mwc-input> </div>+ ` : null}+ </div> `+}}- removeThreshold(config: any, threshold: [number, string]) {- config.thresholds = (config.thresholds as [number, string][]).filter((x) => x != threshold);+ removeThreshold(config: any, threshold: [any, string]) {+ switch (typeof threshold[0]) {+ case "number":+ config.thresholds = (config.thresholds as [number, string][]).filter((x) => x !== threshold);+ break;+ case "string":+ config.textColors = (config.textColors as [string, string][]).filter((x) => x !== threshold);+ break;+ }this.updateParent(new Map<string, any>([["config", this._config]]));}- addThreshold(config: any, threshold: [number, string]) {- (config.thresholds as [number, string][]).push(threshold);++ addThreshold(config: any, threshold: [any, string]) {+ switch (typeof threshold[0]) {+ case "number":+ (config.thresholds as [number, string][]).push(threshold as [number, string]);+ break;+ case "string":+ (config.textColors as [string, string][]).push(threshold as [string, string]);+ break;+ }this.updateParent(new Map<string, any>([["config", this._config]]));}+addNewThreshold(config: any) {- const suggestedValue = (config.thresholds[config.thresholds.length - 1][0] + 10);- this.addThreshold(config, [(suggestedValue <= config.max ? suggestedValue : config.max), "#000000"]);+ if (config.valueType === 'text') {+ this.addThreshold(config, ["new", "#000000"]);+ } else {+ const suggestedValue = (config.thresholds[config.thresholds.length - 1][0] + 10);+ this.addThreshold(config, [(!config.max || suggestedValue <= config.max ? suggestedValue : config.max), "#000000"]);+ }this.updateComplete.then(() => {const elem = this.shadowRoot?.getElementById('thresholds-list') as HTMLElement;const inputField = Array.from(elem.children)[elem.children.length - 2] as HTMLElement;(inputField.children[1] as HTMLElement).setAttribute('focused', 'true');})}++ /* ---------------------------------------------------- */++ async getAssetTypes(config: OrWidgetConfig | any) {+ const response = await manager.rest.api.AssetResource.queryAssets({+ realm: {+ name: manager.displayRealm+ },+ select: {+ attributes: []+ },+ });+ if (response && response.data) {+ const types: string[] = response.data.map(asset => asset.type!).filter((type, index, asset) => asset.indexOf(type) === index).sort();+ return types.map((type) => AssetModelUtil.getAssetDescriptor(type)!).filter((t) => t.descriptorType === "asset");+ }+ }++ getAttributesByType(type: string) {+ const descriptor: AssetDescriptor = (AssetModelUtil.getAssetDescriptor(type) as AssetDescriptor);+ const typeInfo: AssetTypeInfo = (AssetModelUtil.getAssetTypeInfo(descriptor) as AssetTypeInfo);++ if (typeInfo.attributeDescriptors) {+ return typeInfo.attributeDescriptors.filter((ad) => {+ return this._allowedValueTypes.indexOf(ad.type!) > -1;+ }).map((ad) => {+ const label = Util.getAttributeLabel(ad, undefined, type, false);+ return [ad.name!, label];+ }).sort(Util.sortByString((attr) => attr[1]));+ }+ }++ protected mapDescriptors(descriptors: AssetDescriptor[], withNoneValue?: ListItem): ListItem[] {+ const items: ListItem[] = descriptors.map((descriptor) => {+ return {+ styleMap: {+ "--or-icon-fill": descriptor.colour ? "#" + descriptor.colour : "unset"+ },+ icon: descriptor.icon,+ text: Util.getAssetTypeLabel(descriptor),+ value: descriptor.name!,+ data: descriptor+ }+ }).sort(Util.sortByString((listItem) => listItem.text));++ if (withNoneValue) {+ items.splice(0, 0, withNoneValue);+ }+ return items;+ }++ protected getSelectHeader(): TemplateResult {+ return html`+ <or-mwc-input style="width:100%;" type="${InputType.TEXT}" .label="${i18next.t("filter.assetTypeLabel")}"+ iconTrailing="menu-down" iconColor="rgba(0, 0, 0, 0.87)" icon="selection-ellipse"+ value="${i18next.t("filter.assetTypeNone")}"></or-mwc-input>`;+ }++ protected getSelectedHeader(descriptor: AssetDescriptor): TemplateResult {+ return html`+ <or-mwc-input style="width:100%;" type="${InputType.TEXT}" .label="${i18next.t("filter.assetTypeLabel")}"+ .iconColor="${descriptor.colour}" iconTrailing="menu-down" icon="${descriptor.icon}"+ value="${Util.getAssetTypeLabel(descriptor)}"></or-mwc-input>`;+ }++ protected assetTypeSelect(): TemplateResult {+ if (this._config.assetType) {+ const descriptor: AssetDescriptor | undefined = this._loadedAssetTypes.find((at: AssetDescriptor) => {+ return at.name === this._config.assetType+ });+ if (descriptor) {+ return this.getSelectedHeader(descriptor);+ } else {+ return this.getSelectHeader();+ }+ } else {+ return this.getSelectHeader();+ }+ }++ protected handleTypeSelect(value: string) {+ if (this._config.assetType !== value) {+ this._config.attributeName = undefined;+ this._config.assets = [];+ this._config.showLabels = false;+ this._config.showUnits = false;+ this._config.boolColors = {type: 'boolean', 'false': '#ef5350', 'true': '#4caf50'};+ this._config.textColors = [['example', "#4caf50"], ['example2', "#ff9800"]];+ this._config.thresholds = [[0, "#4caf50"], [75, "#ff9800"], [90, "#ef5350"]];+ this._config.assetType = value;+ this._config.attributes = this.getAttributesByType(value);+ this.updateParent(new Map<string, any>([["config", this._config]]));+ }+ }++ protected async handleAttributeSelect(value: string) {+ this._config.attributeName = value;+ await manager.rest.api.AssetResource.queryAssets({+ realm: {+ name: manager.displayRealm+ },+ select: {+ attributes: [value, 'location']+ },+ types: [this._config.assetType],+ }).then(response => {+ this._config.assets = response.data;+ this._config.valueType = response.data[0].attributes![value].type;+ }).catch((reason) => {+ console.error(reason);+ showSnackbar(undefined, i18next.t('errorOccurred'));+ });++ this.updateParent(new Map<string, any>([["config", this._config]]));+ }++ async getAssettypesHTML(config: OrWidgetConfig | any) {+ if (config.assetTypes) {+ if (this._loadedAssetTypes.length === 0) {+ this._loadedAssetTypes = await this.getAssetTypes(config) as AssetDescriptor[]+ }+ return html`+ <div style="padding: 12px 24px 24px 24px; display: flex; flex-direction: column; gap: 16px;">+ ${(config.assetType) ? html`+ ${this._loadedAssetTypes.length > 0 ? getContentWithMenuTemplate(+ this.assetTypeSelect(),+ this.mapDescriptors(this._loadedAssetTypes, {+ text: i18next.t("filter.assetTypeMenuNone"),+ value: "",+ icon: "selection-ellipse"+ }) as ListItem[],+ undefined,+ (v: string[] | string) => {+ this.handleTypeSelect(v as string);+ },+ undefined,+ false,+ true,+ true) : html``+ }++ <div>+ <or-mwc-input .type="${InputType.SELECT}" style="width: 100%;"+ .options="${this._config.attributes}"+ .value="${config.attributeName}" label="${i18next.t('filter.attributeLabel')}"+ @or-mwc-input-changed="${(event: CustomEvent) => {+ this.handleAttributeSelect(event.detail.value);+ }}"+ ></or-mwc-input>+ </div>++ <div style="padding: 0 10px 12px 10px;">+ <div class="switchMwcInputContainer">+ <span>${i18next.t('showLabels')}</span>+ <or-mwc-input .type="${InputType.SWITCH}" style="width: 70px;"+ .value="${config.showLabels}"+ @or-mwc-input-changed="${(event: CustomEvent) => {+ this._config.showLabels = event.detail.value;+ this.updateParent(new Map<string, any>([["config", this._config]]));+ }}"+ ></or-mwc-input>+ </div>+ <div class="switchMwcInputContainer">+ <span>${i18next.t('showUnits')}</span>+ <or-mwc-input .type="${InputType.SWITCH}" style="width: 70px;"+ .value="${config.showUnits}"+ .disabled="${!config.showLabels}"+ @or-mwc-input-changed="${(event: CustomEvent) => {+ this._config.showUnits = event.detail.value;+ this.updateParent(new Map<string, any>([["config", this._config]]));+ }}"+ ></or-mwc-input>+ </div>++ </div>++ ` : undefined}+ </div>+ `+ }+ }}diff --git a/ui/component/or-dashboard-builder/src/widgets/or-gauge-widget.ts b/ui/component/or-dashboard-builder/src/widgets/or-gauge-widget.tsindex 0b9a70973..7bb70176f 100644--- a/ui/component/or-dashboard-builder/src/widgets/or-gauge-widget.ts+++ b/ui/component/or-dashboard-builder/src/widgets/or-gauge-widget.ts@@ -17,7 +17,8 @@ export interface GaugeWidgetConfig extends OrWidgetConfig {thresholds: [number, string][];decimals: number;min: number,- max: number+ max: number,+ valueType: string,}export class OrGaugeWidget implements OrWidgetEntity {@@ -35,7 +36,8 @@ export class OrGaugeWidget implements OrWidgetEntity {thresholds: [[0, "#4caf50"],[75, "#ff9800"],[90, "#ef5350"]], // colors from https://mui.com/material-ui/customization/palette/ as reference (since material has no official colors)decimals: 0,min: 0,- max: 100+ max: 100,+ valueType: 'number',} as GaugeWidgetConfig;}getWidgetHTML(widget: DashboardWidget, editMode: boolean, realm: string) {diff --git a/ui/component/or-dashboard-builder/src/widgets/or-map-widget.ts b/ui/component/or-dashboard-builder/src/widgets/or-map-widget.tsnew file mode 100644index 000000000..18524e46f--- /dev/null+++ b/ui/component/or-dashboard-builder/src/widgets/or-map-widget.ts@@ -0,0 +1,341 @@+import {+ Asset,+ Attribute,+ AttributeRef,+ DashboardWidget,+ WellknownAttributes,+ WellknownMetaItems,+ GeoJSONPoint,+ AssetDescriptor,+ WellknownValueTypes+} from "@openremote/model";+import {InputType, OrInputChangedEvent} from "@openremote/or-mwc-components/or-mwc-input";+import {i18next} from "@openremote/or-translate";+import {html, LitElement, TemplateResult} from "lit";+import {customElement, property, state, query} from "lit/decorators.js";+import {OrWidgetConfig, OrWidgetEntity} from "./or-base-widget";+import {SettingsPanelType, widgetSettingsStyling} from "../or-dashboard-settingspanel";+import {style} from "../style";+import manager, {Util} from "@openremote/core";+import {showSnackbar} from "@openremote/or-mwc-components/or-mwc-snackbar";+import "@openremote/or-map";+import {OrAttributeInputChangedEvent} from "@openremote/or-attribute-input";+import {+ OrMap,+ MapMarkerAssetConfig,+ LngLatLike,+ AttributeMarkerColours,+ RangeAttributeMarkerColours,+ AttributeMarkerColoursRange,+ MapMarkerColours,+ OrMapLongPressEvent,+ ViewSettings,+} from "@openremote/or-map";+import {LngLat, LngLatBounds, LngLatBoundsLike} from "maplibre-gl";++export interface MapWidgetConfig extends OrWidgetConfig {+ // General values+ displayName: string,+ attributeRefs: AttributeRef[];+ // Map related values+ zoom?: number,+ center?: LngLatLike,+ lat?: number,+ lng?: number,+ // Map marker related values+ showLabels: boolean,+ showUnits: boolean,+ boolColors: MapMarkerColours,+ textColors: [string, string][],+ // Threshold related values+ thresholds: [number, string][],+ min?: number,+ max?: number,+ // Asset type related values+ assetType?: string,+ valueType?: string,+ attributeName?: string,+ assetTypes: AssetDescriptor[],+ assets: Asset[],+ attributes: string[],+}+++export class OrMapWidget implements OrWidgetEntity {++ // Properties+ readonly DISPLAY_NAME: string = "Map";+ readonly DISPLAY_MDI_ICON: string = "map"; // https://materialdesignicons.com;+ readonly MIN_COLUMN_WIDTH: number = 2;+ readonly MIN_PIXEL_WIDTH: number = 0;+ readonly MIN_PIXEL_HEIGHT: number = 0;++ getDefaultConfig(widget: DashboardWidget): MapWidgetConfig {+ return {+ displayName: widget?.displayName,+ attributeRefs: [],+ showLabels: false,+ showUnits: false,+ boolColors: {type: 'boolean', 'false': '#ef5350', 'true': '#4caf50'},+ textColors: [['example', '4caf50'], ['example2', 'ef5350']],+ thresholds: [[0, "#4caf50"], [75, "#ff9800"], [90, "#ef5350"]],+ assetTypes: [],+ assetType: " ",+ assets: [],+ attributes: [],+ } as MapWidgetConfig;+ }++ getWidgetHTML(widget: DashboardWidget, editMode: boolean, realm: string): TemplateResult {+ return html`+ <or-map-widget .widget="${widget}" .editMode="${editMode}" .realm="${realm}"+ style="overflow: auto; height: 100%;"></or-map-widget>`;+ }++ getSettingsHTML(widget: DashboardWidget, realm: string): TemplateResult {+ return html`+ <or-map-widgetsettings .widget="${widget}" .realm="${realm}"></or-map-widgetsettings>`;+ }+}+++@customElement('or-map-widget')+export class OrMapWidgetContent extends LitElement {++ @property()+ public readonly widget?: DashboardWidget;++ @property()+ public editMode?: boolean;++ @property()+ public realm?: string;++ @state()+ private assets: Asset[] = [];++ @query("#miniMap")+ protected _map?: OrMap;++ private markers: MapMarkerAssetConfig = {};+++ /* ---------- */++ render() {+ const config = JSON.parse(JSON.stringify(this.widget!.widgetConfig)) as MapWidgetConfig;+ this.markers = {};+ return html`+ <or-map id="miniMap" class="or-map" .zoom="${config.zoom ? config.zoom! : undefined}"+ .center="${config.center ? config.center! : undefined}"+ style="height: 100%">+ ${(this.assets) ?+ this.assets.filter((asset: Asset) => {+ if (!asset.attributes) {+ return false;+ }+ const attr = asset.attributes[WellknownAttributes.LOCATION] as Attribute<GeoJSONPoint>;+ return !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.widget!.widgetConfig.attributeName};+ this.markers[asset.type!].showUnits = this.widget!.widgetConfig.showUnits;+ this.markers[asset.type!].showLabel = this.widget!.widgetConfig.showLabels;+ if (this.widget!.widgetConfig.valueType == 'boolean') {+ this.widget!.widgetConfig.boolColors.true = this.widget!.widgetConfig.boolColors.true.replace("#", "");+ this.widget!.widgetConfig.boolColors.false = this.widget!.widgetConfig.boolColors.false.replace("#", "");+ this.markers[asset.type!].colours = this.widget!.widgetConfig.boolColors;+ } else if (this.widget!.widgetConfig.valueType == 'text') {+ var colors: AttributeMarkerColours = {type: 'string',};+ (this.widget!.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.widget!.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+ };+ this.markers[asset.type!].colours = colorsNum;+ }+ }+ return html`+ <or-map-marker-asset .asset="${asset}"+ .config="${this.markers}"></or-map-marker-asset>+ `+ }) : undefined}+ }+ </or-map>+ `+ }++ updated(changedProperties: Map<string, any>) {+ if (changedProperties.has("widget") || changedProperties.has("editMode")) {+ if (this.assets !== this.widget!.widgetConfig.assets || this.assets.length === 0) {+ this.fetchAssets(this.widget?.widgetConfig).then((assets) => {+ this.assets = assets!;+ });+ }+ }+ }++ // Fetching the assets according to the selected attribute and asset type+ async fetchAssets(config: OrWidgetConfig | any): Promise<Asset[] | undefined> {+ if (config.assetType && config.attributeName) {+ let assets: Asset[] = [];+ await manager.rest.api.AssetResource.queryAssets({+ select: {+ attributes: [config.attributeName, 'location']+ },+ types: [config.assetType],++ }).then(response => {+ assets = response.data;+ this.markers = {};+ }).catch((reason) => {+ console.error(reason);+ showSnackbar(undefined, i18next.t('errorOccurred'));+ });+ return assets;+ }+ }+}++@customElement("or-map-widgetsettings")+class OrMapWidgetSettings extends LitElement {++ @property()+ public widget?: DashboardWidget;++ @state()+ private assetTypes: string[] = [];++ // Default values+ private expandedPanels: string[] = [i18next.t('map')];+++ static get styles() {+ return [style, widgetSettingsStyling];+ }++ // UI Rendering+ render() {+ const config = JSON.parse(JSON.stringify(this.widget!.widgetConfig)) as MapWidgetConfig; // duplicate to edit, to prevent parent updates. Please trigger updateConfig()+ const CoordinatesRegexPattern = "^[ ]*(?:Lat: )?(-?\\d+\\.?\\d*)[, ]+(?:Lng: )?(-?\\d+\\.?\\d*)[ ]*$";+ return html`+ <div>+ ${this.generateExpandableHeader(i18next.t('map'))}+ </div>+ <div>+ ${this.expandedPanels.includes(i18next.t('map')) ? html`+ <div style="padding: 12px 24px 48px 24px; display: flex; flex-direction: column; gap: 16px;">++ <div>+ <or-mwc-input .type="${InputType.NUMBER}" style="width: 100%;"+ .value="${config.zoom}" label="${i18next.t('zoom')}"+ @or-mwc-input-changed="${(event: OrInputChangedEvent) => {+ config.zoom = event.detail.value;+ this.updateConfig(this.widget!, config);+ }}"+ ></or-mwc-input>+ </div>+ <div style="display: flex; gap: 8px;">+ <or-mwc-input .type="${InputType.TEXT}" style="width: 100%;"+ .value="${config.center ? 'Lat: ' + (Object.values(config.center))[1] + ', Lng: ' + (Object.values(config.center))[0] : undefined}"+ label="${i18next.t('center')}"+ .pattern="${CoordinatesRegexPattern}"+ @or-mwc-input-changed="${(event: OrInputChangedEvent) => {+ if (event.detail.value) {+ const lngLatArr = (event.detail.value as string).replace('Lat:', '').replace('Lng:', '').split(/[, ]/).filter(v => !!v);+ if (lngLatArr.length === 2) {+ var value = new LngLat(+ Number.parseFloat(lngLatArr[1]),+ Number.parseFloat(lngLatArr[0])+ );+ config.center = value as LngLatLike;+ this.updateConfig(this.widget!, config);+ }+ }+ }}"+ ></or-mwc-input>+++ </div>+ </div>+ ` : null}+ </div>+ <div>+ ${this.generateExpandableHeader(i18next.t('display'))}+ </div>+ <div>+ ${this.expandedPanels.includes(i18next.t('display')) ? html`+ <or-dashboard-settingspanel .type="${SettingsPanelType.ASSETTYPES}"+ .widgetConfig="${this.widget?.widgetConfig}"+ @updated="${(event: CustomEvent) => {+ this.updateConfig(this.widget!, event.detail.changes.get('config'));+ }}">+ </or-dashboard-settingspanel>+ ` : null}+ </div>+ ${this.widget?.widgetConfig.assets.length > 0 ? html`+ <div>+ ${this.generateExpandableHeader(i18next.t('thresholds'))}+ </div>+ <div>+ ${this.expandedPanels.includes(i18next.t('thresholds')) ? html`+ <or-dashboard-settingspanel .type="${SettingsPanelType.THRESHOLDS}"+ .widgetConfig="${this.widget?.widgetConfig}"+ @updated="${(event: CustomEvent) => {+ this.updateConfig(this.widget!, event.detail.changes.get('config'));+ }}"+ ></or-dashboard-settingspanel>+ ` : null}+ </div>+ ` : null}+ `+ }++ updateConfig(widget: DashboardWidget, config: OrWidgetConfig | any, force: boolean = false) {+ const oldWidget = JSON.parse(JSON.stringify(widget)) as DashboardWidget;+ widget.widgetConfig = config;+ this.requestUpdate("widget", oldWidget);+ this.forceParentUpdate(new Map<string, any>([["widget", widget]]), force);+ }++ // Method to update the Grid. For example after changing a setting.+ public forceParentUpdate(changes: Map<string, any>, force: boolean = false) {+ this.dispatchEvent(new CustomEvent('updated', {detail: {changes: changes, force: force}}));+ }++ generateExpandableHeader(name: string): TemplateResult {+ return html`+ <span class="expandableHeader panel-title" @click="${() => {+ this.expandPanel(name);+ }}">+ <or-icon icon="${this.expandedPanels.includes(name) ? 'chevron-down' : 'chevron-right'}"></or-icon>+ <span style="margin-left: 6px; height: 25px; line-height: 25px;">${name}</span>+ </span>+ `+ }++ expandPanel(panelName: string): void {+ if (this.expandedPanels.includes(panelName)) {+ const indexOf = this.expandedPanels.indexOf(panelName, 0);+ if (indexOf > -1) {+ this.expandedPanels.splice(indexOf, 1);+ }+ } else {+ this.expandedPanels.push(panelName);+ }+ this.requestUpdate();+ }+}diff --git a/ui/component/or-map/src/index.ts b/ui/component/or-map/src/index.tsindex b50b2df42..f8cee3dde 100644--- a/ui/component/or-map/src/index.ts+++ b/ui/component/or-map/src/index.ts@@ -18,6 +18,7 @@ import {import {OrMwcDialog, showDialog} from "@openremote/or-mwc-components/or-mwc-dialog";import {getMarkerIconAndColorFromAssetType} from "./util";import {i18next} from "@openremote/or-translate";+import { debounce } from "lodash";import { MapType } from "@openremote/model";// Re-exports@@ -396,7 +397,6 @@ export class OrMap extends LitElement {public type: MapType = manager.mapType;protected _markerStyles: string[] = [];-@property({type: String, converter: {fromAttribute(value: string | null, type?: String): LngLatLike | undefined {if (!value) {@@ -438,6 +438,8 @@ export class OrMap extends LitElement {protected _observer?: FlattenedNodesObserver;protected _markers: OrMapMarker[] = [];+ protected _resizeObserver?: ResizeObserver;+@query("#map")protected _mapContainer?: HTMLElement;@@ -469,6 +471,9 @@ export class OrMap extends LitElement {if (this._observer) {this._observer.disconnect();}+ if(this._resizeObserver) {+ this._resizeObserver.disconnect();+ }}protected render() {@@ -485,7 +490,6 @@ export class OrMap extends LitElement {protected updated(changedProperties: PropertyValues) {super.updated(changedProperties);-if (changedProperties.has("center") || changedProperties.has("zoom")) {this.flyTo(this.center, this.zoom);}@@ -518,6 +522,14 @@ export class OrMap extends LitElement {this._processNewMarkers(info.addedNodes);this._processRemovedMarkers(info.removedNodes);});+ this._resizeObserver?.disconnect();+ this._resizeObserver = new ResizeObserver(debounce(() => {+ this.resize();+ }, 200));+ var container = this._mapContainer?.parentElement;+ if (container) {+ this._resizeObserver.observe(container);+ }});}diff --git a/ui/component/or-map/src/mapwidget.ts b/ui/component/or-map/src/mapwidget.tsindex 1a15b1ba1..3676ad2f2 100644--- a/ui/component/or-map/src/mapwidget.ts+++ b/ui/component/or-map/src/mapwidget.ts@@ -184,6 +184,9 @@ export class MapWidget {if (!this._center) {this.setCenter(this._viewSettings.center);}+ else {+ this.setCenter(this._center);+ }}return settings;diff --git a/ui/component/or-map/src/markers/or-map-marker-asset.ts b/ui/component/or-map/src/markers/or-map-marker-asset.tsindex cf22d5b6e..b7a47231a 100644--- a/ui/component/or-map/src/markers/or-map-marker-asset.ts+++ b/ui/component/or-map/src/markers/or-map-marker-asset.ts@@ -39,7 +39,7 @@ export type RangeAttributeMarkerColours = {}export type AttributeMarkerColoursRange = {- max: number;+ min: number;colour: string;}diff --git a/ui/component/or-map/src/util.ts b/ui/component/or-map/src/util.tsindex 148b4bd4a..4b5e342f8 100644--- a/ui/component/or-map/src/util.ts+++ b/ui/component/or-map/src/util.ts@@ -115,7 +115,7 @@ export function getMarkerIconAndColorFromAssetType(if (colourConfig.type === "range" && colourConfig.ranges && typeof attrVal === "number") {const ranges = colourConfig.ranges;// see in what range the attrVal fits and if not, what the setting for the highest range is- const colourFromRange = ranges.find(r => attrVal < r.max) || ranges.reduce((a, b) => (a.max > b.max) ? a : b);+ const colourFromRange = ranges.find(r => attrVal > r.min) || ranges.reduce((a, b) => (b.min > a.min) ? a : b);colour = colourFromRange.colour || undefined;} else if (colourConfig.type === "boolean") {const value = !!attrVal + "";