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: Improvements to or-attribute-card and or-attribute-history (#1413)
Martin Peetersa165bd57aeee
diff --git a/ui/component/or-attribute-card/src/index.ts b/ui/component/or-attribute-card/src/index.tsindex 7ffba516a..9c56b0049 100644--- a/ui/component/or-attribute-card/src/index.ts+++ b/ui/component/or-attribute-card/src/index.ts@@ -1,5 +1,5 @@import {css, html, LitElement, PropertyValues, unsafeCSS} from "lit";-import {customElement, property, query} from "lit/decorators.js";+import {customElement, property, state, query} from "lit/decorators.js";import i18next from "i18next";import {Asset,@@ -15,6 +15,7 @@ import {AssetDatapointLTTBQuery} from "@openremote/model";import {DefaultColor3, DefaultColor4, manager, Util} from "@openremote/core";+import {isAxiosError} from "@openremote/rest";import {Chart, ScatterDataPoint, LineController, LineElement, PointElement, LinearScale, TimeSeriesScale, Title} from "chart.js";import "chartjs-adapter-moment";import {OrChartConfig} from "@openremote/or-chart";@@ -27,6 +28,7 @@ import {OrAssetTreeSelectionEvent} from "@openremote/or-asset-tree";import {OrMwcDialog, showDialog} from "@openremote/or-mwc-components/or-mwc-dialog";import {OrAttributePicker, OrAttributePickerPickedEvent} from "@openremote/or-attribute-picker";import {getContentWithMenuTemplate} from "@openremote/or-mwc-components/or-mwc-menu";+import {when} from "lit/directives/when.js";import {debounce} from "lodash";export type ContextMenuOption = "editAttribute" | "editDelta" | "editCurrentValue" | "delete";@@ -148,9 +150,11 @@ const style = css`height: 75%;}.controls-wrapper {+ flex: 0 0 80px;height: 100%;display: flex;flex-direction: column;+ align-items: end;place-content: space-between;}@@ -213,22 +217,26 @@ export class OrAttributeCard extends LitElement {@property()public showControls: boolean = true;@property()+ public hideAttributePicker: boolean = false;+ @property()public showTitle: boolean = true;@property()protected _loading: boolean = false;- private error: boolean = false;-@property()private period: moment.unitOfTime.Base = "day";private asset?: Asset;private formattedMainValue?: {value: number|undefined, unit: string};+ @state()+ protected _error?: string;+@query("#chart")private _chartElem!: HTMLCanvasElement;private _chart?: Chart<"line", ScatterDataPoint[]>;protected _startOfPeriod?: number;protected _endOfPeriod?: number;+ protected _dataAbortController?: AbortController;private resizeObserver?: ResizeObserver;static get styles() {@@ -345,6 +353,9 @@ export class OrAttributeCard extends LitElement {}}+ shouldHideAttributePicker(): boolean {+ return (this.hideAttributePicker && this.hideAttributePicker.toString() == "true");+ }shouldShowControls(): boolean { // Checking for string input as well since that was not workingreturn (this.showControls && this.showControls.toString() == "true");}@@ -354,15 +365,15 @@ export class OrAttributeCard extends LitElement {protected render() {- if (!this.assets || !this.assetAttributes || this.assetAttributes.length === 0) {+ if (!this._error && (!this.assets || !this.assetAttributes || this.assetAttributes.length === 0)) {return html`<div class="panel panel-empty"><div class="panel-content-wrapper"><div class="panel-content">- ${this.shouldShowControls() ? html`+ ${!this.shouldHideAttributePicker() ? html`<or-mwc-input class="button" .type="${InputType.BUTTON}" label="selectAttribute" icon="plus" @or-mwc-input-changed="${() => this._openDialog("editAttribute")}"></or-mwc-input>` : html`- <span>${i18next.t('noAttributeConnected')}</span>+ <span style="text-align: center;">${i18next.t('noAttributeConnected')}</span>`}</div></div>@@ -370,21 +381,6 @@ export class OrAttributeCard extends LitElement {`;}- if (this.error) {- return html`- <div class="panel panel-empty">- <div class="panel-content-wrapper">- <div class="panel-content">- <span>${i18next.t("couldNotRetrieveAttribute")}</span>- ${this.shouldShowControls() ? html`- <or-mwc-input class="button" .type="${InputType.BUTTON}" label="selectAttribute" icon="plus" @or-mwc-input-changed="${() => this._openDialog("editAttribute")}"></or-mwc-input>- ` : undefined}- </div>- </div>- </div>- `;- }-this.updateComplete.then(() => {this.resizeObserver = new ResizeObserver(debounce((entries: ResizeObserverEntry[]) => {const elemSize = entries[0].devicePixelContentBoxSize[0].inlineSize;@@ -424,14 +420,27 @@ export class OrAttributeCard extends LitElement {</div><div class="panel-content"><div class="mainvalue-wrapper">- <span class="main-number-icon">${this.assets && this.assets.length === 1 ? getAssetDescriptorIconTemplate(AssetModelUtil.getAssetDescriptor(this.assets[0].type!)) : ""}</span>- <span class="main-number ${this.mainValueSize}">${this.formattedMainValue ? this.formattedMainValue.value : ""}</span>- <span class="main-number-unit ${this.mainValueSize}">${this.formattedMainValue ? this.formattedMainValue.unit : ""}</span>+ ${when(!this._loading, () => html`+ <span class="main-number-icon">${this.assets && this.assets.length === 1 ? getAssetDescriptorIconTemplate(AssetModelUtil.getAssetDescriptor(this.assets[0].type!)) : ""}</span>+ <span class="main-number ${this.mainValueSize}">${this.formattedMainValue ? this.formattedMainValue.value : ""}</span>+ <span class="main-number-unit ${this.mainValueSize}">${this.formattedMainValue ? this.formattedMainValue.unit : ""}</span>+ `)}</div><div class="graph-wrapper">- <div class="chart-wrapper">- <canvas id="chart"></canvas>- </div>++ ${when(this._error, () => html`+ <div style="flex: 0 0 80px;"></div>+ <or-translate .value="${this._error}" style="flex: 1; text-align: center;"></or-translate>+ `, () => html`+ <div class="chart-wrapper">+ ${when(this._loading, () => html`+ <or-loading-indicator></or-loading-indicator>+ `, () => html`+ <canvas id="chart"></canvas>+ `)}+ </div>+ `)}+<div class="controls-wrapper"><div class="delta-wrapper"><span class="delta">${this.delta ? this.deltaPlus + (this.delta.val !== undefined && this.delta.val !== null ? this.delta.val : "") + (this.delta.unit || "") : ""}</span>@@ -685,10 +694,16 @@ export class OrAttributeCard extends LitElement {protected async loadData() {- if (this._loading || this.data || !this.assetAttributes || !this.assets || this.assets.length === 0 || this.assetAttributes.length === 0 || !this.period) {+ if (this.data || !this.assetAttributes || !this.assets || this.assets.length === 0 || this.assetAttributes.length === 0 || !this.period) {return;}+ // If a new requests comes in, we override it with this one using AbortController.+ if(this._dataAbortController) {+ this._dataAbortController.abort("Data request overridden");+ delete this._dataAbortController;+ }+this._loading = true;let interval: DatapointInterval = DatapointInterval.HOUR;@@ -720,40 +735,59 @@ export class OrAttributeCard extends LitElement {const lowerCaseInterval = interval.toLowerCase();this._startOfPeriod = moment().subtract(1, this.period).toDate().getTime();this._endOfPeriod = moment().toDate().getTime();- this.mainValue = undefined;- this.formattedMainValue = undefined;const assetId = this.assets[0].id!;const attributeName = this.assetAttributes[0][1].name!;- const currentValue: AttributeEvent = await manager.events!.sendEventWithReply({- eventType: "read-asset-attribute",- ref: {- id: assetId,- name: attributeName+ this._dataAbortController = new AbortController();++ try {+ const response = await manager.rest.api.AssetDatapointResource.getDatapoints(+ assetId,+ attributeName,+ {type: "lttb", fromTimestamp: this._startOfPeriod, toTimestamp: this._endOfPeriod, amountOfPoints: 20} as AssetDatapointLTTBQuery,+ {signal: this._dataAbortController.signal}+ );++ this._loading = false;++ if (response.status === 200) {+ this.data = response.data;+ this.delta = this.getFormattedDelta(this.getFirstKnownMeasurement(this.data), this.getLastKnownMeasurement(this.data));+ this.deltaPlus = this.delta && this.delta.val! > 0 ? "+" : "";+ this._error = undefined;+ }++ } catch (ex) {+ console.error(ex);+ if((ex as Error)?.message === "canceled") {+ return; // If request has been canceled (using AbortController); return, and prevent _loading is set to false.+ }+ this._loading = false;++ if(isAxiosError(ex)) {+ if(ex.message.includes("timeout of 10000ms exceeded")) {+ this._error = "noAttributeDataTimeout";+ return;+ }}- } as ReadAttributeEvent);-- this.mainValue = currentValue.value;- this.formattedMainValue = this.getFormattedValue(this.mainValue!);-- const response = await manager.rest.api.AssetDatapointResource.getDatapoints(- assetId,- attributeName,- {- type: "lttb",- fromTimestamp: this._startOfPeriod,- toTimestamp: this._endOfPeriod,- amountOfPoints: 20,- } as AssetDatapointLTTBQuery- );-- this._loading = false;-- if (response.status === 200) {- this.data = response.data;- this.delta = this.getFormattedDelta(this.getFirstKnownMeasurement(this.data), this.getLastKnownMeasurement(this.data));- this.deltaPlus = this.delta && this.delta.val! > 0 ? "+" : "";- this.error = false;++ this._error = "couldNotRetrieveAttribute";++ } finally {++ // Finally, request the current value through WS request/response+ this.mainValue = undefined;+ this.formattedMainValue = undefined;+ const currentValue: AttributeEvent = await manager.events!.sendEventWithReply({+ eventType: "read-asset-attribute",+ ref: {+ id: assetId,+ name: attributeName+ }+ } as ReadAttributeEvent);++ this.mainValue = currentValue.value;+ this.formattedMainValue = this.getFormattedValue(this.mainValue!);}}diff --git a/ui/component/or-attribute-history/src/index.ts b/ui/component/or-attribute-history/src/index.tsindex 984e1e598..587a7e71f 100644--- a/ui/component/or-attribute-history/src/index.ts+++ b/ui/component/or-attribute-history/src/index.ts@@ -24,7 +24,9 @@ import {InputType, OrInputChangedEvent} from "@openremote/or-mwc-components/or-mimport {MDCDataTable} from "@material/data-table";import {JSONPath} from "jsonpath-plus";import moment from "moment";+import {isAxiosError} from "@openremote/rest";import {styleMap} from "lit/directives/style-map.js";+import { when } from "lit/directives/when.js";export class OrAttributeHistoryEvent extends CustomEvent<OrAttributeHistoryEventDetail> {@@ -126,6 +128,7 @@ const style = css`}#container {+ position: relative;display: flex;min-width: 0;width: 100%;@@ -188,6 +191,7 @@ const style = css`#table-container {height: 100%;+ min-height: 250px;}#table {@@ -257,11 +261,13 @@ export class OrAttributeHistory extends translate(i18next)(LitElement) {protected _chart?: Chart<"line", ScatterDataPoint[]>;protected _type?: ValueDescriptor;protected _style!: CSSStyleDeclaration;+ protected _error?: string;protected _startOfPeriod?: number;protected _endOfPeriod?: number;protected _timeUnits?: TimeUnit;protected _stepSize?: number;protected _updateTimestampTimer?: number;+ protected _dataAbortController?: AbortController;protected _dataFirstLoaded: boolean = false;@@ -287,6 +293,10 @@ export class OrAttributeHistory extends translate(i18next)(LitElement) {return false;}+ if(_changedProperties.has("attribute")) {+ this._cleanup();+ }+if (!this._type && this.attribute) {this._type = AssetModelUtil.getValueDescriptor(this.attribute.type) || {};}@@ -303,7 +313,7 @@ export class OrAttributeHistory extends translate(i18next)(LitElement) {render() {const isChart = this._type && (this._type.jsonType === "number" || this._type.jsonType === "boolean");- const disabled = this._loading || !this._type;+ const disabled = !this._type;return html`<div id="container">@@ -317,19 +327,31 @@ export class OrAttributeHistory extends translate(i18next)(LitElement) {</div></div>- ${!this._type ? html`+ ${when(!this._type, () => html`<div id="msg"><or-translate value="invalidAttribute"></or-translate></div>- ` : isChart ? html`- <div id="chart-container">- <canvas id="chart"></canvas>- </div>- ` : html`- <div id="table-container">- ${this._tableTemplate || ``}- </div>- `}+ `, () => when(this._error, () => html`+ <div id="msg">+ <or-translate .value="${this._error}"></or-translate>+ </div>+ `, () => when(isChart, () => html`++ ${when(this._loading, () => html`+ <or-loading-indicator style="position: absolute; top: 50%; left: 50%;"></or-loading-indicator>+ `)}+ <div id="chart-container" style="${this._loading ? 'opacity: 0.2' : undefined}">+ <canvas id="chart"></canvas>+ </div>++ `, () => html`++ <div id="table-container">+ ${when(this._loading, () => html`+ <or-loading-indicator></or-loading-indicator>+ `, () => this._tableTemplate)}+ </div>+ `)))}</div>`;}@@ -639,106 +661,139 @@ export class OrAttributeHistory extends translate(i18next)(LitElement) {}protected async _loadData() {- if (this._loading || this._data || !this.assetType || !this.assetId || (!this.attribute && !this.attributeRef) || !this.period || !this.toTimestamp) {+ if (this._data || !this.assetType || !this.assetId || (!this.attribute && !this.attributeRef) || !this.period || !this.toTimestamp) {return;}+ // If a new requests comes in, we override it with this one using AbortController.+ if(this._loading) {+ if(this._dataAbortController) {+ this._dataAbortController.abort("Data request overridden");+ delete this._dataAbortController;+ } else {+ return;+ }+ }++ this._error = undefined;this._loading = true;+const assetId = this.assetId!;const attributeName = this.attribute ? this.attribute.name! : this.attributeRef!.name!;-- if (!this._type) {- let attr = this.attribute;-- if (!attr) {- const response = await manager.rest.api.AssetResource.queryAssets({- ids: [assetId],- select: {- attributes: [- attributeName- ]+ this._dataAbortController = new AbortController();++ try {+ if (!this._type) {+ let attr = this.attribute;++ if (!attr) {+ const response = await manager.rest.api.AssetResource.queryAssets({+ ids: [assetId],+ select: {+ attributes: [+ attributeName+ ]+ }+ }, { signal: this._dataAbortController.signal });+ if (response.status === 200 && response.data.length > 0) {+ attr = response.data[0].attributes ? response.data[0].attributes[attributeName] : undefined;}- });- if (response.status === 200 && response.data.length > 0) {- attr = response.data[0].attributes ? response.data[0].attributes[attributeName] : undefined;+ }++ if (attr) {+ this._type = AssetModelUtil.getValueDescriptor(attr.type) || {};}}- if (attr) {- this._type = AssetModelUtil.getValueDescriptor(attr.type) || {};+ if (!this._type || !this._type.name) {+ this._loading = false;+ return;}- }- if (!this._type || !this._type.name) {- this._loading = false;- return;- }+ let interval: DatapointInterval = DatapointInterval.HOUR;+ let stepSize = 1;++ switch (this.period) {+ case "hour":+ interval = DatapointInterval.MINUTE;+ stepSize = 5;+ break;+ case "day":+ interval = DatapointInterval.HOUR;+ stepSize = 1;+ break;+ case "week":+ interval = DatapointInterval.HOUR;+ stepSize = 6;+ break;+ case "month":+ interval = DatapointInterval.DAY;+ stepSize = 1;+ break;+ case "year":+ interval = DatapointInterval.MONTH;+ stepSize = 1;+ break;+ }- let interval: DatapointInterval = DatapointInterval.HOUR;- let stepSize = 1;-- switch (this.period) {- case "hour":- interval = DatapointInterval.MINUTE;- stepSize = 5;- break;- case "day":- interval = DatapointInterval.HOUR;- stepSize = 1;- break;- case "week":- interval = DatapointInterval.HOUR;- stepSize = 6;- break;- case "month":- interval = DatapointInterval.DAY;- stepSize = 1;- break;- case "year":- interval = DatapointInterval.MONTH;- stepSize = 1;- break;- }+ const lowerCaseInterval = interval.toLowerCase();+ this._startOfPeriod = moment(this.toTimestamp).subtract(1, this.period).startOf(lowerCaseInterval as moment.unitOfTime.StartOf).add(1, lowerCaseInterval as moment.unitOfTime.Base).toDate().getTime();+ this._endOfPeriod = moment(this.toTimestamp).startOf(lowerCaseInterval as moment.unitOfTime.StartOf).add(1, lowerCaseInterval as moment.unitOfTime.Base).toDate().getTime();+ this._timeUnits = lowerCaseInterval as TimeUnit;+ this._stepSize = stepSize;++ const isChart = this._type && (this._type.jsonType === "number" || this._type.jsonType === "boolean");+ let response;+ if(isChart) {+ response = await manager.rest.api.AssetDatapointResource.getDatapoints(+ assetId,+ attributeName,+ {+ type: "lttb",+ fromTimestamp: this._startOfPeriod,+ toTimestamp: this._endOfPeriod,+ amountOfPoints: 100+ },+ { signal: this._dataAbortController.signal }+ );+ } else {+ response = await manager.rest.api.AssetDatapointResource.getDatapoints(+ assetId,+ attributeName,+ {+ type: "all",+ fromTimestamp: this._startOfPeriod,+ toTimestamp: this._endOfPeriod+ },+ { signal: this._dataAbortController.signal }+ );+ }- const lowerCaseInterval = interval.toLowerCase();- this._startOfPeriod = moment(this.toTimestamp).subtract(1, this.period).startOf(lowerCaseInterval as moment.unitOfTime.StartOf).add(1, lowerCaseInterval as moment.unitOfTime.Base).toDate().getTime();- this._endOfPeriod = moment(this.toTimestamp).startOf(lowerCaseInterval as moment.unitOfTime.StartOf).add(1, lowerCaseInterval as moment.unitOfTime.Base).toDate().getTime();- this._timeUnits = lowerCaseInterval as TimeUnit;- this._stepSize = stepSize;+ this._loading = false;- const isChart = this._type && (this._type.jsonType === "number" || this._type.jsonType === "boolean");- let response;- if(isChart) {- response = await manager.rest.api.AssetDatapointResource.getDatapoints(- assetId,- attributeName,- {- type: "lttb",- fromTimestamp: this._startOfPeriod,- toTimestamp: this._endOfPeriod,- amountOfPoints: 100- }- )- } else {- response = await manager.rest.api.AssetDatapointResource.getDatapoints(- assetId,- attributeName,- {- type: "all",- fromTimestamp: this._startOfPeriod,- toTimestamp: this._endOfPeriod- }- );- }+ if (response.status === 200) {+ this._data = response.data.filter(value => value.y !== null && value.y !== undefined) as ScatterDataPoint[];+ this._dataFirstLoaded = true;+ }- this._loading = false;+ } catch (ex) {+ console.error(ex);+ if((ex as Error)?.message === "canceled") {+ return; // If request has been canceled (using AbortController); return, and prevent _loading is set to false.+ }+ this._loading = false;- if (response.status === 200) {- this._data = response.data.filter(value => value.y !== null && value.y !== undefined) as ScatterDataPoint[];- this._dataFirstLoaded = true;+ if(isAxiosError(ex)) {+ if(ex.message.includes("timeout of 10000ms exceeded")) {+ this._error = "noAttributeDataTimeout";+ return;+ }+ }+ this._error = "errorOccurred";}}+protected _updateTimestamp(timestamp: Date, forward?: boolean, timeout= 300) {if (this._updateTimestampTimer) {diff --git a/ui/component/or-dashboard-builder/src/util/or-asset-widget.ts b/ui/component/or-dashboard-builder/src/util/or-asset-widget.tsindex 1782b4f07..c33fccca0 100644--- a/ui/component/or-dashboard-builder/src/util/or-asset-widget.ts+++ b/ui/component/or-dashboard-builder/src/util/or-asset-widget.ts@@ -3,7 +3,7 @@ import {Asset, AssetQuery, Attribute, AttributeRef} from "@openremote/model";import { state } from "lit/decorators.js";import manager from "@openremote/core";import { showSnackbar } from "@openremote/or-mwc-components/or-mwc-snackbar";-import {WidgetConfig} from "./widget-config";+import {isAxiosError} from "@openremote/rest";import {WidgetSettings} from "./widget-settings";import { CSSResult } from "lit";@@ -22,6 +22,9 @@ export abstract class OrAssetWidget extends OrWidget {@state() // cached attribute list; [asset index of the loadedAssets array, attribute]protected assetAttributes: [number, Attribute<any>][] = [];+ @state()+ protected _error?: string;+static get styles(): CSSResult[] {return [...super.styles];}@@ -83,8 +86,6 @@ export abstract class AssetWidgetSettings extends WidgetSettings {// Simple async function for fetching assets by attributeRefsasync function fetchAssetsByAttributeRef(attributeRefs: AttributeRef[] = []) {- const assetIds = attributeRefs.map(ar => ar.id!);- const attributeNames = attributeRefs.map(ar => ar.name!);return fetchAssets({ids: attributeRefs?.map((x: AttributeRef) => x.id) as string[],select: {@@ -93,14 +94,26 @@ async function fetchAssetsByAttributeRef(attributeRefs: AttributeRef[] = []) {});}+/**+ * Function that will fetch an array of assets based on {@link assetQuery}.+ * On failure, by default, it will only log to the web browser console.+ * In some cases it will throw a custom error, that holds a custom message.+ */async function fetchAssets(assetQuery: AssetQuery) {let assets: Asset[] = [];assetQuery.realm = { name: manager.displayRealm };await manager.rest.api.AssetResource.queryAssets(assetQuery).then(response => {assets = response.data;- }).catch((reason) => {- console.error(reason);+ }).catch((e) => {+ console.error(e);showSnackbar(undefined, "errorOccurred");+ if(isAxiosError(e)) {+ if(e.message === "Network Error") {+ throw new Error("youAreOffline")+ } else if(e.code === "ECONNABORTED") {+ throw new Error("noAttributeDataTimeout")+ }+ }});return assets;}diff --git a/ui/component/or-dashboard-builder/src/widgets/attribute-input-widget.ts b/ui/component/or-dashboard-builder/src/widgets/attribute-input-widget.tsindex c5114b69a..7c7e658f8 100644--- a/ui/component/or-dashboard-builder/src/widgets/attribute-input-widget.ts+++ b/ui/component/or-dashboard-builder/src/widgets/attribute-input-widget.ts@@ -33,6 +33,14 @@ const styling = css`align-items: center;overflow: hidden;}++ #error-txt {+ height: 100%;+ display: flex;+ justify-content: center;+ align-items: center;+ text-align: center;+ }.attr-input {width: 100%;@@ -93,7 +101,9 @@ export class AttributeInputWidget extends OrAssetWidget {// If widgetConfig, and the attributeRefs of them have changed...if(changedProps.has("widgetConfig") && this.widgetConfig) {const attributeRefs = this.widgetConfig.attributeRefs;- if(attributeRefs.length > 0 && !this.isAttributeRefLoaded(attributeRefs[0])) {+ if(attributeRefs.length === 0) {+ this._error = "noAttributesConnected";+ } else if(attributeRefs.length > 0 && !this.isAttributeRefLoaded(attributeRefs[0])) {this.loadAssets(attributeRefs);}}@@ -113,9 +123,16 @@ export class AttributeInputWidget extends OrAssetWidget {}protected loadAssets(attributeRefs: AttributeRef[]) {+ if(attributeRefs.length === 0) {+ this._error = "noAttributesConnected";+ return;+ }this._loading = true;+ this._error = undefined;this.fetchAssets(attributeRefs).then((assets) => {this.loadedAssets = assets;+ }).catch(e => {+ this._error = e.message;}).finally(() => {this._loading = false;});@@ -126,10 +143,13 @@ export class AttributeInputWidget extends OrAssetWidget {const attribute = (config.attributeRefs.length > 0 && this.loadedAssets[0]?.attributes) ? this.loadedAssets[0].attributes[config.attributeRefs[0].name!] : undefined;const readOnlyMetaItem = Util.getMetaValue(WellknownMetaItems.READONLY, attribute);return html`- ${when(this._loading, () => {- return html`- <or-loading-indicator></or-loading-indicator>- `;++ ${when(this._loading || this._error, () => {+ if(this._loading) {+ return html`<or-loading-indicator></or-loading-indicator>`;+ } else {+ return html`<or-translate id="error-txt" .value="${this._error}"></or-translate>`;+ }}, () => when(config.attributeRefs.length > 0 && attribute && this.loadedAssets && this.loadedAssets.length > 0, () => {return html`<div id="widget-wrapper">@@ -143,12 +163,6 @@ export class AttributeInputWidget extends OrAssetWidget {></or-attribute-input></div>`;- }, () => {- return html`- <div style="height: 100%; display: flex; justify-content: center; align-items: center;">- <span><or-translate value="noAttributesConnected"></or-translate></span>- </div>- `;}))}`;}diff --git a/ui/component/or-dashboard-builder/src/widgets/chart-widget.ts b/ui/component/or-dashboard-builder/src/widgets/chart-widget.tsindex 6bd183829..e7c617fd9 100644--- a/ui/component/or-dashboard-builder/src/widgets/chart-widget.ts+++ b/ui/component/or-dashboard-builder/src/widgets/chart-widget.ts@@ -146,17 +146,26 @@ export class ChartWidget extends OrAssetWidget {this.datapointQuery = this.widgetConfig.datapointQuery;const attributeRefs = this.widgetConfig.attributeRefs;- const missingAssets = attributeRefs?.filter((attrRef: AttributeRef) => !this.isAttributeRefLoaded(attrRef));- if (missingAssets.length > 0) {- this.loadAssets(attributeRefs);+ if(attributeRefs.length === 0) {+ this._error = "noAttributesConnected";+ } else {+ const missingAssets = attributeRefs?.filter((attrRef: AttributeRef) => !this.isAttributeRefLoaded(attrRef));+ if (missingAssets.length > 0) {+ this.loadAssets(attributeRefs);+ }}}return super.willUpdate(changedProps);}- protected loadAssets(attributeRefs: AttributeRef[]) {+ protected loadAssets(attributeRefs: AttributeRef[]): void {+ if(attributeRefs.length === 0) {+ this._error = "noAttributesConnected";+ return;+ }this._loading = true;+ this._error = undefined;this.fetchAssets(attributeRefs).then((assets) => {this.loadedAssets = assets;this.assetAttributes = attributeRefs?.map((attrRef: AttributeRef) => {@@ -164,6 +173,8 @@ export class ChartWidget extends OrAssetWidget {const foundAsset = assetIndex >= 0 ? assets[assetIndex] : undefined;return foundAsset && foundAsset.attributes ? [assetIndex, foundAsset.attributes[attrRef.name!]] : undefined;}).filter((indexAndAttr: any) => !!indexAndAttr) as [number, Attribute<any>][];+ }).catch(e => {+ this._error = e.message;}).finally(() => {this._loading = false;});@@ -173,7 +184,13 @@ export class ChartWidget extends OrAssetWidget {return html`${when(this._loading, () => html`<or-loading-indicator></or-loading-indicator>- `, () => when(this.loadedAssets && this.assetAttributes && this.loadedAssets.length > 0 && this.assetAttributes.length > 0, () => {++ `, () => when(this._error, () => html`+ <div style="height: 100%; display: flex; justify-content: center; align-items: center; text-align: center;">+ <span><or-translate .value="${this._error}"></or-translate></span>+ </div>++ `, () => {return html`<or-chart .assets="${this.loadedAssets}" .assetAttributes="${this.assetAttributes}" .rightAxisAttributes="${this.widgetConfig.rightAxisAttributes}".showLegend="${(this.widgetConfig?.showLegend != null) ? this.widgetConfig?.showLegend : true}"@@ -183,12 +200,6 @@ export class ChartWidget extends OrAssetWidget {style="height: 100%"></or-chart>`;- }, () => {- return html`- <div style="height: 100%; display: flex; justify-content: center; align-items: center;">- <span><or-translate value="noAttributesConnected"></or-translate></span>- </div>- `;}))}`;}diff --git a/ui/component/or-dashboard-builder/src/widgets/gauge-widget.ts b/ui/component/or-dashboard-builder/src/widgets/gauge-widget.tsindex bf6b5c5dd..fe0d3e1c1 100644--- a/ui/component/or-dashboard-builder/src/widgets/gauge-widget.ts+++ b/ui/component/or-dashboard-builder/src/widgets/gauge-widget.ts@@ -1,4 +1,4 @@-import {html, TemplateResult} from "lit";+import {html, css, TemplateResult} from "lit";import {customElement, state} from "lit/decorators.js";import {OrAssetWidget} from "../util/or-asset-widget";import {WidgetConfig} from "../util/widget-config";@@ -29,6 +29,16 @@ function getDefaultWidgetConfig(): GaugeWidgetConfig {};}+const styling = css`+ #error-txt {+ height: 100%;+ display: flex;+ justify-content: center;+ align-items: center;+ text-align: center;+ }+`;+@customElement("gauge-widget")export class GaugeWidget extends OrAssetWidget {@@ -60,6 +70,10 @@ export class GaugeWidget extends OrAssetWidget {this.loadAssets(this.widgetConfig.attributeRefs);}+ static get styles() {+ return [...super.styles, styling];+ }+// WebComponent lifecycle method, that occurs DURING every state updateprotected willUpdate(changedProps: Map<string, any>) {@@ -80,7 +94,12 @@ export class GaugeWidget extends OrAssetWidget {}protected loadAssets(attributeRefs: AttributeRef[]) {+ if(attributeRefs.length === 0) {+ this._error = "noAttributesConnected";+ return;+ }this._loading = true;+ this._error = undefined;this.fetchAssets(attributeRefs).then((assets) => {this.loadedAssets = assets;this.assetAttributes = attributeRefs?.map((attrRef: AttributeRef) => {@@ -88,6 +107,8 @@ export class GaugeWidget extends OrAssetWidget {const foundAsset = assetIndex >= 0 ? assets[assetIndex] : undefined;return foundAsset && foundAsset.attributes ? [assetIndex, foundAsset.attributes[attrRef.name!]] : undefined;}).filter((indexAndAttr: any) => !!indexAndAttr) as [number, Attribute<any>][];+ }).catch(e => {+ this._error = e.message;}).finally(() => {this._loading = false;});@@ -96,10 +117,12 @@ export class GaugeWidget extends OrAssetWidget {protected render(): TemplateResult {return html`- ${when(this._loading, () => {- return html`- <or-loading-indicator></or-loading-indicator>- `;+ ${when(this._loading || this._error, () => {+ if(this._loading) {+ return html`<or-loading-indicator></or-loading-indicator>`;+ } else {+ return html`<or-translate id="error-txt" .value="${this._error}"></or-translate>`;+ }}, () => when(this.loadedAssets && this.assetAttributes && this.loadedAssets.length > 0 && this.assetAttributes.length > 0, () => {return html`<or-gauge .asset="${this.loadedAssets[0]}" .assetAttribute="${this.assetAttributes[0]}" .thresholds="${this.widgetConfig.thresholds}"@@ -109,7 +132,7 @@ export class GaugeWidget extends OrAssetWidget {`;}, () => {return html`- <div style="height: 100%; display: flex; justify-content: center; align-items: center;">+ <div style="height: 100%; display: flex; justify-content: center; align-items: center; text-align: center;"><span><or-translate value="noAttributeConnected"></or-translate></span></div>`;diff --git a/ui/component/or-dashboard-builder/src/widgets/kpi-widget.ts b/ui/component/or-dashboard-builder/src/widgets/kpi-widget.tsindex b3b49e9ae..4be52f2db 100644--- a/ui/component/or-dashboard-builder/src/widgets/kpi-widget.ts+++ b/ui/component/or-dashboard-builder/src/widgets/kpi-widget.ts@@ -76,7 +76,12 @@ export class KpiWidget extends OrAssetWidget {}protected loadAssets(attributeRefs: AttributeRef[]) {+ if(attributeRefs.length === 0) {+ this._error = "noAttributesConnected";+ return;+ }this._loading = true;+ this._error = undefined;this.fetchAssets(attributeRefs).then((assets) => {this.loadedAssets = assets;this.assetAttributes = attributeRefs?.map((attrRef: AttributeRef) => {@@ -84,6 +89,8 @@ export class KpiWidget extends OrAssetWidget {const foundAsset = assetIndex >= 0 ? assets[assetIndex] : undefined;return foundAsset && foundAsset.attributes ? [assetIndex, foundAsset.attributes[attrRef.name!]] : undefined;}).filter((indexAndAttr: any) => !!indexAndAttr) as [number, Attribute<any>][];+ }).catch(e => {+ this._error = e.message;}).finally(() => {this._loading = false;});@@ -92,17 +99,21 @@ export class KpiWidget extends OrAssetWidget {protected render(): TemplateResult {return html`<div style="position: relative; height: 100%; overflow: hidden;">- ${when(this._loading, () => {+ ${when(this._loading || this._error, () => {// Have to use `position: absolute` with white background due to rendering inconsistencies in or-attribute-cardreturn html`- <div style="position: absolute; top: -5%; width: 100%; height: 105%; background: white; z-index: 1;">- <or-loading-indicator></or-loading-indicator>+ <div style="position: absolute; top: -5%; width: 100%; height: 105%; background: white; z-index: 1; display: flex; justify-content: center; align-items: center; text-align: center;">+ ${when(this._loading, () => html`+ <or-loading-indicator></or-loading-indicator>+ `, () => html`+ <or-translate .value="${this._error}"></or-translate>+ `)}</div>`;})}<or-attribute-card .assets="${this.loadedAssets}" .assetAttributes="${this.assetAttributes}" .period="${this.widgetConfig.period}".deltaFormat="${this.widgetConfig.deltaFormat}" .mainValueDecimals="${this.widgetConfig.decimals}"- showControls="${this.widgetConfig?.showTimestampControls}" showTitle="${false}" style="height: 100%;">+ showControls="${this.widgetConfig?.showTimestampControls}" showTitle="${false}" hideAttributePicker="${true}" style="height: 100%;"></or-attribute-card></div>`;