Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Major rewrite of Insights widget handling, and added dashboard interval feature. (#1165)

Martin Peeters226f9e543175
diff --git a/manager/src/web/shared/locales/en/or.json b/manager/src/web/shared/locales/en/or.json
index 9c78be9ee..3505c62ab 100644
--- a/manager/src/web/shared/locales/en/or.json
+++ b/manager/src/web/shared/locales/en/or.json
@@ -608,6 +608,8 @@
"chartConfig": "Chart Configuration",
"markerCoordinates": "Marker Coordinates",
"imageSettings": "Image Settings",
+ "dataManagement": "Data Options",
+ "defaultRefreshInterval": "Default refresh interval",
"presets.wrap_to_single_column": "Wrap to single column",
"presets.keep_layout": "Keep layout",
"presets.block_device": "Block this device",
@@ -622,6 +624,11 @@
"access.public": "Public",
"access.shared": "Realm Users",
"access.private": "Only me",
+ "interval.off": "Off",
+ "interval.one_min": "1 min",
+ "interval.five_min": "5 min",
+ "interval.quarter": "15 min",
+ "interval.one_hour": "1 hour",
"saveSuccessful": "Saved dashboard successfully!",
"initialName": "New Dashboard",
"openInNewTab": "Open in new tab",
diff --git a/manager/src/web/shared/locales/nl/or.json b/manager/src/web/shared/locales/nl/or.json
index 04bb0228e..7ae73de78 100644
--- a/manager/src/web/shared/locales/nl/or.json
+++ b/manager/src/web/shared/locales/nl/or.json
@@ -608,6 +608,8 @@
"chartConfig": "Grafiek configuratie",
"markerCoordinates": "Marker coordinaten",
"imageSettings": "Afbeeldingsinstellingen",
+ "dataManagement": "Weergave van data",
+ "defaultRefreshInterval": "Standaard interval van data verversen",
"presets.wrap_to_single_column": "Widgets onder elkaar zetten",
"presets.keep_layout": "Behoud indeling",
"presets.block_device": "Blokkeer dit apparaat",
@@ -622,6 +624,11 @@
"access.public": "Openbaar",
"access.shared": "Realm gebruikers",
"access.private": "Alleen ik",
+ "interval.off": "Uit",
+ "interval.one_min": "1 min",
+ "interval.five_min": "5 min",
+ "interval.quarter": "15 min",
+ "interval.one_hour": "1 uur",
"saveSuccessful": "Dashboard succesvol opgeslagen!",
"initialName": "Nieuw dashboard",
"openInNewTab": "Openen in een nieuw tabblad",
diff --git a/model/src/main/java/org/openremote/model/dashboard/DashboardRefreshInterval.java b/model/src/main/java/org/openremote/model/dashboard/DashboardRefreshInterval.java
new file mode 100644
index 000000000..c06d95ca5
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/dashboard/DashboardRefreshInterval.java
@@ -0,0 +1,5 @@
+package org.openremote.model.dashboard;
+
+public enum DashboardRefreshInterval {
+ OFF, ONE_MIN, FIVE_MIN, QUARTER, ONE_HOUR
+}
diff --git a/model/src/main/java/org/openremote/model/dashboard/DashboardTemplate.java b/model/src/main/java/org/openremote/model/dashboard/DashboardTemplate.java
index 3cb4966b8..47cedb2ea 100644
--- a/model/src/main/java/org/openremote/model/dashboard/DashboardTemplate.java
+++ b/model/src/main/java/org/openremote/model/dashboard/DashboardTemplate.java
@@ -15,6 +15,9 @@ public class DashboardTemplate {
@Min(value = 1, message = "${Dashboard.template.maxScreenWidth.Min}")
protected int maxScreenWidth;
+ @Valid
+ protected DashboardRefreshInterval refreshInterval;
+
@NotNull(message = "{Dashboard.template.screenPresets.NotNull}")
@Valid
protected DashboardScreenPreset[] screenPresets;
@@ -32,18 +35,21 @@ public class DashboardTemplate {
public DashboardTemplate(DashboardScreenPreset[] screenPresets) {
this.columns = 1;
this.maxScreenWidth = 1;
+ this.refreshInterval = DashboardRefreshInterval.OFF;
this.screenPresets = screenPresets;
}
public void setId(String id) { this.id = id; }
public void setColumns(int columns) { this.columns = columns; }
public void setMaxScreenWidth(int maxScreenWidth) { this.maxScreenWidth = maxScreenWidth; }
+ public void setRefreshInterval(DashboardRefreshInterval interval) { this.refreshInterval = interval; }
public void setScreenPresets(DashboardScreenPreset[] screenPresets) { this.screenPresets = screenPresets; }
public void setWidgets(DashboardWidget[] widgets) { this.widgets = widgets; }
public String getId() { return id; }
public int getColumns() { return columns; }
public int getMaxScreenWidth() { return maxScreenWidth; }
+ public DashboardRefreshInterval getRefreshInterval() { return this.refreshInterval; }
public DashboardScreenPreset[] getScreenPresets() { return screenPresets; }
public DashboardWidget[] getWidgets() { return widgets; }
}
diff --git a/ui/app/insights/src/pages/page-view.ts b/ui/app/insights/src/pages/page-view.ts
index aff24991c..1a09e6185 100644
--- a/ui/app/insights/src/pages/page-view.ts
+++ b/ui/app/insights/src/pages/page-view.ts
@@ -236,7 +236,7 @@ export class PageView extends Page<AppStateKeyed> {
${getDashboardHeaderTemplate(!this.viewDashboardOnly, selected, () => this.dashboardMenu?.toggleDrawer(), () => this.rerenderPending = true)}
<div style="flex: 1;">
${guard([this._selectedId, this._loadedDashboards, this.rerenderPending], () => html`
- ${when(this._selectedId && selected != undefined, () => html`
+ ${when(this._selectedId && selected !== undefined, () => html`
<or-dashboard-preview style="background: transparent;" .rerenderPending="${this.rerenderPending}"
.realm="${manager.displayRealm}" .template="${selected?.template}" .editMode="${false}"
.fullscreen="${true}" .readonly="${true}"
diff --git a/ui/component/or-dashboard-builder/README.md b/ui/component/or-dashboard-builder/README.md
index cce52a090..fdf257aa3 100644
--- a/ui/component/or-dashboard-builder/README.md
+++ b/ui/component/or-dashboard-builder/README.md
@@ -1 +1,156 @@
-Documentation coming soon.
+# or-dashboard-builder
+### All-in-one bundle for creating dashboards with OpenRemote data.
+
+This component is the core of the Insights page on our OpenRemote manager,<br />
+where users can build dashboards with widgets, for monitoring their assets in their preferred way.<br />
+It is quite an extensive piece of code, so some apps using this (such as or standalone Insights app)<br />
+might not need the full package.<br />
+<br />
+It is structured to support the additions of custom widgets, whereof a short tutorial is shown below.
+
+
+---
+
+## Install
+```bash
+npm i @openremote/or-dashboard-builder
+yarn add @openremote/or-dashboard-builder
+```
+
+
+
+## Terminology:
+
+To be clear about what all functionalities are meant for, we created a list of terms used within `or-dashboard-builder`.
+Here it is:
+
+| Term | Definition |
+|---------------|--------------------------------------------------------------------------------------------------------------------------------------------------|
+| **Dashboard** | The board / area that contains widgets. (stored in database) |
+| **Widget** | The object on the dashboard that contains information like content (stored in database) |
+| *WidgetContainer* | Wrapper that displays widget content, header, and its actions |
+| *WidgetSettings* | The available settings to customise WidgetConfig,
+| **Insights** | 'The showcase term' we use for the page in our Manager App. We also have an "Insights app" that is a standalone app for viewing your dashboards. |
+
+<br/>
+
+Here is an overview of all elements used:
+
+| HTML Tag | Description |
+|----------------------------|----------------------------------------------------------------------------------|
+| or-dashboard-builder | Contains the layout of the full dashboard builder. Keeps track of state as well. |
+| or-dashboard-preview | Manages grid, and the widgets loaded onto it. |
+| or-dashboard-browser | Lists widget(s) in cards that can be dragged onto `or-dashboard-preview` |
+| or-dashboard-tree | Lists dashboards |
+| or-dashboard-boardsettings | Managing dashboard settings |
+| or-dashboard-widgetsettings | Wrapper that displays settings of the selected widget (`or-widget-settings`)
+| or-widget-container | Manages the loaded widget in that container |
+| or-widget-settings | Loads and saves widget settings based on the selected widget. |
+
+*or-dashboard-engine is a logic class to inject in Gridstack for overriding grid behavior.*<br />
+*or-dashboard-keyhandler is used to handle keystrokes from the user*
+<br />
+<br />
+
+## Creating your own Widget
+
+Add your widget manifest to the `registerWidgetTypes()` function in `index.ts`.<br />
+This will register the widget, and handle all functions automatically.
+```typescript
+export function registerWidgetTypes() {
+ widgetTypes.set("linechart", ChartWidget.getManifest());
+ widgetTypes.set("gauge", GaugeWidget.getManifest());
+ ...
+ // add here
+}
+```
+
+From there, you can add your custom class to the `/widgets` folder and build your HTMLElements.<br />
+It is **required** to inherit from `or-widget`, *(or an extended class of it such as or-asset-widget)*<br />
+and your custom config should extend on `WidgetConfig`<br />
+<br />
+
+
+### Example of a custom Widget
+
+Here is a code example of how to create custom widgets.<br />
+Feel free to copy, put it in seperate files, and adjust it to your needs.<br />
+Looking into our existing widgets also helps understanding the codebase.
+
+```typescript
+import {CustomWidgetConfig} from "./custom-widget";
+
+export interface CustomWidgetConfig extends WidgetConfig {
+ attributeRefs: AttributeRef[];
+ customFieldOne: string;
+ customFieldTwo: number;
+}
+
+function getDefaultWidgetConfig(): CustomWidgetConfig {
+ return {
+ attributeRefs: [],
+ customFieldOne: "default text",
+ customFieldTwo: 0
+ };
+}
+
+@customElement("custom-widget")
+export class CustomWidget extends OrWidget {
+
+ // Override of widgetConfig with extended type
+ protected readonly widgetConfig!: CustomWidgetConfig;
+
+ static getManifest(): WidgetManifest {
+ return {
+ displayName: "Custom widget", // name to display in widget browser
+ displayIcon: "gauge", // icon to display in widget browser. Uses <or-icon> and https://materialdesignicons.com
+ minColumnWidth: 1,
+ minColumnHeight: 1,
+ getContentHtml(config: CustomWidgetConfig): OrWidget {
+ return new CustomWidget(config);
+ },
+ getSettingsHtml(config: CustomWidgetConfig): WidgetSettings {
+ return new CustomSettings(config);
+ },
+ getDefaultConfig(): CustomWidgetConfig {
+ return getDefaultWidgetConfig();
+ }
+ }
+ }
+
+ public refreshContent(force: boolean) {
+ // function that executes on refresh of the widget.
+ // It's normally a 'silent' function that, for example, fetches the data of assets again.
+ }
+
+ protected render(): TemplateResult {
+ return html`
+ <span>Custom field one: </span>
+ <span>${this.widgetConfig.customFieldOne}</span>
+ `;
+ }
+
+}
+
+// Settings element
+// This can be placed in a seperate file if preferred.
+@customElement("custom-settings")
+export class CustomSettings extends WidgetSettings {
+
+ // Override of widgetConfig with extended type
+ protected readonly widgetConfig!: CustomWidgetConfig;
+
+ protected render(): TemplateResult {
+ return html`
+ <span>Custom settings</span>
+ <button @click="${() => this.onButtonClick()}">Click to customize text</button>
+ `;
+ }
+
+ protected onButtonClick() {
+ this.widgetConfig.customFieldOne = "custom text";
+ this.notifyConfigUpdate();
+ }
+}
+
+```
diff --git a/ui/component/or-dashboard-builder/src/controls/dashboard-refresh-controls.ts b/ui/component/or-dashboard-builder/src/controls/dashboard-refresh-controls.ts
new file mode 100644
index 000000000..923efe932
--- /dev/null
+++ b/ui/component/or-dashboard-builder/src/controls/dashboard-refresh-controls.ts
@@ -0,0 +1,93 @@
+import {InputType} from "@openremote/or-mwc-components/or-mwc-input";
+import {ListItem} from "@openremote/or-mwc-components/or-mwc-list";
+import {getContentWithMenuTemplate} from "@openremote/or-mwc-components/or-mwc-menu";
+import {html, LitElement, PropertyValues, TemplateResult} from "lit";
+import {customElement, property} from "lit/decorators.js";
+import {when} from "lit/directives/when.js";
+import {i18next} from "@openremote/or-translate";
+import {DashboardRefreshInterval} from "@openremote/model";
+
+export function intervalToMillis(interval: DashboardRefreshInterval): number | undefined {
+ switch (interval) {
+ case DashboardRefreshInterval.OFF:
+ return undefined;
+ case DashboardRefreshInterval.ONE_MIN:
+ return (60 * 1000);
+ case DashboardRefreshInterval.FIVE_MIN:
+ return (5 * 60 * 1000);
+ case DashboardRefreshInterval.QUARTER:
+ return (15 * 60 * 1000);
+ case DashboardRefreshInterval.ONE_HOUR:
+ return (60 * 60 * 1000);
+ default:
+ return undefined;
+ }
+}
+
+export class IntervalSelectEvent extends CustomEvent<DashboardRefreshInterval> {
+
+ public static readonly NAME = "interval-select";
+
+ constructor(interval: DashboardRefreshInterval) {
+ super(IntervalSelectEvent.NAME, {
+ bubbles: true,
+ composed: true,
+ detail: interval
+ });
+ }
+}
+
+@customElement("dashboard-refresh-controls")
+export class DashboardRefreshControls extends LitElement {
+
+ @property()
+ protected interval: DashboardRefreshInterval = DashboardRefreshInterval.OFF;
+
+ @property()
+ protected readonly = true;
+
+ // TODO: Replace this with Object.values(), after generated typescript enums support this. ('const' variable issue in model.ts)
+ protected intervalOptions = [DashboardRefreshInterval.OFF, DashboardRefreshInterval.ONE_MIN, DashboardRefreshInterval.FIVE_MIN, DashboardRefreshInterval.QUARTER, DashboardRefreshInterval.ONE_HOUR]
+
+ protected willUpdate(changedProps: PropertyValues) {
+ super.willUpdate(changedProps);
+ if (changedProps.has("interval") && this.interval !== undefined) {
+ this.dispatchEvent(new IntervalSelectEvent(this.interval));
+ }
+ }
+
+ protected render(): TemplateResult {
+ const intervalOptions: string[] = this.getRefreshOptions();
+ const value = this.getIntervalString(this.interval);
+ return html`
+ <div style="height: 100%; display: flex; align-items: center;">
+ ${when(this.readonly, () => html`
+ <or-mwc-input .type="${InputType.BUTTON}" .label="${i18next.t(value)}" disabled="true"></or-mwc-input>
+ `, () => html`
+ ${getContentWithMenuTemplate(
+ html`<or-mwc-input .type="${InputType.BUTTON}" .label="${i18next.t(value)}"></or-mwc-input>`,
+ intervalOptions.map(o => ({value: o} as ListItem)),
+ value,
+ (newVal) => this.onIntervalSelect(intervalOptions, newVal as string),
+ undefined,
+ false,
+ true,
+ true
+ )}
+ `)}
+ </div>
+ `;
+ }
+
+ protected onIntervalSelect(stringOptions: string[], value: string) {
+ this.interval = this.intervalOptions[stringOptions.indexOf(value as DashboardRefreshInterval)];
+ }
+
+ protected getIntervalString(interval: DashboardRefreshInterval): string {
+ return (`dashboard.interval.${interval.toLowerCase()}`);
+ }
+
+ protected getRefreshOptions(): string[] {
+ return this.intervalOptions.map(interval => this.getIntervalString(interval));
+ }
+}
diff --git a/ui/component/or-dashboard-builder/src/index.ts b/ui/component/or-dashboard-builder/src/index.ts
index e0468635d..d286ee024 100644
--- a/ui/component/or-dashboard-builder/src/index.ts
+++ b/ui/component/or-dashboard-builder/src/index.ts
@@ -1,5 +1,5 @@
-import {css, html, LitElement, unsafeCSS} from "lit";
-import {customElement, property, state} from "lit/decorators.js";
+import {css, html, LitElement, PropertyValues, unsafeCSS} from "lit";
+import {customElement, property, query, state} from "lit/decorators.js";
import {when} from 'lit/directives/when.js';
import {styleMap} from 'lit/directives/style-map.js';
import "./or-dashboard-tree";
@@ -7,34 +7,27 @@ import "./or-dashboard-browser";
import "./or-dashboard-preview";
import "./or-dashboard-widgetsettings";
import "./or-dashboard-boardsettings";
+import "./controls/dashboard-refresh-controls";
import {InputType, OrInputChangedEvent} from '@openremote/or-mwc-components/or-mwc-input';
import "@openremote/or-icon";
import {style} from "./style";
-import {ORGridStackNode} from "./or-dashboard-preview";
-import {
- ClientRole,
- Dashboard,
- DashboardAccess,
- DashboardGridItem,
- DashboardScalingPreset,
- DashboardScreenPreset,
- DashboardTemplate,
- DashboardWidget
-} from "@openremote/model";
+import {ClientRole, Dashboard, DashboardAccess, DashboardRefreshInterval, DashboardScalingPreset, DashboardScreenPreset, DashboardTemplate, DashboardWidget} from "@openremote/model";
import manager, {DefaultColor1, DefaultColor3, DefaultColor5, Util} from "@openremote/core";
import {ListItem} from "@openremote/or-mwc-components/or-mwc-list";
import {OrMwcTabItem} from "@openremote/or-mwc-components/or-mwc-tabs";
import "@openremote/or-mwc-components/or-mwc-tabs";
import {showSnackbar} from "@openremote/or-mwc-components/or-mwc-snackbar";
import {i18next} from "@openremote/or-translate";
-import { showOkCancelDialog } from "@openremote/or-mwc-components/or-mwc-dialog";
+import {showOkCancelDialog} from "@openremote/or-mwc-components/or-mwc-dialog";
import {DashboardKeyEmitter} from "./or-dashboard-keyhandler";
-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";
-import {OrImageWidget} from "./widgets/or-image-widget";
+import {OrDashboardPreview} from "./or-dashboard-preview";
+import {WidgetManifest} from "./util/or-widget";
+import {ChartWidget} from "./widgets/chart-widget";
+import {GaugeWidget} from "./widgets/gauge-widget";
+import {IntervalSelectEvent, intervalToMillis} from "./controls/dashboard-refresh-controls";
+import {ImageWidget} from "./widgets/image-widget";
+import {KpiWidget} from "./widgets/kpi-widget";
+import {MapWidget} from "./widgets/map-widget";
// language=CSS
const styling = css`
@@ -208,14 +201,17 @@ export function getActivePreset(gridWidth: number, presets: DashboardScreenPrese
});
return activePreset;
}
-export const widgetTypes: Map<string, OrWidgetEntity> = new Map<string, OrWidgetEntity>();
+
+// A map containing a unique identifier as key, and a WidgetManifest (displayName, displayIcon and HTML tags) as value.
+// We will use this for or-dashboard-browser and to initialise widgets, based on the html tags.
+export const widgetTypes: Map<string, WidgetManifest> = new Map<string, WidgetManifest>();
export function registerWidgetTypes() {
- widgetTypes.set("linechart", new OrChartWidget());
- widgetTypes.set("kpi", new OrKpiWidget());
- widgetTypes.set("gauge", new OrGaugeWidget());
- widgetTypes.set("map", new OrMapWidget());
- widgetTypes.set("image", new OrImageWidget());
+ widgetTypes.set("linechart", ChartWidget.getManifest());
+ widgetTypes.set("gauge", GaugeWidget.getManifest());
+ widgetTypes.set("image", ImageWidget.getManifest());
+ widgetTypes.set("kpi", KpiWidget.getManifest());
+ widgetTypes.set("map", MapWidget.getManifest());
}
@customElement("or-dashboard-builder")
@@ -229,23 +225,23 @@ export class OrDashboardBuilder extends LitElement {
@property()
protected readonly config: DashboardBuilderConfig | undefined;
- @property() // Originally from URL
+ @property() // (originally from URL)
protected readonly editMode: boolean = false;
@property()
protected readonly fullscreen: boolean = true;
- @property() // Originally from URL
+ @property() // ID of the selected dashboard (originally from URL)
protected readonly selectedId: string | undefined;
- @property() // Originally just manager.displayRealm
- protected realm: string | undefined;
+ @property()
+ protected realm: string = manager.displayRealm;
@property() // REQUIRED userId
- protected userId: string | undefined;
+ protected readonly userId!: string;
@property()
- protected readonly: boolean = true;
+ protected readonly readonly: boolean = true;
/* ------------------- */
@@ -268,6 +264,9 @@ export class OrDashboardBuilder extends LitElement {
@state() // Used to toggle the SAVE button depending on whether changes have been made.
protected initialTemplateJSON: string | undefined;
+ @state()
+ protected refreshInterval: DashboardRefreshInterval = DashboardRefreshInterval.OFF;
+
@state()
protected isInitializing: boolean;
@@ -277,9 +276,10 @@ export class OrDashboardBuilder extends LitElement {
@state() // Whether changes have been made
protected hasChanged: boolean;
- @state()
- protected rerenderPending: boolean;
+ @query('or-dashboard-preview')
+ protected dashboardPreview?: OrDashboardPreview;
+ protected refreshTimer?: NodeJS.Timer;
private readonly keyEmitter: DashboardKeyEmitter = new DashboardKeyEmitter();
@@ -290,12 +290,11 @@ export class OrDashboardBuilder extends LitElement {
this.isInitializing = true;
this.isLoading = true;
this.hasChanged = false;
- this.rerenderPending = false;
registerWidgetTypes();
- this.updateComplete.then(async () => {
- await this.updateDashboards(this.realm!);
+ this.updateComplete.then(() => {
+ this.loadAllDashboards(this.realm);
});
}
@@ -310,91 +309,116 @@ export class OrDashboardBuilder extends LitElement {
this.keyEmitter.addListener('deselect', (_e: KeyboardEvent) => { this.deselectWidget(); });
this.keyEmitter.addListener('save', (_e: KeyboardEvent) => { this.saveDashboard(); });
}
+
disconnectedCallback() {
super.disconnectedCallback();
this.keyEmitter.removeAllListeners();
}
- async updateDashboards(realm: string) {
-
- // Getting dashboards
- await manager.rest.api.DashboardResource.getAllRealmDashboards(realm).then((result) => {
- this.dashboards = result.data;
- }).catch((reason) => {
- showSnackbar(undefined, i18next.t('errorOccurred'));
- console.error(reason);
- });
-
- // Setting dashboard if selectedId is given by parent component
- if(this.selectedId != undefined) {
- this.selectedDashboard = this.dashboards?.find(x => { return x.id == this.selectedId; });
- }
- }
+ willUpdate(changedProps: PropertyValues) {
+ super.willUpdate(changedProps);
- /* ------------- */
-
- // On every property update
- updated(changedProperties: Map<string, any>) {
this.isLoading = (this.dashboards == undefined);
this.isInitializing = (this.dashboards == undefined);
- if(this.realm == undefined) { this.realm = manager.displayRealm; }
// On any update (except widget selection), check whether hasChanged should be updated.
- if(!(changedProperties.size == 1 && changedProperties.has('selectedWidget'))) {
+ if(!(changedProps.size === 1 && changedProps.has('selectedWidget'))) {
const dashboardEqual = Util.objectsEqual(this.selectedDashboard, this.initialDashboardJSON ? JSON.parse(this.initialDashboardJSON) : undefined);
const templateEqual = Util.objectsEqual(this.currentTemplate, this.initialTemplateJSON ? JSON.parse(this.initialTemplateJSON) : undefined);
this.hasChanged = (!dashboardEqual || !templateEqual);
}
// Support for realm switching
- if(changedProperties.has("realm") && changedProperties.get("realm") != undefined) {
- this.updateDashboards(this.realm);
+ if(changedProps.has("realm") && changedProps.get("realm") !== undefined && this.realm) {
+ this.loadAllDashboards(this.realm);
}
// Any update on the dashboard
- if(changedProperties.has("selectedDashboard")) {
+ if(changedProps.has("selectedDashboard")) {
this.deselectWidget();
this.currentTemplate = this.selectedDashboard?.template;
+ if(!this.editMode) {
+ this.refreshInterval = this.currentTemplate?.refreshInterval || DashboardRefreshInterval.OFF;
+ changedProps.set('refreshInterval', this.refreshInterval);
+ }
this.dispatchEvent(new CustomEvent("selected", { detail: this.selectedDashboard }))
}
- // Update on the Grid and its widget
- if(changedProperties.has("currentTemplate")) {
- if(this.selectedDashboard != null) {
- this.selectedDashboard.template = this.currentTemplate;
- }
- }
// When edit/view mode gets toggled
- if(changedProperties.has("editMode")) {
+ if(changedProps.has("editMode")) {
this.deselectWidget();
+ this.refreshInterval = DashboardRefreshInterval.OFF;
this.showDashboardTree = true;
+ if(this.editMode) {
+ this.refreshInterval = DashboardRefreshInterval.OFF;
+ } else {
+ this.refreshInterval = this.currentTemplate?.refreshInterval || DashboardRefreshInterval.OFF;
+ }
+ changedProps.set('refreshInterval', this.refreshInterval);
+ }
+
+ // When refresh interval has changed
+ if(changedProps.has("refreshInterval") && this.refreshInterval) {
+ this.setRefreshTimer(intervalToMillis(this.refreshInterval));
}
}
- /* ----------------- */
+ protected setRefreshTimer(millis: number | undefined) {
+ this.clearRefreshTimer();
+ if(millis !== undefined) {
+ this.refreshTimer = setInterval(() => {
+ this.deselectWidget();
+ this.dashboardPreview?.refreshWidgets();
+ }, millis)
+ }
+ }
+
+ protected clearRefreshTimer() {
+ if(this.refreshTimer) {
+ clearInterval(this.refreshTimer);
+ this.refreshTimer = undefined;
+ }
+ }
+ async loadAllDashboards(realm: string) {
- createWidget(gridStackNode: ORGridStackNode): DashboardWidget {
- const randomId = (Math.random() + 1).toString(36).substring(2);
- let displayName = widgetTypes.get(gridStackNode.widgetTypeId)?.DISPLAY_NAME;
- if(displayName == undefined) { displayName = (i18next.t('dashboard.widget') + " #" + randomId); } // If no displayName, set random ID as name.
- const gridItem: DashboardGridItem = generateGridItem(gridStackNode, displayName);
+ // Getting dashboards
+ await manager.rest.api.DashboardResource.getAllRealmDashboards(realm).then((result) => {
+ this.dashboards = result.data;
+ }).catch((reason) => {
+ showSnackbar(undefined, i18next.t('errorOccurred'));
+ console.error(reason);
+ });
- const widget = {
- id: randomId,
- displayName: displayName,
- gridItem: gridItem,
- widgetTypeId: gridStackNode.widgetTypeId,
- } as DashboardWidget;
- widget.widgetConfig = widgetTypes.get(gridStackNode.widgetTypeId)?.getDefaultConfig(widget);
+ // Setting dashboard if selectedId is given by parent component
+ if(this.selectedId !== undefined) {
+ this.selectedDashboard = this.dashboards?.find(x => { return x.id == this.selectedId; });
+ }
+ }
+
+ /* ------------- */
+ // On every property update
+ updated(changedProperties: Map<string, any>) {
+ super.updated(changedProperties);
+
+ // Update on the Grid and its widget
+ if(changedProperties.has("currentTemplate")) {
+ if(this.selectedDashboard != null) {
+ this.selectedDashboard.template = this.currentTemplate;
+ }
+ }
+ }
+
+ /* ----------------- */
+
+ protected onWidgetCreation(widget: DashboardWidget): void {
const tempTemplate = JSON.parse(JSON.stringify(this.currentTemplate)) as DashboardTemplate;
- if(tempTemplate.widgets == undefined) {
+ if(!tempTemplate.widgets) {
tempTemplate.widgets = [];
}
- tempTemplate.widgets?.push(widget);
+ tempTemplate.widgets.push(widget);
this.currentTemplate = tempTemplate;
- return widget;
}
deleteWidget(widget: DashboardWidget) {
@@ -403,7 +427,7 @@ export class OrDashboardBuilder extends LitElement {
tempTemplate.widgets = tempTemplate.widgets?.filter((x: DashboardWidget) => { return x.id != widget.id; });
this.currentTemplate = tempTemplate;
}
- if(this.selectedWidgetId == widget.id) {
+ if(this.selectedWidgetId === widget.id) {
this.deselectWidget();
}
}
@@ -418,6 +442,7 @@ export class OrDashboardBuilder extends LitElement {
console.error("The selected widget does not exist!");
}
}
+
deselectWidget() {
this.selectedWidgetId = undefined;
}
@@ -511,6 +536,7 @@ export class OrDashboardBuilder extends LitElement {
{ icon: "content-copy", text: (i18next.t("copy") + " URL"), value: "copy" },
{ icon: "open-in-new", text: i18next.t("dashboard.openInNewTab"), value: "tab" },
];
+
private readonly tabItems: OrMwcTabItem[] = [
{ name: i18next.t("dashboard.widgets") }, { name: i18next.t("settings") }
];
@@ -551,21 +577,23 @@ export class OrDashboardBuilder extends LitElement {
</div>
<div id="header-actions">
<div id="header-actions-content">
- <or-mwc-input id="refresh-btn" class="small-btn" .disabled="${this.isLoading || (this.selectedDashboard == null)}" type="${InputType.BUTTON}" icon="refresh"
- @or-mwc-input-changed="${() => { this.rerenderPending = true; }}">
- </or-mwc-input>
- <or-mwc-input id="responsive-btn" class="small-btn" .disabled="${this.isLoading || (this.selectedDashboard == null)}" type="${InputType.BUTTON}" icon="responsive"
- @or-mwc-input-changed="${() => { this.dispatchEvent(new CustomEvent('fullscreenToggle', { detail: !this.fullscreen })); }}">
- </or-mwc-input>
- <or-mwc-input id="share-btn" class="small-btn" .disabled="${this.isLoading || (this.selectedDashboard == null)}" type="${InputType.BUTTON}" icon="open-in-new"
- @or-mwc-input-changed="${() => { this.openDashboardInInsights(); }}">
- </or-mwc-input>
- <or-mwc-input id="save-btn" ?hidden="${this._isReadonly() || !this._hasEditAccess()}" .disabled="${this.isLoading || !this.hasChanged || (this.selectedDashboard == null)}" type="${InputType.BUTTON}" raised label="${i18next.t('save')}"
- @or-mwc-input-changed="${() => { this.saveDashboard(); }}">
- </or-mwc-input>
- <or-mwc-input id="view-btn" ?hidden="${this._isReadonly() || !this._hasViewAccess()}" type="${InputType.BUTTON}" outlined icon="eye" label="${i18next.t('viewAsset')}"
- @or-mwc-input-changed="${() => { this.dispatchEvent(new CustomEvent('editToggle', { detail: false })); }}">
- </or-mwc-input>
+ ${when(this.selectedDashboard, () => html`
+ <or-mwc-input id="refresh-btn" class="small-btn" .disabled="${this.isLoading}" type="${InputType.BUTTON}" icon="refresh"
+ @or-mwc-input-changed="${() => { this.deselectWidget(); this.dashboardPreview?.refreshPreview(); }}">
+ </or-mwc-input>
+ <or-mwc-input id="responsive-btn" class="small-btn" .disabled="${this.isLoading}" type="${InputType.BUTTON}" icon="responsive"
+ @or-mwc-input-changed="${() => { this.dispatchEvent(new CustomEvent('fullscreenToggle', { detail: !this.fullscreen })); }}">
+ </or-mwc-input>
+ <or-mwc-input id="share-btn" class="small-btn" .disabled="${this.isLoading}" type="${InputType.BUTTON}" icon="open-in-new"
+ @or-mwc-input-changed="${() => { this.openDashboardInInsights(); }}">
+ </or-mwc-input>
+ <or-mwc-input id="save-btn" ?hidden="${this._isReadonly() || !this._hasEditAccess()}" .disabled="${this.isLoading || !this.hasChanged}" type="${InputType.BUTTON}" raised label="${i18next.t('save')}"
+ @or-mwc-input-changed="${() => { this.saveDashboard(); }}">
+ </or-mwc-input>
+ <or-mwc-input id="view-btn" ?hidden="${this._isReadonly() || !this._hasViewAccess()}" type="${InputType.BUTTON}" outlined icon="eye" label="${i18next.t('viewAsset')}"
+ @or-mwc-input-changed="${() => { this.dispatchEvent(new CustomEvent('editToggle', { detail: false })); }}">
+ </or-mwc-input>
+ `)}
</div>
</div>
</div>
@@ -580,14 +608,20 @@ export class OrDashboardBuilder extends LitElement {
</div>
<div id="fullscreen-header-actions">
<div id="fullscreen-header-actions-content">
- <or-mwc-input id="refresh-btn" class="small-btn" .disabled="${(this.selectedDashboard == null)}" type="${InputType.BUTTON}" icon="refresh"
- @or-mwc-input-changed="${() => { this.rerenderPending = true; }}"
- ></or-mwc-input>
- <or-mwc-input id="share-btn" class="small-btn" .disabled="${(this.selectedDashboard == null)}" type="${InputType.BUTTON}" icon="open-in-new"
- @or-mwc-input-changed="${() => { this.openDashboardInInsights(); }}"
- ></or-mwc-input>
- <or-mwc-input id="view-btn" class="hideMobile" ?hidden="${this.selectedDashboard == null || this._isReadonly() || !this._hasEditAccess()}" type="${InputType.BUTTON}" outlined icon="pencil" label="${i18next.t('editAsset')}"
- @or-mwc-input-changed="${() => { this.dispatchEvent(new CustomEvent('editToggle', { detail: true })); }}"></or-mwc-input>
+ ${when(this.selectedDashboard, () => html`
+ <or-mwc-input id="refresh-btn" class="small-btn" .disabled="${(this.selectedDashboard == null)}" type="${InputType.BUTTON}" icon="refresh"
+ @or-mwc-input-changed="${() => { this.deselectWidget(); this.dashboardPreview?.refreshPreview(); }}"
+ ></or-mwc-input>
+ <dashboard-refresh-controls .interval="${this.refreshInterval}" .readonly="${false}"
+ @interval-select="${(ev: IntervalSelectEvent) => this.onIntervalSelect(ev)}"
+ ></dashboard-refresh-controls>
+ <or-mwc-input id="share-btn" class="small-btn" .disabled="${(this.selectedDashboard == null)}" type="${InputType.BUTTON}" icon="open-in-new"
+ @or-mwc-input-changed="${() => { this.openDashboardInInsights(); }}"
+ ></or-mwc-input>
+ <or-mwc-input id="view-btn" class="hideMobile" ?hidden="${this.selectedDashboard == null || this._isReadonly() || !this._hasEditAccess()}" type="${InputType.BUTTON}" outlined icon="pencil" label="${i18next.t('editAsset')}"
+ @or-mwc-input-changed="${() => { this.dispatchEvent(new CustomEvent('editToggle', { detail: true })); }}">
+ </or-mwc-input>
+ `)}
</div>
</div>
</div>
@@ -603,14 +637,15 @@ export class OrDashboardBuilder extends LitElement {
<div id="builder" style="${styleMap(builderStyles)}">
${(this.selectedDashboard != null) ? html`
<or-dashboard-preview class="editor" style="background: transparent;"
- .realm="${this.realm}" .template="${this.currentTemplate}" .rerenderPending="${this.rerenderPending}"
+ .realm="${this.realm}" .template="${this.currentTemplate}"
.selectedWidget="${this.selectedDashboard?.template?.widgets?.find(w => w.id == this.selectedWidgetId)}" .editMode="${this.editMode}"
.fullscreen="${this.fullscreen}" .readonly="${this._isReadonly()}"
@selected="${(event: CustomEvent) => { this.selectWidget(event.detail); }}"
@deselected="${() => { this.deselectWidget(); }}"
- @dropped="${(event: CustomEvent) => { this.createWidget(event.detail as ORGridStackNode)}}"
- @changed="${(event: CustomEvent) => { this.currentTemplate = event.detail.template; }}"
- @rerenderfinished="${(event: CustomEvent) => { this.rerenderPending = false; }}"
+ @created="${(event: CustomEvent) => { this.onWidgetCreation(event.detail); }}"
+ @changed="${(event: CustomEvent) => {
+ this.currentTemplate = event.detail.template;
+ }}"
></or-dashboard-preview>
` : html`
<div style="display: flex; justify-content: center; align-items: center; height: 100%;">
@@ -643,7 +678,7 @@ export class OrDashboardBuilder extends LitElement {
@delete="${(event: CustomEvent) => { this.deleteWidget(event.detail); }}"
@update="${(event: CustomEvent) => {
this.currentTemplate = Object.assign({}, this.selectedDashboard?.template);
- if(event.detail.force) { this.rerenderPending = true; }}}"
+ if(event.detail.force) { this.deselectWidget(); this.dashboardPreview?.refreshPreview(); }}}"
></or-dashboard-widgetsettings>
</div>
</div>
@@ -660,7 +695,7 @@ export class OrDashboardBuilder extends LitElement {
.dashboard="${this.selectedDashboard}" .showPerms="${this.selectedDashboard?.ownerId == this.userId}"
@update="${(event: CustomEvent) => {
this.currentTemplate = Object.assign({}, this.selectedDashboard?.template);
- if(event.detail.force) { this.rerenderPending = true; }}}"
+ if(event.detail.force) { this.deselectWidget(); this.dashboardPreview?.refreshPreview(); }}}"
></or-dashboard-boardsettings>
</div>
</div>
@@ -683,26 +718,10 @@ export class OrDashboardBuilder extends LitElement {
`
}
- /* ======================== */
+ protected onIntervalSelect(ev: IntervalSelectEvent) {
+ this.refreshInterval = ev.detail;
+ }
-}
+ /* ======================== */
-// Generating the Grid Item details like X and Y coordinates for GridStack to work.
-export function generateGridItem(gridstackNode: ORGridStackNode, _displayName: string): DashboardGridItem {
- const randomId = (Math.random() + 1).toString(36).substring(2);
- const widgetType = widgetTypes.get(gridstackNode.widgetTypeId)!;
- return {
- id: randomId,
- x: gridstackNode.x,
- y: gridstackNode.y,
- w: 2,
- h: 2,
- minW: widgetType.MIN_COLUMN_WIDTH,
- minH: widgetType.MIN_COLUMN_WIDTH,
- minPixelW: widgetType.MIN_PIXEL_WIDTH,
- minPixelH: widgetType.MIN_PIXEL_HEIGHT,
- noResize: false,
- noMove: false,
- locked: false,
- }
}
diff --git a/ui/component/or-dashboard-builder/src/or-dashboard-boardsettings.ts b/ui/component/or-dashboard-builder/src/or-dashboard-boardsettings.ts
index 0e406db7a..3e62a6ab8 100644
--- a/ui/component/or-dashboard-builder/src/or-dashboard-boardsettings.ts
+++ b/ui/component/or-dashboard-builder/src/or-dashboard-boardsettings.ts
@@ -1,15 +1,12 @@
-import {Dashboard, DashboardAccess, DashboardScreenPreset, DashboardScalingPreset } from "@openremote/model";
-import {css, html, LitElement, TemplateResult } from "lit";
-import { customElement, property, state } from "lit/decorators.js";
-import { InputType, OrInputChangedEvent } from "@openremote/or-mwc-components/or-mwc-input";
+import {Dashboard, DashboardAccess, DashboardRefreshInterval, DashboardScalingPreset, DashboardScreenPreset} from "@openremote/model";
+import {css, html, LitElement} from "lit";
+import {customElement, property} from "lit/decorators.js";
+import {InputType, OrInputChangedEvent} from "@openremote/or-mwc-components/or-mwc-input";
import {style} from './style';
-import { i18next } from "@openremote/or-translate";
+import {i18next} from "@openremote/or-translate";
import {unsafeHTML} from 'lit/directives/unsafe-html.js';
-import {
- dashboardAccessToString,
- scalingPresetToString,
- sortScreenPresets
-} from ".";
+import {when} from "lit/directives/when.js";
+import {dashboardAccessToString, scalingPresetToString, sortScreenPresets} from ".";
//language=css
const boardSettingsStyling = css`
@@ -27,22 +24,6 @@ export class OrDashboardBoardsettings extends LitElement {
@property()
protected readonly showPerms?: boolean;
- @state()
- protected expandedPanels: string[] = [i18next.t('permissions'), i18next.t('layout'), i18next.t('display'), "Breakpoints"];
-
- constructor() {
- super();
- this.updateComplete.then(() => {
- if(this.shadowRoot != null) {
- this.shadowRoot.querySelectorAll(".displayInput").forEach(element => {
- (element.shadowRoot?.querySelector(".mdc-menu") as HTMLElement).style.minWidth = "250px"; // small fix for dropdown menu's to be the correct width
- })
- this.shadowRoot.querySelectorAll(".permissionInput").forEach(element => {
- (element.shadowRoot?.querySelector(".mdc-menu") as HTMLElement).style.minWidth = "250px"; // small fix for dropdown menu's to be the correct width
- })
- }
- })
- }
/* ------------------------- */
static get styles() {
@@ -50,146 +31,154 @@ export class OrDashboardBoardsettings extends LitElement {
}
forceParentUpdate(force: boolean = false) {
- this.dispatchEvent(new CustomEvent('update', { detail: { force: force }}));
- }
-
- /* ------------------------- */
-
- // Method when a user opens or closes an expansion panel. (UI related)
- 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();
+ this.dispatchEvent(new CustomEvent('update', {detail: {force: force}}));
}
/* -------------------------------- */
private setViewAccess(access: DashboardAccess) {
this.dashboard.viewAccess = access;
- if(access == DashboardAccess.PRIVATE) {
+ if (access === DashboardAccess.PRIVATE) {
this.dashboard.editAccess = DashboardAccess.PRIVATE; // if viewAccess changed to PRIVATE, make editAccess private as well.
}
this.requestUpdate();
this.forceParentUpdate(false);
}
+
private setEditAccess(access: DashboardAccess) {
this.dashboard.editAccess = access;
this.requestUpdate();
this.forceParentUpdate(false);
}
+
private setBreakpoint(presetIndex: number, value: number) {
this.dashboard.template!.screenPresets![presetIndex].breakpoint = value;
this.requestUpdate();
this.forceParentUpdate(true);
}
+ private setRefreshInterval(interval: DashboardRefreshInterval) {
+ this.dashboard.template!.refreshInterval = interval;
+ this.requestUpdate();
+ this.forceParentUpdate(false);
+ }
+
protected render() {
- if(this.dashboard.template?.screenPresets != null) {
+ if (this.dashboard.template?.screenPresets != null) {
const screenPresets = sortScreenPresets(this.dashboard.template.screenPresets, true);
- const viewAccessOptions = [DashboardAccess.PRIVATE, DashboardAccess.SHARED, DashboardAccess.PUBLIC].map((access) => ({ key: access, value: dashboardAccessToString(access) }));
- const editAccessOptions = [DashboardAccess.PRIVATE, DashboardAccess.SHARED].map((access) => ({ key: access, value: dashboardAccessToString(access) }));
- const scalingPresets: {key: DashboardScalingPreset, value: string}[] = [];
+ const viewAccessOptions = [DashboardAccess.PRIVATE, DashboardAccess.SHARED, DashboardAccess.PUBLIC].map((access) => ({key: access, value: dashboardAccessToString(access)}));
+ const editAccessOptions = [DashboardAccess.PRIVATE, DashboardAccess.SHARED].map((access) => ({key: access, value: dashboardAccessToString(access)}));
+ const refreshIntervalOptions = [DashboardRefreshInterval.OFF, DashboardRefreshInterval.ONE_MIN, DashboardRefreshInterval.FIVE_MIN, DashboardRefreshInterval.QUARTER, DashboardRefreshInterval.ONE_HOUR].map(interval => ({key: interval, value: `dashboard.interval.${interval.toLowerCase()}`}))
+ const scalingPresets: { key: DashboardScalingPreset, value: string }[] = [];
[DashboardScalingPreset.KEEP_LAYOUT, DashboardScalingPreset.WRAP_TO_SINGLE_COLUMN, /*DashboardScalingPreset.REDIRECT,*/ DashboardScalingPreset.BLOCK_DEVICE].forEach((preset: DashboardScalingPreset) => {
- scalingPresets.push({key: preset, value: scalingPresetToString(preset) });
+ scalingPresets.push({key: preset, value: scalingPresetToString(preset)});
});
return html`
- <!-------------------->
- <div>${this.showPerms ? this.generateExpandableHeader(i18next.t('permissions')) : undefined}</div>
- <div>
- ${this.showPerms && this.expandedPanels.includes(i18next.t('permissions')) ? html`
- <div style="padding: 12px 24px 24px 24px;">
+
+ <!-- Permissions panel, to set who can view/edit the selected dashboard -->
+ ${when(this.showPerms, () => html`
+ <settings-panel displayName="${i18next.t('permissions')}" expanded="${true}">
+ <div>
<div style="margin-bottom: 24px;">
<div class="label">
${html`<span>${unsafeHTML(i18next.t('dashboard.whoCanView').toString())}</span>`}
</div>
- <or-mwc-input class="permissionInput" comfortable type="${InputType.SELECT}" style="width: 250px;"
+ <or-mwc-input class="permissionInput" comfortable type="${InputType.SELECT}" style="width: 100%;"
.options="${viewAccessOptions.map((access) => access.value)}"
.value="${dashboardAccessToString(this.dashboard.viewAccess!)}"
- @or-mwc-input-changed="${(event: OrInputChangedEvent) => { this.setViewAccess(viewAccessOptions.find((access) => access.value == event.detail.value)?.key!); }}"
+ @or-mwc-input-changed="${(event: OrInputChangedEvent) => {
+ this.setViewAccess(viewAccessOptions.find((access) => access.value == event.detail.value)?.key!);
+ }}"
></or-mwc-input>
</div>
<div style="margin-bottom: 24px;">
<div class="label">
${html`<span>${unsafeHTML(i18next.t('dashboard.whoCanEdit').toString())}</span>`}
</div>
- <or-mwc-input class="permissionInput" comfortable type="${InputType.SELECT}" style="width: 250px;"
- .disabled="${(this.dashboard.viewAccess == DashboardAccess.PRIVATE)}"
- .options="${editAccessOptions.map((access) => access.value)}"
- .value="${dashboardAccessToString(this.dashboard.editAccess!)}"
- @or-mwc-input-changed="${(event: OrInputChangedEvent) => { this.setEditAccess(editAccessOptions.find((access) => access.value == event.detail.value)?.key!); }}"
+ <or-mwc-input class="permissionInput" comfortable type="${InputType.SELECT}" style="width: 100%;"
+ .disabled="${(this.dashboard.viewAccess == DashboardAccess.PRIVATE)}"
+ .options="${editAccessOptions.map((access) => access.value)}"
+ .value="${dashboardAccessToString(this.dashboard.editAccess!)}"
+ @or-mwc-input-changed="${(event: OrInputChangedEvent) => {
+ this.setEditAccess(editAccessOptions.find((access) => access.value == event.detail.value)?.key!);
+ }}"
></or-mwc-input>
</div>
</div>
- ` : null}
- </div>
- <!-------------------->
- <div>${this.generateExpandableHeader(i18next.t('layout'))}</div>
- <div>
- ${this.expandedPanels.includes(i18next.t('layout')) ? html`
- <div style="padding: 12px 24px 24px 24px;">
- <!-- Number of Columns control -->
- <div style="margin-bottom: 24px; display: flex; align-items: center;">
- <span style="min-width: 180px;">${i18next.t("dashboard.numberOfColumns")}</span>
- <or-mwc-input type="${InputType.NUMBER}" comfortable .value="${this.dashboard.template.columns}" min="1" max="24" @or-mwc-input-changed="${(event: OrInputChangedEvent) => {
- if(this.dashboard.template != null && event.detail.value as number <= 24 && event.detail.value as number >= 1) {
- this.dashboard.template.columns = event.detail.value as number; this.forceParentUpdate(true);
- }
- }}"></or-mwc-input>
- </div>
- ${screenPresets.length == 1 ? html`
- ${this.scalingPresetTemplate(screenPresets, scalingPresets)}
- ` : undefined}
- ${screenPresets.length == 1 ? html`
- ${this.screenPresetTemplate(screenPresets, ['Mobile breakpoint'])}
- ` : undefined}
- <!-- Max Screen Width control-->
- <div style="margin-bottom: 24px; display: flex; align-items: center; justify-content: space-between;">
- <span style="min-width: 150px;">${i18next.t('dashboard.maxScreenWidth')}</span>
- <div>
- <or-mwc-input type="${InputType.NUMBER}" comfortable .value="${this.dashboard.template.maxScreenWidth}" style="width: 70px;"
- @or-mwc-input-changed="${(event: OrInputChangedEvent) => { if(this.dashboard.template != null) {
- this.dashboard.template.maxScreenWidth = event.detail.value as number; this.forceParentUpdate(true);
- }}}">
- </or-mwc-input>
- <span style="margin-left: 2px;">px</span>
- </div>
- </div>
+ </settings-panel>
+ `)}
+
+ <!-- Layout panel, with options such as 'amount of columns' -->
+ <settings-panel displayName="${i18next.t('layout')}" expanded="${true}">
+ <div>
+
+ <!-- Number of Columns control -->
+ <div style="margin-bottom: 24px; display: flex; align-items: center;">
+ <span style="min-width: 180px;">${i18next.t("dashboard.numberOfColumns")}</span>
+ <or-mwc-input type="${InputType.NUMBER}" comfortable .value="${this.dashboard.template.columns}" min="1" max="24" @or-mwc-input-changed="${(event: OrInputChangedEvent) => {
+ if (this.dashboard.template != null && event.detail.value as number <= 24 && event.detail.value as number >= 1) {
+ this.dashboard.template.columns = event.detail.value as number;
+ this.forceParentUpdate(true);
+ }
+ }}"></or-mwc-input>
+ </div>
+
+ <!-- Scaling preset -->
+ ${screenPresets.length === 1 ? html`
+ ${this.scalingPresetTemplate(screenPresets, scalingPresets)}
+ ` : undefined}
+
+ <!-- Screen preset -->
+ ${screenPresets.length === 1 ? html`
+ ${this.screenPresetTemplate(screenPresets, ['Mobile breakpoint'])}
+ ` : undefined}
+
+ <!-- Max Screen Width control-->
+ <div style="margin-bottom: 24px; display: flex; align-items: center; justify-content: space-between;">
+ <span style="min-width: 150px;">${i18next.t('dashboard.maxScreenWidth')}</span>
<div>
- <or-mwc-input type="${InputType.BUTTON}" comfortable label="${i18next.t('dashboard.setToMobilePreset')}"
- @or-mwc-input-changed="${() => { this.setToMobilePreset(); }}">
+ <or-mwc-input type="${InputType.NUMBER}" comfortable .value="${this.dashboard.template.maxScreenWidth}" style="width: 70px;"
+ @or-mwc-input-changed="${(event: OrInputChangedEvent) => {
+ if (this.dashboard.template != null) {
+ this.dashboard.template.maxScreenWidth = event.detail.value as number;
+ this.forceParentUpdate(true);
+ }
+ }}">
</or-mwc-input>
+ <span style="margin-left: 2px;">px</span>
</div>
</div>
- ` : null}
- </div>
- <!-------------------->
- ${screenPresets.length > 1 ? html`
- <div>${this.generateExpandableHeader(i18next.t('display'))}</div>
- <div>
- ${this.expandedPanels.includes(i18next.t('display')) ? html`
- <div style="padding: 24px 24px 24px 24px;">
- ${this.scalingPresetTemplate(screenPresets, scalingPresets)}
- </div>
- ` : null}
+
+ <!-- "Set to mobile" preset button, for ease of use -->
+ <div>
+ <or-mwc-input type="${InputType.BUTTON}" comfortable label="${i18next.t('dashboard.setToMobilePreset')}"
+ @or-mwc-input-changed="${() => {
+ this.setToMobilePreset();
+ }}">
+ </or-mwc-input>
+ </div>
</div>
- ` : undefined}
- <!-------------------->
- ${screenPresets.length > 1 ? html`
- <div>${this.generateExpandableHeader('Breakpoints')}</div>
+ </settings-panel>
+
+ <!-- Data management options -->
+ <settings-panel displayName="${i18next.t('dashboard.dataManagement')}" expanded="${true}">
<div>
- ${this.expandedPanels.includes('Breakpoints') ? html`
- <div style="padding: 24px 24px 24px 24px;">
- ${this.screenPresetTemplate(screenPresets)}
- </div>
- ` : null}
+ <div class="label">
+ <span>${i18next.t('dashboard.defaultRefreshInterval')}</span>
+ </div>
+ <or-mwc-input type="${InputType.SELECT}" comfortable .options="${refreshIntervalOptions.map(o => o.value)}" style="width: 100%;"
+ .value="${`dashboard.interval.${this.dashboard.template.refreshInterval?.toLowerCase() || `off`}`}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => {
+ const intervalEntry = refreshIntervalOptions.find(o => o.value === ev.detail.value);
+ if(intervalEntry) {
+ this.setRefreshInterval(intervalEntry.key)
+ }
+ }}">
+ </or-mwc-input>
</div>
- ` : undefined}
- <!-------------------->
- `
+ </settings-panel>
+
+ `;
} else {
return html`
<div style="padding: 24px;">
@@ -213,16 +202,7 @@ export class OrDashboardBoardsettings extends LitElement {
/* ======================== */
- // UI generation of an expandable panel header.
- generateExpandableHeader(name: string): TemplateResult {
- return html`
- <span class="expandableHeader" @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>
- `
- }
- scalingPresetTemplate(screenPresets: DashboardScreenPreset[], scalingPresets: {key: DashboardScalingPreset, value: string}[]) {
+ scalingPresetTemplate(screenPresets: DashboardScreenPreset[], scalingPresets: { key: DashboardScalingPreset, value: string }[]) {
return html`
${screenPresets.map((preset) => {
return html`
@@ -244,6 +224,7 @@ export class OrDashboardBoardsettings extends LitElement {
})}
`
}
+
screenPresetTemplate(screenPresets: DashboardScreenPreset[], customLabels?: string[]) {
return html`
${screenPresets.map((preset, index) => {
@@ -252,9 +233,11 @@ export class OrDashboardBoardsettings extends LitElement {
<span style="min-width: 140px;">${customLabels ? customLabels[index] : (preset.displayName + " " + i18next.t('screen'))}</span>
<div>
<span style="margin-right: 4px;">${(screenPresets.indexOf(preset) == 0) ? '>' : '<'}</span>
- <or-mwc-input type="${InputType.NUMBER}" comfortable .disabled="${(screenPresets.length > 1 && screenPresets.indexOf(preset) == 0)}" style="width: 70px;"
- .value="${(screenPresets.length > 1 && screenPresets.indexOf(preset) == 0 ? screenPresets[1].breakpoint : preset.breakpoint)}"
- @or-mwc-input-changed="${(event: OrInputChangedEvent) => { this.setBreakpoint(screenPresets.indexOf(preset), event.detail.value)}}"
+ <or-mwc-input type="${InputType.NUMBER}" comfortable .disabled="${(screenPresets.length > 1 && screenPresets.indexOf(preset) == 0)}" style="width: 70px;"
+ .value="${(screenPresets.length > 1 && screenPresets.indexOf(preset) == 0 ? screenPresets[1].breakpoint : preset.breakpoint)}"
+ @or-mwc-input-changed="${(event: OrInputChangedEvent) => {
+ this.setBreakpoint(screenPresets.indexOf(preset), event.detail.value)
+ }}"
></or-mwc-input>
<span style="margin-left: 2px;">px</span>
</div>
@@ -263,8 +246,4 @@ export class OrDashboardBoardsettings extends LitElement {
})}
`
}
-
-
- /* ------------------------- */
-
}
diff --git a/ui/component/or-dashboard-builder/src/or-dashboard-browser.ts b/ui/component/or-dashboard-builder/src/or-dashboard-browser.ts
index cfd64570a..d507b7c7c 100644
--- a/ui/component/or-dashboard-builder/src/or-dashboard-browser.ts
+++ b/ui/component/or-dashboard-builder/src/or-dashboard-browser.ts
@@ -67,7 +67,7 @@ export class OrDashboardBrowser extends LitElement {
const sidebarElement = this.shadowRoot?.getElementById("sidebarElement");
const coords: Array<[number, number]> = new Array<[number, number]>([0,0],[2,0], [0,2], [2,2], [0,4], [2,4], [0,6], [2,6], [0,8], [2,8]) // TODO: make this unlimited possibilities with a formula
const sidebarItems: any[] = Array.from(widgetTypes).map((typeArr, index) => {
- return {x: coords[index][0], y: coords[index][1], w: 2, h: 2, widgetTypeId: typeArr[0], locked: true, content: `<div class="sidebarItem"><or-icon icon="${typeArr[1].DISPLAY_MDI_ICON}"></or-icon><span class="itemText">${typeArr[1].DISPLAY_NAME}</span>`}
+ return {x: coords[index][0], y: coords[index][1], w: 2, h: 2, widgetTypeId: typeArr[0], locked: true, content: `<div class="sidebarItem"><or-icon icon="${typeArr[1].displayIcon}"></or-icon><span class="itemText">${typeArr[1].displayName}</span>`}
});
// Setting Sidebar height depending on sidebarItems
@@ -104,7 +104,9 @@ export class OrDashboardBrowser extends LitElement {
// @ts-ignore typechecking, because we can only provide an HTMLElement (which GridHTMLElement inherits)
}, sidebarElement);
+
this.sidebarGrid.load(sidebarItems);
+
// If an item gets dropped on the main grid, the dragged item needs to be reset to the sidebar.
// This is done by just loading the initial/original widget back in the sidebar.
// @ts-ignore typechecking since we assume they are not undefined
diff --git a/ui/component/or-dashboard-builder/src/or-dashboard-preview.ts b/ui/component/or-dashboard-builder/src/or-dashboard-preview.ts
index e1a172165..529fab5d6 100644
--- a/ui/component/or-dashboard-builder/src/or-dashboard-preview.ts
+++ b/ui/component/or-dashboard-builder/src/or-dashboard-preview.ts
@@ -2,7 +2,7 @@ import manager, {DefaultColor4, DefaultColor5} from "@openremote/core";
import {css, html, LitElement, TemplateResult, unsafeCSS} from "lit";
import {customElement, property, state} from "lit/decorators.js";
import {style} from "./style";
-import "./or-dashboard-widget";
+import "./or-dashboard-widgetcontainer";
import {debounce} from "lodash";
import {DashboardGridItem, DashboardScalingPreset, DashboardScreenPreset, DashboardTemplate, DashboardWidget} from "@openremote/model";
import {getActivePreset} from "./index";
@@ -14,7 +14,10 @@ import {showSnackbar} from "@openremote/or-mwc-components/or-mwc-snackbar";
import {i18next} from "@openremote/or-translate";
import {when} from "lit/directives/when.js";
import {cache} from "lit/directives/cache.js";
+import {guard} from "lit/directives/guard.js";
import {OrDashboardEngine} from "./or-dashboard-engine";
+import {WidgetService} from "./service/widget-service";
+import {OrDashboardWidgetContainer} from "./or-dashboard-widgetcontainer";
// TODO: Add webpack/rollup to build so consumers aren't forced to use the same tooling
const gridcss = require('gridstack/dist/gridstack.min.css');
@@ -105,7 +108,7 @@ const editorStyling = css`
/* -------------------------------------------------- */
-export interface ORGridStackNode extends GridStackNode {
+export interface DashboardGridNode extends GridStackNode {
widgetTypeId: string;
}
export interface DashboardPreviewSize {
@@ -182,14 +185,8 @@ export class OrDashboardPreview extends LitElement {
@property()
protected fullscreen: boolean = true;
- @property() // Property that, when toggled on, shows a "loading" state for 200ms, and then renders the component again.
- protected rerenderPending: boolean = false;
-
/* -------------- */
- @state()
- protected grid?: GridStack;
-
@state() // State where the changes of the template are saved temporarily (for comparison with incoming data)
protected latestChanges?: {
changedKeys: string[],
@@ -197,9 +194,6 @@ export class OrDashboardPreview extends LitElement {
newValue: DashboardTemplate
}
- @state() // Records time a user is dragging
- protected latestDragWidgetStart?: Date;
-
@state()
protected activePreset?: DashboardScreenPreset;
@@ -210,6 +204,10 @@ export class OrDashboardPreview extends LitElement {
private isLoading: boolean = false;
+ protected grid?: GridStack;
+ protected latestDragWidgetStart?: Date;
+
+
/* ------------------------------------------- */
// Using constructor to set initial values
@@ -241,6 +239,7 @@ export class OrDashboardPreview extends LitElement {
// Checking whether actual changes have been made; if not, prevent updating.
shouldUpdate(changedProperties: Map<PropertyKey, unknown>): boolean {
const changed = changedProperties;
+
if(changedProperties.has('latestChanges')
&& this.latestChanges?.changedKeys.length == 0
&& (JSON.stringify((changedProperties.get('latestChanges') as any)?.oldValue)) == (JSON.stringify((changedProperties.get('latestChanges') as any)?.newValue))) {
@@ -256,25 +255,14 @@ export class OrDashboardPreview extends LitElement {
changed.delete('previewHeight');
}
- if(changedProperties.has("rerenderPending")) {
- if(this.rerenderPending) {
- this.setupGrid(true, true).then(() => {
- this.rerenderPending = false;
- this.dispatchEvent(new CustomEvent("rerenderfinished"));
- });
- return false;
- }
- }
-
- // Delete ones that not actually change anything
- changed.delete('latestDragWidgetStart');
-
- return (changed.size == 0 ? false : super.shouldUpdate(changedProperties));
+ return (changed.size === 0 ? false : super.shouldUpdate(changedProperties));
}
// Main method for executing actions after property changes
updated(changedProperties: Map<string, any>) {
+ super.updated(changedProperties);
+
if(this.realm == undefined) { this.realm = manager.displayRealm; }
// Setup template (list of widgets and properties)
@@ -356,7 +344,7 @@ export class OrDashboardPreview extends LitElement {
if(recreate && this.grid != null) {
this.grid.destroy(false);
- if(force) { // Fully rerender the grid by switching rerenderPending on and off, and continue after that.
+ if(force) { // Fully rerender the grid by switching rerenderActive on and off, and continue after that.
this.rerenderActive = true;
await this.updateComplete;
await this.waitUntil((_: any) => !this.rerenderActive);
@@ -367,7 +355,7 @@ export class OrDashboardPreview extends LitElement {
const width: number = (this.fullscreen ? this.clientWidth : (+(this.previewWidth?.replace(/\D/g, "")!)));
const newPreset = getActivePreset(width, this.template.screenPresets!);
if(newPreset?.scalingPreset != this.activePreset?.scalingPreset) {
- if(!(recreate && force)) { // Fully rerender the grid by switching rerenderPending on and off, and continue after that.
+ if(!(recreate && force)) { // Fully rerender the grid by switching rerenderActive on and off, and continue after that.
if(!recreate) { // If not destroyed yet, destroy first.
this.grid?.destroy(false);
}
@@ -392,9 +380,9 @@ export class OrDashboardPreview extends LitElement {
this.grid = GridStack.init({
acceptWidgets: (this.editMode),
animate: true,
- cellHeight: (this.activePreset?.scalingPreset == DashboardScalingPreset.WRAP_TO_SINGLE_COLUMN ? (width / (this.template?.columns ? (this.template.columns / 4) : 2)) : 'initial'),
+ cellHeight: (this.activePreset?.scalingPreset === DashboardScalingPreset.WRAP_TO_SINGLE_COLUMN ? (width / (this.template?.columns ? (this.template.columns / 4) : 2)) : 'initial'),
column: this.template?.columns,
- disableOneColumnMode: (this.activePreset?.scalingPreset != DashboardScalingPreset.WRAP_TO_SINGLE_COLUMN),
+ disableOneColumnMode: (this.activePreset?.scalingPreset !== DashboardScalingPreset.WRAP_TO_SINGLE_COLUMN),
oneColumnModeDomSort: true,
draggable: {
appendTo: 'parent', // Required to work, seems to be Shadow DOM related.
@@ -404,7 +392,7 @@ export class OrDashboardPreview extends LitElement {
resizable: {
handles: 'all'
},
- staticGrid: (this.activePreset?.scalingPreset == DashboardScalingPreset.WRAP_TO_SINGLE_COLUMN ? true : (!this.editMode)),
+ staticGrid: (this.activePreset?.scalingPreset === DashboardScalingPreset.WRAP_TO_SINGLE_COLUMN ? true : (!this.editMode)),
styleInHead: false
}, gridElement!);
@@ -412,12 +400,9 @@ export class OrDashboardPreview extends LitElement {
gridElement!.style.height = "100%";
gridElement!.style.minHeight = "100%";
- this.grid.on('dropped', (_event: Event, _previousWidget: any, newWidget: GridStackNode | undefined) => {
- if(this.grid != null && newWidget != null) {
- this.grid.removeWidget((newWidget.el) as GridStackElement, true, false); // Removes dragged widget first
- this.dispatchEvent(new CustomEvent("dropped", { detail: newWidget }));
- }
- });
+ // When an item gets dropped ontop of the grid. GridStack docs say:
+ // "called when an item has been dropped and accepted over a grid. If the item came from another grid, the previous widget node info will also be sent (but dom item long gone)."
+ this.grid.on('dropped', (ev: Event, prevWidget: any, newWidget: GridStackNode | undefined) => this.onWidgetDrop(ev, prevWidget, newWidget as DashboardGridNode));
this.grid.on('change', (_event: Event, items: any) => {
if(this.template != null && this.template.widgets != null) {
(items as GridStackNode[]).forEach(node => {
@@ -443,7 +428,20 @@ export class OrDashboardPreview extends LitElement {
/* ------------------------------- */
- selectGridItem(gridItem: GridItemHTMLElement) {
+ public refreshPreview() {
+ this.setupGrid(true, true);
+ }
+
+ public refreshWidgets() {
+ this.grid?.getGridItems().forEach(gridItem => {
+ const widgetContainer = gridItem.querySelector(OrDashboardWidgetContainer.tagName) as OrDashboardWidgetContainer | null;
+ if(widgetContainer) {
+ widgetContainer.refreshContent(false);
+ }
+ })
+ }
+
+ protected selectGridItem(gridItem: GridItemHTMLElement) {
if(this.grid != null) {
this.deselectGridItems(this.grid.getGridItems()); // deselecting all other items
gridItem.querySelectorAll<HTMLElement>(".grid-stack-item-content").forEach((item: HTMLElement) => {
@@ -451,19 +449,20 @@ export class OrDashboardPreview extends LitElement {
});
}
}
- deselectGridItem(gridItem: GridItemHTMLElement) {
+
+ protected deselectGridItem(gridItem: GridItemHTMLElement) {
gridItem.querySelectorAll<HTMLElement>(".grid-stack-item-content").forEach((item: HTMLElement) => {
item.classList.remove('grid-stack-item-content__active'); // Remove active CSS class
});
}
- deselectGridItems(gridItems: GridItemHTMLElement[]) {
+ protected deselectGridItems(gridItems: GridItemHTMLElement[]) {
gridItems.forEach(item => {
this.deselectGridItem(item);
})
}
- onGridItemClick(gridItem: DashboardGridItem | undefined) {
+ protected onGridItemClick(gridItem: DashboardGridItem | undefined) {
if(!this.latestDragWidgetStart && !this.grid?.opts.staticGrid) {
if(!gridItem) {
this.selectedWidget = undefined;
@@ -473,7 +472,7 @@ export class OrDashboardPreview extends LitElement {
}
}
- onFitToScreenClick() {
+ protected onFitToScreenClick() {
const container = this.shadowRoot?.querySelector('#container');
if(container) {
const zoomWidth = +((0.95 * container.clientWidth) / +this.previewWidth!.replace('px', '')).toFixed(2);
@@ -481,7 +480,7 @@ export class OrDashboardPreview extends LitElement {
}
}
- isPreviewVisible(): boolean {
+ protected isPreviewVisible(): boolean {
return !this.isLoading && this.activePreset?.scalingPreset != DashboardScalingPreset.BLOCK_DEVICE;
}
@@ -543,23 +542,33 @@ export class OrDashboardPreview extends LitElement {
</div>
` : undefined}
`)}
+ <!-- The grid itself. Will also show during isLoading, but will be invisible through CSS -->
<div class="${this.fullscreen ? 'maingridContainer__fullscreen' : 'maingridContainer'}" style="${this.isLoading ? 'visibility: hidden;' : ''}">
- <div class="maingrid ${this.fullscreen ? 'maingrid__fullscreen' : undefined }"
- @click="${(ev: MouseEvent) => { if((ev.composedPath()[0] as HTMLElement).id == 'gridElement') { this.onGridItemClick(undefined) }}}"
+ <div class="maingrid ${this.fullscreen ? 'maingrid__fullscreen' : undefined}"
style="width: ${this.previewWidth}; height: ${this.previewHeight}; visibility: ${this.isPreviewVisible() ? 'visible' : 'hidden'}; zoom: ${this.editMode && !this.fullscreen ? this.previewZoom : 'normal'}; ${this.editMode && !this.fullscreen ? ('-moz-transform: scale(' + this.previewZoom + ')') : undefined}; transform-origin: top;"
- >
- <!-- Gridstack element on which the Grid will be rendered -->
- <div id="gridElement" class="grid-stack ${this.editMode ? 'grid-element' : undefined}" style="margin: auto;">
- ${this.template?.widgets ? repeat(this.template.widgets, (item) => item.id, (widget) => {
- return html`
- <div class="grid-stack-item" id="${widget.id}" gs-id="${widget.gridItem?.id}" gs-x="${widget.gridItem?.x}" gs-y="${widget.gridItem?.y}" gs-w="${widget.gridItem?.w}" gs-h="${widget.gridItem?.h}" @click="${() => { this.onGridItemClick(widget.gridItem); }}">
- <div class="grid-stack-item-content" style="display: flex;">
- <or-dashboard-widget .widget="${widget}" .editMode="${this.editMode}" .realm="${this.realm}" style="width: 100%; height: auto; border-radius: 4px;"></or-dashboard-widget>
- </div>
- </div>
- `
- }) : undefined}
- </div>
+ @click="${(ev: MouseEvent) => {
+ if ((ev.composedPath()[0] as HTMLElement).id == 'gridElement') {
+ this.onGridItemClick(undefined)
+ }
+ }}">
+ ${guard([this.editMode, this.template], () => html`
+ <!-- Gridstack element on which the Grid will be rendered -->
+ <div id="gridElement" class="grid-stack ${this.editMode ? 'grid-element' : undefined}" style="margin: auto;">
+ ${this.template?.widgets ? repeat(this.template.widgets, (item) => item.id, (widget) => {
+ return html`
+ <div class="grid-stack-item" id="${widget.id}" gs-id="${widget.gridItem?.id}" gs-x="${widget.gridItem?.x}" gs-y="${widget.gridItem?.y}"
+ gs-w="${widget.gridItem?.w}" gs-h="${widget.gridItem?.h}" gs-min-w="${widget.gridItem?.minW}" gs-min-h="${widget.gridItem?.minH}"
+ @click="${() => {
+ this.onGridItemClick(widget.gridItem);
+ }}">
+ <div class="grid-stack-item-content" style="display: flex;">
+ <or-dashboard-widget-container .widget="${widget}" style="width: 100%; height: auto; border-radius: 4px;"></or-dashboard-widget-container>
+ </div>
+ </div>
+ `
+ }) : undefined}
+ </div>
+ `)}
</div>
</div>
</div>
@@ -573,12 +582,12 @@ export class OrDashboardPreview extends LitElement {
`
}
- getGridstackColumns(grid: GridStack | undefined): number | undefined {
+ protected getGridstackColumns(grid: GridStack | undefined): number | undefined {
try { return grid?.getColumn(); }
catch (e) { return undefined; }
}
- isExtraLargeGrid(): boolean {
+ protected isExtraLargeGrid(): boolean {
return !!this.grid && (
(this.getGridstackColumns(this.grid) && this.getGridstackColumns(this.grid)! > 12)
|| !!(this.template?.columns && this.template.columns > 12)
@@ -591,7 +600,7 @@ export class OrDashboardPreview extends LitElement {
// Provides support for > 12 columns in GridStack (which requires manual css edits)
//language=html
- applyCustomGridstackGridCSS(columns: number): TemplateResult {
+ protected applyCustomGridstackGridCSS(columns: number): TemplateResult {
if(this.cachedGridstackCSS.has(columns)) {
return html`${this.cachedGridstackCSS.get(columns)!.map((x) => x)}`;
} else {
@@ -613,10 +622,7 @@ export class OrDashboardPreview extends LitElement {
/* ---------------------------------------------- */
-
- @state()
protected resizeObserver?: ResizeObserver;
-
protected previousObserverEntry?: ResizeObserverEntry;
disconnectedCallback() {
@@ -626,7 +632,7 @@ export class OrDashboardPreview extends LitElement {
// Triggering a Grid rerender on every time the element resizes.
// In fullscreen, debounce (only trigger after 550ms of no changes) to limit amount of rerenders.
- setupResizeObserver(element: Element): ResizeObserver {
+ protected setupResizeObserver(element: Element): ResizeObserver {
this.resizeObserver?.disconnect();
if(this.fullscreen) {
this.resizeObserver = new ResizeObserver(debounce(this.resizeObserverCallback, 200));
@@ -644,13 +650,13 @@ export class OrDashboardPreview extends LitElement {
this.previousObserverEntry = entries[0];
}
- _onGridResize() {
+ protected _onGridResize() {
this.setupGrid(true, false);
}
/* --------------------------------------- */
- processTemplateChanges(changes: { changedKeys: string[], oldValue: DashboardTemplate, newValue: DashboardTemplate }) {
+ protected processTemplateChanges(changes: { changedKeys: string[], oldValue: DashboardTemplate, newValue: DashboardTemplate }) {
// If only columns property changed, change columns through the framework and then recreate grid.
if(changes.changedKeys.length == 1 && changes.changedKeys.includes('columns') && this.grid) {
@@ -683,11 +689,25 @@ export class OrDashboardPreview extends LitElement {
}
// Wait until function that waits until a boolean returns differently
- waitUntil(conditionFunction: any) {
+ // TODO: Remove this, and replace 'waiting' functionality with observer pattern principles.
+ protected waitUntil(conditionFunction: any) {
const poll = (resolve: any) => {
if(conditionFunction()) resolve();
else setTimeout(_ => poll(resolve), 400);
}
return new Promise(poll);
}
+
+ // Callback method for GridStack Grid 'dropped' event. GridStack docs say:
+ // called when an item has been dropped and accepted over a grid. If the item came from another grid, the previous widget node info will also be sent (but dom item long gone).
+ protected onWidgetDrop(_ev: Event, _prevWidget: any, newWidget: DashboardGridNode | undefined) {
+
+ // When a "Widget Card" gets dropped onto the grid, we create a new widget on those coordinates.
+ if(this.grid && newWidget) {
+ this.grid.removeWidget((newWidget.el) as GridStackElement, true, false); // Removes dragged widget first
+ WidgetService.placeNew(newWidget.widgetTypeId, newWidget.x!, newWidget.y!).then((widget) => {
+ this.dispatchEvent(new CustomEvent("created", { detail: widget }));
+ });
+ }
+ }
}
diff --git a/ui/component/or-dashboard-builder/src/or-dashboard-settingspanel.ts b/ui/component/or-dashboard-builder/src/or-dashboard-settingspanel.ts
deleted file mode 100644
index 11dffd778..000000000
--- a/ui/component/or-dashboard-builder/src/or-dashboard-settingspanel.ts
+++ /dev/null
@@ -1,638 +0,0 @@
-import manager, {DefaultColor5, Util} from "@openremote/core";
-import {
- Asset, Attribute, AssetModelUtil, AttributeRef, AssetDescriptor, 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, 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, TemplateResult} from "lit";
-import {customElement, property, state} from "lit/decorators.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=css
-export const widgetSettingsStyling = css`
-
- /* ------------------------------- */
- .switchMwcInputContainer {
- display: flex;
- align-items: center;
- justify-content: space-between;
- }
-
- /* ---------------------------- */
- #attribute-list {
- overflow: auto;
- flex: 1 1 0;
- width: 100%;
- display: flex;
- flex-direction: column;
- }
-
- .attribute-list-item {
- cursor: pointer;
- display: flex;
- flex-direction: row;
- align-items: center;
- padding: 0;
- min-height: 50px;
- }
-
- .attribute-list-item-label {
- display: flex;
- flex: 1 1 0;
- line-height: 16px;
- flex-direction: column;
- }
-
- .attribute-list-item-bullet {
- width: 14px;
- height: 14px;
- border-radius: 7px;
- margin-right: 10px;
- }
-
- .attribute-list-item .button.delete {
- display: none;
- }
-
- .attribute-list-item:hover .button.delete {
- display: block;
- }
-
- /* ---------------------------- */
- .button-clear {
- background: none;
- visibility: hidden;
- color: var(--or-app-color5, ${unsafeCSS(DefaultColor5)});
- --or-icon-fill: var(--or-app-color5, ${unsafeCSS(DefaultColor5)});
- display: inline-block;
- border: none;
- padding: 0;
- cursor: pointer;
- }
-
- .attribute-list-item:hover .button-clear {
- visibility: visible;
- }
-
- .button-clear:hover {
- --or-icon-fill: var(--or-app-color4);
- }
-
- .expanded-panel {
- padding: 6px 16px 24px;
- display: flex;
- flex-direction: column;
- gap: 16px;
- }
-
- /* ---------------------------- */
-
- .threshold-list-item {
- display: flex;
- flex-direction: row;
- align-items: center;
- }
-
- .threshold-list-item-colour {
- height: 100%;
- padding: 0 4px 0 0;
- }
-
- .threshold-list-item:hover .button-clear {
- visibility: visible;
- }
-`
-
-export enum SettingsPanelType {
- SINGLE_ATTRIBUTE, MULTI_ATTRIBUTE, THRESHOLDS, ASSETTYPES,
-}
-
-@customElement('or-dashboard-settingspanel')
-export class OrDashboardSettingsPanel extends LitElement {
-
- @property()
- private readonly type?: SettingsPanelType;
-
- @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.
- private readonly onlyDataAttrs: boolean = true;
-
- @property() // used to specify the attribute valuetype that can be used in the widget.
- public attributeFilter?: ((attribute: Attribute<any>) => boolean) | undefined;
-
- @state()
- private loadedAssets?: Asset[];
-
- static get styles() {
- 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.widgetConfig.attributeRefs != undefined && (!this._config || (changedProperties.get("widgetConfig") != this._config))) {
- const loadedRefs: AttributeRef[] = this.widgetConfig.attributeRefs.filter((attrRef: AttributeRef) => this.isAttributeRefLoaded(attrRef));
- if (loadedRefs.length != this.widgetConfig.attributeRefs.length) {
- this.fetchAssets(this.widgetConfig).then(assets => {
- this.loadedAssets = assets;
- });
- }
- }
- this._config = (this.widgetConfig ? JSON.parse(JSON.stringify(this.widgetConfig)) : undefined);
- }
- }
-
-
- /* ---------------------------------- */
-
- render() {
- switch (this.type) {
-
- case SettingsPanelType.SINGLE_ATTRIBUTE:
- case SettingsPanelType.MULTI_ATTRIBUTE: {
- if (!this._config.attributeRefs) {
- return html`<span>${i18next.t('errorOccurred')}</span>`;
- } else {
- return html`
- ${until(this.getAttributeHTML(this._config, (this.type == SettingsPanelType.MULTI_ATTRIBUTE), this.onlyDataAttrs, this.attributeFilter), html`${i18next.t('loading')}`)}
- `;
- }
- }
- 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>`;
- } else {
- return html`
- ${until(this.getThresholdsHTML(this._config), html`${i18next.t('loading')}`)}
- `;
- }
- }
- }
- }
-
-
- /* --------------------------------- */
-
- // UTILITY FUNCTIONS
-
-
- // Method to update the Grid. For example after changing a setting.
- updateParent(changes: Map<string, any>, force: boolean = false) {
- this.dispatchEvent(new CustomEvent('updated', {detail: {changes: changes, force: force}}));
- }
-
- async getAttributeHTML(config: any, multi: boolean, onlyDataAttrs: boolean = true, attributeFilter?: (attribute: Attribute<any>) => boolean) {
- return html`
- <div style="padding: 0 14px 12px 14px;">
- ${(config.attributeRefs == null || config.attributeRefs.length == 0) ? html`
- <span style="padding: 14px 0; display: block;">${i18next.t('noAttributesConnected')}</span>
- ` : undefined}
- <div id="attribute-list">
- ${(config.attributeRefs != null && this.loadedAssets != null) ? config.attributeRefs.map((attributeRef: AttributeRef) => {
- const asset = this.loadedAssets?.find((x: Asset) => {
- return x.id == attributeRef.id;
- }) as 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);
- return html`
- <div class="attribute-list-item">
- <span style="margin-right: 10px; --or-icon-width: 20px;">${getAssetDescriptorIconTemplate(AssetModelUtil.getAssetDescriptor(asset.type))}</span>
- <div class="attribute-list-item-label">
- <span>${asset.name}</span>
- <span style="font-size:14px; color:grey;">${label}</span>
- </div>
- <button class="button-clear"
- @click="${() => this.removeWidgetAttribute(attributeRef)}">
- <or-icon icon="close-circle"></or-icon>
- </button>
- </div>
- `;
- } else {
- return undefined;
- }
- }) : undefined}
- </div>
- <or-mwc-input .type="${InputType.BUTTON}" label="${i18next.t('attribute')}" icon="${(multi || config.attributeRefs.length == 0) ? "plus" : "swap-horizontal"}"
- style="margin-top: 8px;"
- @or-mwc-input-changed="${() => this.openDialog(config.attributeRefs, multi, onlyDataAttrs, attributeFilter)}">
- </or-mwc-input>
- </div>
- `
- }
-
- isAttributeRefLoaded(attrRef: AttributeRef) {
- return this.loadedAssets?.find((asset) => asset.id == attrRef.id)
- }
-
- // Fetching the assets according to the AttributeRef[] input in DashboardWidget if required.
- async fetchAssets(config: OrWidgetConfig | any): Promise<Asset[] | undefined> {
- if (config.attributeRefs) {
- let assets: Asset[] = [];
- await manager.rest.api.AssetResource.queryAssets({
- ids: config.attributeRefs?.map((x: AttributeRef) => x.id) as string[],
- select: {
- attributes: config.attributeRefs?.map((x: AttributeRef) => x.name) as string[]
- }
- }).then(response => {
- assets = response.data;
- }).catch((reason) => {
- console.error(reason);
- showSnackbar(undefined, i18next.t('errorOccurred'));
- });
- return assets;
- }
- }
-
- setWidgetAttributes(selectedAttrs?: AttributeRef[]) {
- if (this._config != null) {
- this._config.attributeRefs = selectedAttrs;
- this.fetchAssets(this._config).then((assets) => {
- this.loadedAssets = assets;
- this.updateComplete.then(() => {
- this.updateParent(new Map<string, any>([["config", this._config], ["loadedAssets", assets]]));
- });
- });
- }
- }
-
- removeWidgetAttribute(attributeRef: AttributeRef) {
- if (this._config.attributeRefs != null) {
- this._config.attributeRefs.splice(this._config.attributeRefs.indexOf(attributeRef), 1);
- this.updateParent(new Map<string, any>([["config", this._config]]));
- }
- }
-
- // Opening the attribute picker dialog, and listening to its result. (UI related)
- openDialog(attributeRefs: AttributeRef[], multi: boolean, onlyDataAttrs: boolean = true, attributeFilter?: (attribute: Attribute<any>) => boolean) {
- let dialog: OrAttributePicker;
- if (attributeRefs != null) {
- dialog = showDialog(new OrAttributePicker().setMultiSelect(multi).setSelectedAttributes(attributeRefs).setShowOnlyDatapointAttrs(onlyDataAttrs).setAttributeFilter(attributeFilter));
- } else {
- dialog = showDialog(new OrAttributePicker().setMultiSelect(multi).setShowOnlyDatapointAttrs(onlyDataAttrs))
- }
- dialog.addEventListener(OrAttributePickerPickedEvent.NAME, (event: CustomEvent) => {
- this.setWidgetAttributes(event.detail);
- })
- }
-
-
- /* ---------------------------------------------------- */
-
- async getThresholdsHTML(config: OrWidgetConfig | any) {
- if (config.thresholds && config.valueType) {
- return html`
- <div id="thresholds-list" class="expanded-panel">
- ${(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">
- <div class="threshold-list-item-colour">
- <or-mwc-input type="${InputType.COLOUR}" value="${threshold[1]}"
- @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) => {
- 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>
- ${index == 0 ? html`
- <button class="button-clear"
- style="margin-left: 8px;">
- <or-icon icon="lock" style="--or-icon-fill: var(--or-app-color5, ${unsafeCSS(DefaultColor5)});"></or-icon>
- </button>
- ` : html`
- <button class="button-clear"
- style="margin-left: 8px;"
- @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"
- @or-mwc-input-changed="${() => this.addNewThreshold(this._config)}">
- </or-mwc-input>
- ` : null}
- ${(config.valueType === 'boolean') ? html`
- <div class="threshold-list-item">
- <div class="threshold-list-item-colour">
- <or-mwc-input type="${InputType.COLOUR}" value="${config.boolColors.true}"
- @or-mwc-input-changed="${(event: CustomEvent) => {
- this._config.boolColors.true = event.detail.value;
- this.updateParent(new Map<string, any>([["config", 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">
- <div class="threshold-list-item-colour">
- <or-mwc-input type="${InputType.COLOUR}" value="${config.boolColors.false}"
- @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">
- <div class="threshold-list-item-colour">
- <or-mwc-input type="${InputType.COLOUR}" value="${threshold[1]}"
- @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>
- ${index == 0 ? html`
- <button class="button-clear"
- style="margin-left: 8px;">
- <or-icon icon="lock" style="--or-icon-fill: var(--or-app-color5, ${unsafeCSS(DefaultColor5)});"></or-icon>
- </button>
- ` : html`
- <button class="button-clear"
- style="margin-left: 8px;"
- @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"
- @or-mwc-input-changed="${() => this.addNewThreshold(this._config)}">
- </or-mwc-input> </div>
- ` : null}
- </div> `
-
- }
- }
-
- 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: [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) {
- 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() {
- return AssetModelUtil.getAssetDescriptors().filter((t) => t.descriptorType == "asset");
- }
-
- getAttributesByType(type: string) {
- const descriptor: AssetDescriptor = (AssetModelUtil.getAssetDescriptor(type) as AssetDescriptor);
- if(descriptor) {
- 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.assetIds = [];
- 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.assetIds = response.data.map((a) => a.id);
- this._config.valueType = (response.data.length > 0) ? response.data[0].attributes![value].type : "text"; // sometimes no asset exists of that assetType, so using 'text' as fallback.
- }).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 (this._loadedAssetTypes.length === 0) {
- this._loadedAssetTypes = await this.getAssetTypes() as AssetDescriptor[]
- }
- return html`
- <div class="expanded-panel">
- ${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,
- true) : html``
- }
- <div>
- <or-mwc-input .type="${InputType.SELECT}" .disabled="${config.assetType == undefined || config.assetType == ''}" 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>
- <div class="switchMwcInputContainer">
- <span>${i18next.t('dashboard.showLabels')}</span>
- <or-mwc-input .type="${InputType.SWITCH}" style="width: 70px;"
- .value="${config.showLabels}" .disabled="${config.assetType == undefined || config.assetType == ''}"
- @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('dashboard.showUnits')}</span>
- <or-mwc-input .type="${InputType.SWITCH}" style="width: 70px;"
- .value="${config.showUnits}" .disabled="${!config.showLabels || config.assetType == undefined || config.assetType == ''}"
- @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>
- </div>
- `
- }
-}
diff --git a/ui/component/or-dashboard-builder/src/or-dashboard-tree.ts b/ui/component/or-dashboard-builder/src/or-dashboard-tree.ts
index b700825ee..355dc1cfb 100644
--- a/ui/component/or-dashboard-builder/src/or-dashboard-tree.ts
+++ b/ui/component/or-dashboard-builder/src/or-dashboard-tree.ts
@@ -1,34 +1,33 @@
-import {css, html, LitElement} from "lit";
-import { customElement, property} from "lit/decorators.js";
-import {InputType} from '@openremote/or-mwc-components/or-mwc-input';
+import {css, html, LitElement, PropertyValues} from "lit";
+import {customElement, property} from "lit/decorators.js";
+import {InputType} from "@openremote/or-mwc-components/or-mwc-input";
import "@openremote/or-icon";
import {style} from "./style";
-import {Dashboard, DashboardScalingPreset, DashboardScreenPreset} from "@openremote/model";
+import {Dashboard} from "@openremote/model";
import manager from "@openremote/core";
import {ListItem} from "@openremote/or-mwc-components/or-mwc-list";
import "@openremote/or-mwc-components/or-mwc-menu";
import {showOkCancelDialog} from "@openremote/or-mwc-components/or-mwc-dialog";
-import { i18next } from "@openremote/or-translate";
+import {i18next} from "@openremote/or-translate";
import {showSnackbar} from "@openremote/or-mwc-components/or-mwc-snackbar";
import {style as OrAssetTreeStyle} from "@openremote/or-asset-tree";
+import {DashboardService, DashboardSizeOption} from "./service/dashboard-service";
+import {isAxiosError} from "@openremote/rest";
-//language=css
+// language=css
const treeStyling = css`
#header-btns {
display: flex;
flex-direction: row;
padding-right: 5px;
}
+
.node-container {
align-items: center;
padding-left: 10px;
}
`;
-enum DashboardSizeOption {
- DESKTOP, MOBILE
-}
-
@customElement("or-dashboard-tree")
export class OrDashboardTree extends LitElement {
@@ -37,145 +36,154 @@ export class OrDashboardTree extends LitElement {
}
@property()
- protected realm?: string;
+ protected dashboards?: Dashboard[];
@property()
- private dashboards: Dashboard[] | undefined;
+ protected selected?: Dashboard;
@property()
- private selected: Dashboard | undefined;
+ protected readonly realm: string = manager.displayRealm;
@property() // REQUIRED
- private readonly userId?: string;
+ protected readonly userId!: string;
@property()
- private readonly readonly: boolean = true;
+ protected readonly readonly = true;
- @property()
- protected hasChanged: boolean = false;
+ @property() // Whether the selected dashboard has been changed or not.
+ protected readonly hasChanged = false;
@property()
- protected showControls: boolean = true;
+ protected showControls = true;
/* --------------- */
- constructor() {
- super();
- this.updateComplete.then(async () => {
- if(this.dashboards == undefined) {
- await this.getAllDashboards();
- }
- });
- }
-
- shouldUpdate(changedProperties: Map<string, any>) {
- if(changedProperties.size == 1) {
+ shouldUpdate(changedProperties: PropertyValues) {
+ if (changedProperties.size === 1) {
// Prevent any update since it is not necessary in its current state.
// However, do update when dashboard is saved (aka when hasChanged is set back to false)
- if(changedProperties.has("hasChanged") && this.hasChanged) {
+ if (changedProperties.has("hasChanged") && this.hasChanged) {
return false;
}
}
return super.shouldUpdate(changedProperties);
}
- private async getAllDashboards() {
- return manager.rest.api.DashboardResource.getAllRealmDashboards(this.realm!)
- .then((result) => {
- this.dashboards = result.data;
- }).catch((reason) => {
- console.error(reason);
- showSnackbar(undefined, i18next.t('errorOccurred'));
- });
- }
-
- updated(changedProperties: Map<string, any>) {
- if(this.realm == undefined) { this.realm = manager.displayRealm; }
-
- if(changedProperties.has("dashboards") && changedProperties.get("dashboards") != null) {
- this.dispatchEvent(new CustomEvent("updated", { detail: this.dashboards }));
+ updated(changedProperties: PropertyValues) {
+ if (!this.dashboards) {
+ this.getAllDashboards();
}
- if(changedProperties.has("selected")) {
- this.dispatchEvent(new CustomEvent("select", { detail: this.selected }));
+ if (changedProperties.has("dashboards") && changedProperties.get("dashboards") != null) {
+ this.dispatchEvent(new CustomEvent("updated", {detail: this.dashboards}));
+ }
+ if (changedProperties.has("selected")) {
+ this.dispatchEvent(new CustomEvent("select", {detail: this.selected}));
}
}
/* ---------------------- */
- private createDashboard(size: DashboardSizeOption) {
- const randomId = (Math.random() + 1).toString(36).substring(2);
- const dashboard = {
- realm: this.realm!,
- displayName: this.getDefaultDisplayName(size),
- template: {
- id: randomId,
- columns: this.getDefaultColumns(size),
- maxScreenWidth: this.getDefaultMaxScreenWidth(size),
- screenPresets: this.getDefaultScreenPresets(size),
- }
- } as Dashboard
- manager.rest.api.DashboardResource.create(dashboard).then((response => {
- if(response.status == 200) {
- this.dashboards?.push(response.data);
- this.requestUpdate("dashboards");
- this.dispatchEvent(new CustomEvent("created", { detail: { dashboard: response.data }}));
- // Select the item that was created
- this.selected = this.dashboards?.find((x) => { return x.id == response.data.id; });
- }
- })).catch((reason) => {
- console.error(reason);
- showSnackbar(undefined, i18next.t('errorOccurred'));
- })
+ // Gets ALL dashboards the user has access to.
+ // TODO: Optimize this by querying the database, or limit the JSON that is fetched.
+ private async getAllDashboards() {
+ return manager.rest.api.DashboardResource.getAllRealmDashboards(this.realm)
+ .then(result => {
+ this.dashboards = result.data;
+ }).catch(reason => {
+ console.error(reason);
+ showSnackbar(undefined, i18next.t("errorOccurred"));
+ });
}
+ // Selects the dashboard (id).
+ // Will emit a "select" event during the lifecycle
private selectDashboard(id: string | Dashboard | undefined) {
- if(typeof id == 'string') {
- this.selected = this.dashboards?.find((dashboard) => { return dashboard.id == id; });
+ if (typeof id === "string") {
+ this.selected = this.dashboards?.find(dashboard => dashboard.id === id);
} else {
this.selected = id;
}
}
+ // Creates a dashboard, and adds it onto the list.
+ // Dispatch a "created" event, to let parent elements know a new dashboard has been created.
+ // It will automatically select the newly created dashboard.
+ private createDashboard(size: DashboardSizeOption) {
+ DashboardService.create(undefined, size, this.realm).then(dashboard => {
+ if (!this.dashboards) {
+ this.dashboards = [dashboard] as Dashboard[];
+ } else {
+ this.dashboards.push(dashboard);
+ this.requestUpdate("dashboards");
+ }
+ this.dispatchEvent(new CustomEvent("created", {detail: {dashboard}}));
+ this.selectDashboard(dashboard);
+
+ }).catch(e => {
+ console.error(e);
+ if (isAxiosError(e) && e.response?.status === 404) {
+ showSnackbar(undefined, i18next.t("noDashboardFound"));
+ } else {
+ showSnackbar(undefined, i18next.t("errorOccurred"));
+ }
+ });
+ }
+
private deleteDashboard(dashboard: Dashboard) {
- if(dashboard.id != null) {
- manager.rest.api.DashboardResource.delete(this.realm, dashboard.id)
- .then((response) => {
- if(response.status == 204) {
- this.getAllDashboards();
- }
- }).catch((reason) => {
- console.error(reason);
- showSnackbar(undefined, i18next.t('errorOccurred'));
- })
+ if (dashboard.id != null) {
+ DashboardService.delete(dashboard.id, this.realm).then(() => {
+ this.getAllDashboards();
+ }).catch(reason => {
+ console.error(reason);
+ showSnackbar(undefined, i18next.t("errorOccurred"));
+ });
}
}
/* ---------------------- */
+
+ // When a user clicks on a dashboard within the list...
+ protected onDashboardClick(dashboardId: string) {
+ if (dashboardId !== this.selected?.id) {
+ if (this.hasChanged) {
+ showOkCancelDialog(i18next.t("areYouSure"), i18next.t("confirmContinueDashboardModified"), i18next.t("discard")).then((ok: boolean) => {
+ if (ok) {
+ this.selectDashboard(dashboardId);
+ }
+ });
+ } else {
+ this.selectDashboard(dashboardId);
+ }
+ }
+ }
+
+ // Element render method
+ // TODO: Move dashboard filtering to separate method.
protected render() {
- const dashboardItems: ListItem[][] = []
- if(this.dashboards!.length > 0) {
- if(this.userId) {
+ const dashboardItems: ListItem[][] = [];
+ if (this.dashboards && this.dashboards.length > 0) {
+ if (this.userId) {
const myDashboards: Dashboard[] = [];
const otherDashboards: Dashboard[] = [];
- this.dashboards?.forEach((d) => {
- (d.ownerId == this.userId) ? myDashboards.push(d) : otherDashboards.push(d);
- })
- if(myDashboards.length > 0) {
+ this.dashboards?.forEach(d => {
+ (d.ownerId === this.userId) ? myDashboards.push(d) : otherDashboards.push(d);
+ });
+ if (myDashboards.length > 0) {
const items: ListItem[] = [];
- myDashboards.sort((a, b) => a.displayName ? a.displayName.localeCompare(b.displayName!) : 0).forEach((d) => {
- items.push({ icon: "view-dashboard", text: d.displayName, value: d.id });
+ myDashboards.sort((a, b) => a.displayName ? a.displayName.localeCompare(b.displayName!) : 0).forEach(d => {
+ items.push({icon: "view-dashboard", text: d.displayName, value: d.id});
});
dashboardItems.push(items);
}
- if(otherDashboards.length > 0) {
+ if (otherDashboards.length > 0) {
const items: ListItem[] = [];
- otherDashboards.sort((a, b) => a.displayName ? a.displayName.localeCompare(b.displayName!) : 0).forEach((d) => {
- items.push({ icon: "view-dashboard", text: d.displayName, value: d.id });
+ otherDashboards.sort((a, b) => a.displayName ? a.displayName.localeCompare(b.displayName!) : 0).forEach(d => {
+ items.push({icon: "view-dashboard", text: d.displayName, value: d.id});
});
dashboardItems.push(items);
}
@@ -184,111 +192,66 @@ export class OrDashboardTree extends LitElement {
return html`
<div id="menu-header">
<div id="title-container">
- <span id="title">${i18next.t('insights')}</span>
+ <span id="title">${i18next.t("insights")}</span>
</div>
+
+ <!-- Controls header -->
${this.showControls ? html`
<div id="header-btns">
- ${this.selected != null ? html`
- <or-mwc-input type="${InputType.BUTTON}" icon="close" @or-mwc-input-changed="${() => { this.selectDashboard(undefined); }}"></or-mwc-input>
+ ${this.selected !== null ? html`
+ <or-mwc-input type="${InputType.BUTTON}" icon="close" @or-mwc-input-changed="${() => {
+ this.selectDashboard(undefined);
+ }}"></or-mwc-input>
${!this.readonly ? html`
- <or-mwc-input type="${InputType.BUTTON}" icon="delete" @or-mwc-input-changed="${() => { if(this.selected != null) {
- showOkCancelDialog(i18next.t('areYouSure'), i18next.t('dashboard.deletePermanentWarning', { dashboard: this.selected.displayName }), i18next.t('delete')).then((ok: boolean) => { if(ok) { this.deleteDashboard(this.selected!); }});
- }}}"></or-mwc-input>
+ <or-mwc-input type="${InputType.BUTTON}" icon="delete" @or-mwc-input-changed="${() => {
+ if (this.selected != null) {
+ showOkCancelDialog(i18next.t("areYouSure"), i18next.t("dashboard.deletePermanentWarning", {dashboard: this.selected.displayName}), i18next.t("delete")).then((ok: boolean) => {
+ if (ok) {
+ this.deleteDashboard(this.selected!);
+ }
+ });
+ }
+ }}"></or-mwc-input>
` : undefined}
` : undefined}
${!this.readonly ? html`
<or-mwc-input type="${InputType.BUTTON}" class="hideMobile" icon="plus"
- @or-mwc-input-changed="${() => { this.createDashboard(DashboardSizeOption.DESKTOP); }}"
+ @or-mwc-input-changed="${() => {
+ this.createDashboard(DashboardSizeOption.DESKTOP);
+ }}"
></or-mwc-input>
` : undefined}
</div>
` : undefined}
</div>
+
+ <!-- List of dashboards -->
<div id="content">
<div style="padding-top: 8px;">
${dashboardItems.map((items, index) => {
return (items != null && items.length > 0) ? html`
<div style="padding: 8px 0;">
- <span style="font-weight: 500; padding-left: 14px; color: #000000;">${(index == 0 ? i18next.t('dashboard.myDashboards') : i18next.t('dashboard.createdByOthers'))}</span>
+ <span style="font-weight: 500; padding-left: 14px; color: #000000;">${(index === 0 ? i18next.t("dashboard.myDashboards") : i18next.t("dashboard.createdByOthers"))}</span>
<div id="list-container" style="overflow: hidden;">
<ol id="list">
${items.map((listItem: ListItem) => {
return html`
- <li ?data-selected="${listItem.value == this.selected?.id}" @click="${(_evt: MouseEvent) => {
- if(listItem.value != this.selected?.id) {
- if(this.hasChanged) {
- showOkCancelDialog(i18next.t('areYouSure'), i18next.t('confirmContinueDashboardModified'), i18next.t('discard')).then((ok: boolean) => {
- if(ok) { this.selectDashboard(listItem.value); }
- });
- } else {
- this.selectDashboard(listItem.value);
- }
- }
+ <li ?data-selected="${listItem.value === this.selected?.id}" @click="${(_evt: MouseEvent) => {
+ this.onDashboardClick(listItem.value);
}}">
<div class="node-container">
<span class="node-name">${listItem.text} </span>
</div>
</li>
- `
+ `;
})}
</ol>
</div>
</div>
- ` : undefined
+ ` : undefined;
})}
</div>
</div>
- `
- }
-
-
-
- /* ------------------ */
-
- // TODO: Needs to be moved to probably model itself
- private getDefaultColumns(preset: DashboardSizeOption): number {
- switch (preset) {
- case DashboardSizeOption.MOBILE: { return 4; }
- case DashboardSizeOption.DESKTOP: { return 12; }
- default: { return 12; }
- }
- }
-
- // TODO: Needs to be moved to probably model itself
- private getDefaultDisplayName(preset: DashboardSizeOption): string {
- switch (preset) {
- case DashboardSizeOption.DESKTOP: { return i18next.t('dashboard.initialName'); }
- case DashboardSizeOption.MOBILE: { return i18next.t('dashboard.initialName') + " (" + i18next.t('dashboard.size.mobile') + ")"; }
- }
- }
-
- // TODO: Needs to be moved to probably model itself
- private getDefaultScreenPresets(preset: DashboardSizeOption): DashboardScreenPreset[] {
- switch (preset) {
- case DashboardSizeOption.MOBILE: {
- return [{
- id: "mobile",
- displayName: 'dashboard.size.mobile',
- breakpoint: 640,
- scalingPreset: DashboardScalingPreset.KEEP_LAYOUT
- }];
- }
- default: { // DashboardSizeOption.DESKTOP since that is the default
- return [{
- id: "mobile",
- displayName: 'dashboard.size.mobile',
- breakpoint: 640,
- scalingPreset: DashboardScalingPreset.WRAP_TO_SINGLE_COLUMN
- }];
- }
- }
- }
-
- // TODO: Needs to be moved to probably model itself
- private getDefaultMaxScreenWidth(preset: DashboardSizeOption): number {
- switch (preset) {
- case DashboardSizeOption.DESKTOP: return 4000;
- case DashboardSizeOption.MOBILE: return 640;
- }
+ `;
}
}
diff --git a/ui/component/or-dashboard-builder/src/or-dashboard-widget.ts b/ui/component/or-dashboard-builder/src/or-dashboard-widget.ts
deleted file mode 100644
index a11cf1dba..000000000
--- a/ui/component/or-dashboard-builder/src/or-dashboard-widget.ts
+++ /dev/null
@@ -1,113 +0,0 @@
-import {DashboardWidget } from "@openremote/model";
-import { i18next } from "@openremote/or-translate";
-import {css, html, LitElement, TemplateResult } from "lit";
-import { customElement, property, query, state } from "lit/decorators.js";
-import { when } from "lit/directives/when.js";
-import {throttle} from "lodash";
-import {style} from "./style";
-import {widgetTypes} from "./index";
-
-//language=css
-const styling = css`
-`
-
-/* ------------------------------------ */
-
-@customElement("or-dashboard-widget")
-export class OrDashboardWidget extends LitElement {
-
- @property({ hasChanged(oldValue, newValue) { return JSON.stringify(oldValue) != JSON.stringify(newValue); }})
- protected readonly widget?: DashboardWidget;
-
- @property()
- protected readonly editMode?: boolean;
-
- @property()
- protected readonly realm?: string;
-
- @property()
- protected loading: boolean = false;
-
- @state()
- protected error?: string;
-
- @state()
- protected resizeObserver?: ResizeObserver;
-
- @query("#widget-container")
- protected widgetContainerElement?: Element;
-
-
- static get styles() {
- return [styling, style];
- }
-
- constructor() {
- super();
- }
-
- shouldUpdate(changedProperties: Map<PropertyKey, unknown>): boolean {
-
- // Update config if some values in the spec are not set.
- // Useful for when migrations have taken place.
- if(this.widget) {
- const widgetType = widgetTypes.get(this.widget.widgetTypeId!);
- if(widgetType) {
- this.widget.widgetConfig = widgetType.verifyConfigSpec(this.widget);
- }
- }
-
- const changed = changedProperties;
- changed.delete('resizeObserver');
- return changed.size > 0;
- }
-
- disconnectedCallback() {
- super.disconnectedCallback()
- this.resizeObserver?.disconnect();
- }
-
- firstUpdated(_changedProperties: Map<string, any>) {
- this.updateComplete.then(() => {
- const gridItemElement = this.widgetContainerElement;
- if(gridItemElement) {
- this.resizeObserver?.disconnect();
- this.resizeObserver = new ResizeObserver(throttle(() => {
- const isMinimumSize: boolean = (this.widget?.gridItem?.minPixelW != null && this.widget.gridItem.minPixelH != null &&
- (this.widget.gridItem.minPixelW < gridItemElement.clientWidth) && (this.widget.gridItem.minPixelH < gridItemElement.clientHeight)
- );
- this.error = (isMinimumSize ? undefined : i18next.t('dashboard.widgetTooSmall'));
- }, 200));
- this.resizeObserver.observe(gridItemElement);
- } else {
- console.error("gridItemElement could not be found!");
- }
- });
- }
-
-
- protected render() {
- return html`
- <div id="widget-container" style="height: calc(100% - 16px); padding: 8px 16px 8px 16px; display: flex; flex-direction: column;">
- <div style="flex: 0 0 36px; display: flex; justify-content: space-between; align-items: center;">
- <span class="panel-title" style="width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">${this.widget?.displayName?.toUpperCase()}</span>
- </div>
- <div style="flex: 1; max-height: calc(100% - 36px);">
- ${when((!this.error && !this.loading), () => html`
- ${this.getWidgetContent(this.widget!)}
- `, () => html`
- ${this.error ? html`${this.error}` : html`${i18next.t('loading')}`}
- `)}
- </div>
- </div>
- `
- }
-
- getWidgetContent(widget: DashboardWidget): TemplateResult {
- if(widget.gridItem) {
- const widgetEntity = widgetTypes.get(widget.widgetTypeId!);
- return widgetEntity!.getWidgetHTML(widget, this.editMode!, this.realm!);
- }
- return html`<span>${i18next.t('error')}!</span>`;
- }
-}
diff --git a/ui/component/or-dashboard-builder/src/or-dashboard-widgetcontainer.ts b/ui/component/or-dashboard-builder/src/or-dashboard-widgetcontainer.ts
new file mode 100644
index 000000000..bfffdbea5
--- /dev/null
+++ b/ui/component/or-dashboard-builder/src/or-dashboard-widgetcontainer.ts
@@ -0,0 +1,146 @@
+import {i18next} from "@openremote/or-translate";
+import {html, LitElement, PropertyValues} from "lit";
+import {customElement, property, query, state} from "lit/decorators.js";
+import {when} from "lit/directives/when.js";
+import {throttle} from "lodash";
+import {style} from "./style";
+import {DashboardWidget} from "@openremote/model";
+import {OrWidget, WidgetManifest} from "./util/or-widget";
+import {WidgetService} from "./service/widget-service";
+import {WidgetConfig} from "./util/widget-config";
+
+/* ------------------------------------ */
+
+const elemTagName = "or-dashboard-widget-container"
+
+@customElement(elemTagName)
+export class OrDashboardWidgetContainer extends LitElement {
+
+ static tagName = elemTagName;
+
+ @property()
+ protected readonly widget!: DashboardWidget;
+
+ @property()
+ protected loading: boolean = false;
+
+ @state()
+ protected orWidget?: OrWidget
+
+ @state()
+ protected error?: string;
+
+ @query("#widget-container")
+ protected containerElem?: Element;
+
+ protected resizeObserver?: ResizeObserver;
+ protected manifest?: WidgetManifest;
+
+
+ static get styles() {
+ return [style];
+ }
+
+ disconnectedCallback() {
+ super.disconnectedCallback()
+ this.resizeObserver?.disconnect();
+ }
+
+ shouldUpdate(changedProps: Map<PropertyKey, unknown>): boolean {
+ const changed = changedProps;
+
+ // Update config if some values in the spec are not set.
+ // Useful for when migrations have taken place.
+ if (this.widget) {
+ const manifest = WidgetService.getManifest(this.widget.widgetTypeId!);
+ if (manifest) {
+ this.widget.widgetConfig = WidgetService.correctToConfigSpec(manifest, this.widget.widgetConfig);
+ }
+ }
+
+ // Only update widget if certain properties of widget has changed.
+ // For example, when the 'gridItem' field changes, no update is needed since it doesn't apply here.
+ if (changedProps.has('widget') && this.widget) {
+ const oldVal = changedProps.get('widget') as DashboardWidget | undefined;
+ const idChanged = oldVal?.id !== this.widget?.id;
+ const nameChanged = oldVal?.displayName !== this.widget?.displayName;
+ const configChanged = JSON.stringify(oldVal?.widgetConfig) !== JSON.stringify(this.widget?.widgetConfig);
+ if (!(idChanged || nameChanged || configChanged)) {
+ changed.delete('widget');
+ }
+ }
+
+ return (changed.size === 0 ? false : super.shouldUpdate(changedProps));
+ }
+
+ willUpdate(changedProps: Map<string, any>) {
+ super.willUpdate(changedProps);
+
+ if (!this.manifest && this.widget) {
+ this.manifest = WidgetService.getManifest(this.widget.widgetTypeId!);
+ }
+
+ // Create widget
+ if (changedProps.has("widget") && this.widget) {
+ this.initializeWidgetElem(this.manifest!, this.widget.widgetConfig);
+ }
+ }
+
+ firstUpdated(changedProps: PropertyValues) {
+ super.firstUpdated(changedProps);
+
+ if (this.orWidget) {
+ const containerElem = this.containerElem;
+ if (containerElem) {
+ this.resizeObserver?.disconnect();
+ this.resizeObserver = new ResizeObserver(throttle(() => {
+ const minWidth = this.manifest!.minPixelWidth || 0;
+ const minHeight = this.manifest!.minPixelHeight || 0;
+ const isMinimumSize: boolean = (minWidth < containerElem.clientWidth) && (minHeight < containerElem.clientHeight);
+ this.error = (isMinimumSize ? undefined : i18next.t('dashboard.widgetTooSmall'));
+ }, 200));
+ this.resizeObserver.observe(containerElem);
+ } else {
+ console.error("gridItemElement could not be found!");
+ }
+ }
+ }
+
+ protected initializeWidgetElem(manifest: WidgetManifest, config: WidgetConfig) {
+ console.log(`Initialising ${manifest.displayName} widget..`);
+ if (this.orWidget) {
+ this.orWidget.remove();
+ }
+ this.orWidget = manifest.getContentHtml(config);
+ }
+
+ protected render() {
+ const showHeader = !!this.widget.displayName;
+ return html`
+ <div id="widget-container" style="height: calc(100% - 16px); padding: 8px 16px 8px 16px; display: flex; flex-direction: column;">
+
+ <!-- Container title -->
+ ${when(showHeader, () => html`
+ <div style="flex: 0 0 36px; display: flex; justify-content: space-between; align-items: center;">
+ <span class="panel-title" style="width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
+ ${this.widget.displayName?.toUpperCase()}
+ </span>
+ </div>
+ `)}
+
+ <!-- Content -->
+ <div style="flex: 1; max-height: ${showHeader ? 'calc(100% - 36px)' : '100%'};">
+ ${when((!this.error && !this.loading), () => html`
+ ${this.orWidget}
+ `, () => html`
+ ${this.error ? html`${this.error}` : html`${i18next.t('loading')}`}
+ `)}
+ </div>
+ </div>
+ `
+ }
+
+ public refreshContent(force: boolean) {
+ this.orWidget?.refreshContent(force);
+ }
+}
diff --git a/ui/component/or-dashboard-builder/src/or-dashboard-widgetsettings.ts b/ui/component/or-dashboard-builder/src/or-dashboard-widgetsettings.ts
index c4b398172..412fbe095 100644
--- a/ui/component/or-dashboard-builder/src/or-dashboard-widgetsettings.ts
+++ b/ui/component/or-dashboard-builder/src/or-dashboard-widgetsettings.ts
@@ -1,111 +1,31 @@
import {Asset, DashboardWidget } from "@openremote/model";
-import {css, html, LitElement, TemplateResult, unsafeCSS } from "lit";
+import {html, LitElement, TemplateResult, unsafeCSS } from "lit";
import { customElement, property, state } from "lit/decorators.js";
import { InputType, OrInputChangedEvent } from "@openremote/or-mwc-components/or-mwc-input";
import {style} from './style';
-import {DefaultColor5} from "@openremote/core";
import { i18next } from "@openremote/or-translate";
-import {widgetTypes} from "./index";
+import { until } from "lit/directives/until.js";
+import {WidgetService} from "./service/widget-service";
+import {WidgetSettings, WidgetSettingsChangedEvent} from "./util/widget-settings";
+import {WidgetManifest} from "./util/or-widget";
+import { guard } from "lit/directives/guard.js";
const tableStyle = require("@material/data-table/dist/mdc.data-table.css");
-//language=css
-const widgetSettingsStyling = css`
-
- /* ------------------------------- */
- .switchMwcInputContainer {
- display: flex;
- align-items: center;
- justify-content: space-between;
- }
- /* ---------------------------- */
- #attribute-list {
- overflow: auto;
- flex: 1 1 0;
- min-height: 150px;
- width: 100%;
- display: flex;
- flex-direction: column;
- }
-
- .attribute-list-item {
- cursor: pointer;
- display: flex;
- flex-direction: row;
- align-items: center;
- padding: 0;
- min-height: 50px;
- }
-
- .attribute-list-item-label {
- display: flex;
- flex: 1 1 0;
- line-height: 16px;
- flex-direction: column;
- }
-
- .attribute-list-item-bullet {
- width: 14px;
- height: 14px;
- border-radius: 7px;
- margin-right: 10px;
- }
-
- .attribute-list-item .button.delete {
- display: none;
- }
-
- .attribute-list-item:hover .button.delete {
- display: block;
- }
-
- /* ---------------------------- */
- .button-clear {
- background: none;
- visibility: hidden;
- color: var(--or-app-color5, ${unsafeCSS(DefaultColor5)});
- --or-icon-fill: var(--or-app-color5, ${unsafeCSS(DefaultColor5)});
- display: inline-block;
- border: none;
- padding: 0;
- cursor: pointer;
- }
-
- .attribute-list-item:hover .button-clear {
- visibility: visible;
- }
-
- .button-clear:hover {
- --or-icon-fill: var(--or-app-color4);
- }
- /* ---------------------------- */
-`
-
/* ------------------------------------ */
@customElement("or-dashboard-widgetsettings")
export class OrDashboardWidgetsettings extends LitElement {
static get styles() {
- return [unsafeCSS(tableStyle), widgetSettingsStyling, style]
+ return [unsafeCSS(tableStyle), style]
}
@property({type: Object})
- protected selectedWidget: DashboardWidget | undefined;
-
- @property()
- protected realm?: string;
-
- @state() // list of assets that are loaded in the list
- protected loadedAssets: Asset[] | undefined;
+ protected selectedWidget!: DashboardWidget;
@state()
- protected expandedPanels: string[];
-
- constructor() {
- super();
- this.expandedPanels = [];
- }
+ protected settingsElem?: WidgetSettings;
/* ------------------------------------ */
@@ -117,46 +37,43 @@ export class OrDashboardWidgetsettings extends LitElement {
}
protected render() {
- this.updateComplete.then(() => {
- const settingElem = this.shadowRoot?.children[0].children[1];
- settingElem!.addEventListener('updated', (event: any) => {
- this.forceParentUpdate(event.detail.changes, event.detail.force);
- });
- });
- if(this.selectedWidget?.widgetTypeId != null && this.selectedWidget.widgetConfig != null) {
- return this.generateHTML(this.selectedWidget.widgetTypeId, this.selectedWidget.widgetConfig);
- }
- return html`<span>${i18next.t('errorOccurred')}</span>`
- }
-
-
-
-
- /* ----------------------------------- */
-
- // UI generation of all settings fields. Depending on the WidgetType it will
- // return different HTML containing different settings.
- generateHTML(widgetTypeId: string, widgetConfig: any): TemplateResult {
- let htmlGeneral: TemplateResult;
- let htmlContent: TemplateResult;
- htmlGeneral = html`
+ return html`
<div style="padding: 12px;">
<div>
- <or-mwc-input .type="${InputType.TEXT}" style="width: 100%;" .value="${this.selectedWidget?.displayName}" label="${i18next.t('name')}"
+ <or-mwc-input .type="${InputType.TEXT}" style="width: 100%;" .value="${this.selectedWidget?.displayName}" label="${i18next.t('name')}"
@or-mwc-input-changed="${(event: OrInputChangedEvent) => {
this.selectedWidget!.displayName = event.detail.value;
this.forceParentUpdate(new Map<string, any>([['widget', this.selectedWidget]])); }}"
></or-mwc-input>
</div>
</div>
- `
- htmlContent = widgetTypes.get(widgetTypeId)!.getSettingsHTML(this.selectedWidget!, this.realm!);
-
- return html`
<div>
- ${htmlGeneral}
- ${htmlContent}
+ ${guard([this.selectedWidget], () => html`
+ ${until(this.generateContent(this.selectedWidget!.widgetTypeId!), html`Loading...`)}
+ `)}
</div>
- `
+ `;
+ }
+
+ protected async generateContent(widgetTypeId: string): Promise<TemplateResult> {
+ if(!this.settingsElem || this.settingsElem.id !== this.selectedWidget.id) {
+ const manifest = WidgetService.getManifest(widgetTypeId);
+ this.settingsElem = this.initSettings(manifest);
+ }
+ return html`
+ ${this.settingsElem}
+ `;
+ }
+
+ protected initSettings(manifest: WidgetManifest): WidgetSettings {
+ const settingsElem = manifest.getSettingsHtml(this.selectedWidget!.widgetConfig);
+ settingsElem.id = this.selectedWidget.id!;
+ settingsElem.addEventListener(WidgetSettingsChangedEvent.NAME, (ev: any) => this.onWidgetConfigChange(ev));
+ return settingsElem;
+ }
+
+ protected onWidgetConfigChange(ev: WidgetSettingsChangedEvent) {
+ this.selectedWidget!.widgetConfig = ev.detail;
+ this.forceParentUpdate(new Map<string, any>([['widget', this.selectedWidget]]));
}
}
diff --git a/ui/component/or-dashboard-builder/src/panels/assettypes-panel.ts b/ui/component/or-dashboard-builder/src/panels/assettypes-panel.ts
new file mode 100644
index 000000000..9fdb79cac
--- /dev/null
+++ b/ui/component/or-dashboard-builder/src/panels/assettypes-panel.ts
@@ -0,0 +1,241 @@
+import {css, html, LitElement, PropertyValues, TemplateResult} from "lit";
+import {customElement, property, state} from "lit/decorators.js";
+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 {Util} from "@openremote/core";
+
+export class AssetTypeSelectEvent extends CustomEvent<string> {
+
+ public static readonly NAME = "assettype-select";
+
+ constructor(assetTypeName: string) {
+ super(AssetTypeSelectEvent.NAME, {
+ bubbles: true,
+ composed: true,
+ detail: assetTypeName
+ });
+ }
+}
+
+export class AttributeNameSelectEvent extends CustomEvent<string> {
+
+ public static readonly NAME = "attributename-select";
+
+ constructor(attributeName: string) {
+ super(AttributeNameSelectEvent.NAME, {
+ bubbles: true,
+ composed: true,
+ detail: attributeName
+ });
+ }
+}
+
+export class ShowLabelsToggleEvent extends CustomEvent<boolean> {
+
+ public static readonly NAME = "showlabels-toggle";
+
+ constructor(state: boolean) {
+ super(ShowLabelsToggleEvent.NAME, {
+ bubbles: true,
+ composed: true,
+ detail: state
+ });
+ }
+}
+
+export class ShowUnitsToggleEvent extends CustomEvent<boolean> {
+
+ public static readonly NAME = "showunits-toggle";
+
+ constructor(state: boolean) {
+ super(ShowUnitsToggleEvent.NAME, {
+ bubbles: true,
+ composed: true,
+ detail: state
+ });
+ }
+}
+
+const styling = css`
+ .switchMwcInputContainer {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ }
+`
+
+@customElement("assettypes-panel")
+export class AssettypesPanel extends LitElement {
+
+ @property()
+ protected assetType?: string;
+
+ @property()
+ protected attributeName?: string;
+
+ @property()
+ protected attributeList: string[][] = [];
+
+ @property()
+ protected showLabels!: boolean;
+
+ @property()
+ protected showUnits!: boolean;
+
+ @property()
+ protected valueTypes: string[] = [];
+
+ @state()
+ protected _loadedAssetTypes: AssetDescriptor[] = AssetModelUtil.getAssetDescriptors().filter((t) => t.descriptorType === "asset");
+;
+
+ static get styles() {
+ return [styling];
+ }
+
+ protected willUpdate(changedProps: PropertyValues) {
+ super.willUpdate(changedProps);
+ if (changedProps.has("assetType") && this.assetType) {
+ this.attributeList = this.getAttributesByType(this.assetType)!;
+ this.dispatchEvent(new AssetTypeSelectEvent(this.assetType));
+ }
+ if (changedProps.has("attributeName") && this.attributeName) {
+ this.dispatchEvent(new AttributeNameSelectEvent(this.attributeName));
+ }
+ if (changedProps.has("showLabels")) {
+ this.dispatchEvent(new ShowLabelsToggleEvent(this.showLabels));
+ }
+ if (changedProps.has("showUnits")) {
+ this.dispatchEvent(new ShowUnitsToggleEvent(this.showUnits));
+ }
+ }
+
+ protected render(): TemplateResult {
+ const options: [string, string][] = this.attributeList.map(al => [al[0], al[1]]);
+ const searchProvider: (search?: string) => Promise<[any, string][]> = async (search) => {
+ return search ? options.filter(o => o[1].toLowerCase().includes(search.toLowerCase())) : options;
+ };
+ return html`
+ <div style="display: flex; flex-direction: column; gap: 8px;">
+ <div>
+ ${this._loadedAssetTypes.length > 0 ? getContentWithMenuTemplate(
+ this.getAssetTypeTemplate(),
+ this.mapDescriptors(this._loadedAssetTypes, {
+ text: i18next.t("filter.assetTypeMenuNone"),
+ value: "",
+ icon: "selection-ellipse"
+ }) as ListItem[],
+ undefined,
+ (v: string[] | string) => {
+ this.assetType = v as string;
+ },
+ undefined,
+ false,
+ true,
+ true,
+ true) : html``
+ }
+ </div>
+ <div>
+ <or-mwc-input .type="${InputType.SELECT}" label="${i18next.t("filter.attributeLabel")}" .disabled="${!this.assetType}" style="width: 100%;"
+ .options="${options}" .searchProvider="${searchProvider}" .value="${this.attributeName}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => {
+ this.attributeName = ev.detail.value;
+ }}"
+ ></or-mwc-input>
+ </div>
+ <div>
+ <div class="switchMwcInputContainer">
+ <span>${i18next.t("dashboard.showLabels")}</span>
+ <or-mwc-input .type="${InputType.SWITCH}" style="width: 70px;"
+ .value="${this.showLabels}" .disabled="${!this.assetType}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => {
+ this.showLabels = ev.detail.value;
+ }}"
+ ></or-mwc-input>
+ </div>
+ <div class="switchMwcInputContainer">
+ <span>${i18next.t("dashboard.showUnits")}</span>
+ <or-mwc-input .type="${InputType.SWITCH}" style="width: 70px;"
+ .value="${this.showUnits}" .disabled="${!this.showLabels || !this.assetType}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => {
+ this.showUnits = ev.detail.value;
+ }}"
+ ></or-mwc-input>
+ </div>
+
+ </div>
+ </div>
+ `;
+ }
+
+ protected getAssetTypeTemplate(): TemplateResult {
+ if (this.assetType) {
+ const descriptor: AssetDescriptor | undefined = this._loadedAssetTypes.find((at: AssetDescriptor) => at.name === this.assetType);
+ if (descriptor) {
+ return this.getSelectedHeader(descriptor);
+ } else {
+ return this.getSelectHeader();
+ }
+ } else {
+ return this.getSelectHeader();
+ }
+ }
+
+ protected getSelectHeader(): TemplateResult {
+ return html`
+ <or-mwc-input style="width:100%;" type="${InputType.TEXT}" readonly .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}" readonly .label="${i18next.t("filter.assetTypeLabel")}"
+ .iconColor="${descriptor.colour}" iconTrailing="menu-down" icon="${descriptor.icon}"
+ value="${Util.getAssetTypeLabel(descriptor)}">
+ </or-mwc-input>
+ `;
+ }
+
+ 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 getAttributesByType(type: string) {
+ const descriptor: AssetDescriptor = (AssetModelUtil.getAssetDescriptor(type) as AssetDescriptor);
+ if (descriptor) {
+ const typeInfo: AssetTypeInfo = (AssetModelUtil.getAssetTypeInfo(descriptor) as AssetTypeInfo);
+ if (typeInfo?.attributeDescriptors) {
+ return typeInfo.attributeDescriptors
+ .filter((ad) => this.valueTypes.indexOf(ad.type!) > -1)
+ .map((ad) => {
+ const label = Util.getAttributeLabel(ad, undefined, type, false);
+ return [ad.name!, label];
+ })
+ .sort(Util.sortByString((attr) => attr[1]));
+ }
+ }
+ }
+
+}
diff --git a/ui/component/or-dashboard-builder/src/panels/attributes-panel.ts b/ui/component/or-dashboard-builder/src/panels/attributes-panel.ts
new file mode 100644
index 000000000..a8ab8a23e
--- /dev/null
+++ b/ui/component/or-dashboard-builder/src/panels/attributes-panel.ts
@@ -0,0 +1,222 @@
+import {css, CSSResult, html, LitElement, PropertyValues, TemplateResult, unsafeCSS} from "lit";
+import {customElement, property, state} from "lit/decorators.js";
+import {Asset, AssetModelUtil, Attribute, AttributeRef} from "@openremote/model";
+import {style} from "../style";
+import {when} from "lit/directives/when.js";
+import {map} from "lit/directives/map.js";
+import {guard} from "lit/directives/guard.js";
+import {i18next} from "@openremote/or-translate";
+import {InputType} from "@openremote/or-mwc-components/or-mwc-input";
+import manager, {DefaultColor5, Util} from "@openremote/core";
+import {getAssetDescriptorIconTemplate} from "@openremote/or-icon";
+import {OrAttributePicker, OrAttributePickerPickedEvent} from "@openremote/or-attribute-picker";
+import {showDialog} from "@openremote/or-mwc-components/or-mwc-dialog";
+import {showSnackbar} from "@openremote/or-mwc-components/or-mwc-snackbar";
+
+export class AttributesSelectEvent extends CustomEvent<AttributeRef[]> {
+
+ public static readonly NAME = "attribute-select";
+
+ constructor(attributeRefs: AttributeRef[]) {
+ super(AttributesSelectEvent.NAME, {
+ bubbles: true,
+ composed: true,
+ detail: attributeRefs
+ });
+ }
+}
+
+const styling = css`
+ #attribute-list {
+ overflow: auto;
+ flex: 1 1 0;
+ width: 100%;
+ display: flex;
+ flex-direction: column;
+ }
+
+ .attribute-list-item {
+ cursor: pointer;
+ display: flex;
+ flex-direction: row;
+ align-items: center;
+ padding: 0;
+ min-height: 50px;
+ }
+
+ .attribute-list-item-label {
+ display: flex;
+ flex: 1 1 0;
+ line-height: 16px;
+ flex-direction: column;
+ }
+
+ .attribute-list-item-bullet {
+ width: 14px;
+ height: 14px;
+ border-radius: 7px;
+ margin-right: 10px;
+ }
+
+ .attribute-list-item .button.delete {
+ display: none;
+ }
+
+ .attribute-list-item:hover .button.delete {
+ display: block;
+ }
+
+ .button-clear {
+ background: none;
+ visibility: hidden;
+ color: var(--or-app-color5, ${unsafeCSS(DefaultColor5)});
+ --or-icon-fill: var(--or-app-color5, ${unsafeCSS(DefaultColor5)});
+ display: inline-block;
+ border: none;
+ padding: 0;
+ cursor: pointer;
+ }
+
+ .attribute-list-item:hover .button-clear {
+ visibility: visible;
+ }
+
+ .button-clear:hover {
+ --or-icon-fill: var(--or-app-color4);
+ }
+`
+
+@customElement('attributes-panel')
+export class AttributesPanel extends LitElement {
+
+ @property()
+ protected attributeRefs: AttributeRef[] = [];
+
+ @property()
+ protected multi: boolean = false;
+
+ @property()
+ protected onlyDataAttrs: boolean = false;
+
+ @property()
+ protected attributeFilter?: (attribute: Attribute<any>) => boolean;
+
+ @state()
+ protected loadedAssets: Asset[] = [];
+
+ static get styles(): CSSResult[] {
+ return [styling, style];
+ }
+
+ // Lit lifecycle method to compute values during update
+ protected willUpdate(changedProps: PropertyValues) {
+ super.willUpdate(changedProps);
+
+ if (!this.attributeRefs) {
+ this.attributeRefs = [];
+ }
+ if (changedProps.has("attributeRefs") && this.attributeRefs) {
+ if(this.attributeRefs.filter(ar => !this.getLoadedAsset(ar)).length > 0) {
+ this.loadAssets(this.attributeRefs);
+ }
+ // Only dispatch event when it CHANGED, so not from 'undefined' to [];
+ if(changedProps.get("attributeRefs")) {
+ this.dispatchEvent(new AttributesSelectEvent(this.attributeRefs))
+ }
+ }
+ }
+
+ protected getLoadedAsset(attrRef: AttributeRef): Asset | undefined {
+ return this.loadedAssets?.find((asset) => asset.id === attrRef.id)
+ }
+
+ protected removeWidgetAttribute(attributeRef: AttributeRef) {
+ if (this.attributeRefs != null) {
+ this.attributeRefs = this.attributeRefs.filter(ar => ar !== attributeRef);
+ }
+ }
+
+ protected loadAssets(attributeRefs: AttributeRef[]) {
+ this.fetchAssets(attributeRefs).then(assets => {
+ this.loadedAssets = assets;
+ })
+ }
+
+ // Fetching the assets according to the AttributeRef[] input in DashboardWidget if required.
+ // TODO: Move this to more generic spot?
+ async fetchAssets(attributeRefs: AttributeRef[] = []): Promise<Asset[]> {
+ let assets: Asset[] = [];
+ await manager.rest.api.AssetResource.queryAssets({
+ ids: attributeRefs.map((x: AttributeRef) => x.id) as string[],
+ realm: { name: manager.displayRealm },
+ select: {
+ attributes: attributeRefs.map((x: AttributeRef) => x.name) as string[]
+ }
+ }).then(response => {
+ assets = response.data;
+ }).catch((reason) => {
+ console.error(reason);
+ showSnackbar(undefined, i18next.t('errorOccurred'));
+ });
+ return assets;
+ }
+
+ protected openAttributeSelector(attributeRefs: AttributeRef[], multi: boolean, onlyDataAttrs = true, attributeFilter?: (attribute: Attribute<any>) => boolean) {
+ let dialog: OrAttributePicker;
+ if (attributeRefs != null) {
+ dialog = showDialog(new OrAttributePicker().setMultiSelect(multi).setSelectedAttributes(attributeRefs).setShowOnlyDatapointAttrs(onlyDataAttrs).setAttributeFilter(attributeFilter));
+ } else {
+ dialog = showDialog(new OrAttributePicker().setMultiSelect(multi).setShowOnlyDatapointAttrs(onlyDataAttrs))
+ }
+ dialog.addEventListener(OrAttributePickerPickedEvent.NAME, (event: CustomEvent) => {
+ this.attributeRefs = event.detail;
+ })
+ }
+
+ protected render(): TemplateResult {
+ return html`
+ <div>
+ ${when(this.attributeRefs.length > 0, () => html`
+
+ <div id="attribute-list">
+ ${guard([this.attributeRefs, this.loadedAssets], () => html`
+ ${map(this.attributeRefs, (attributeRef: AttributeRef) => {
+ const asset = this.getLoadedAsset(attributeRef);
+ 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);
+ return html`
+ <div class="attribute-list-item">
+ <span style="margin-right: 10px; --or-icon-width: 20px;">${getAssetDescriptorIconTemplate(AssetModelUtil.getAssetDescriptor(asset.type))}</span>
+ <div class="attribute-list-item-label">
+ <span>${asset.name}</span>
+ <span style="font-size:14px; color:grey;">${label}</span>
+ </div>
+ <button class="button-clear"
+ @click="${() => this.removeWidgetAttribute(attributeRef)}">
+ <or-icon icon="close-circle"></or-icon>
+ </button>
+ </div>
+ `;
+ } else {
+ return undefined;
+ }
+ })}
+ `)}
+ </div>
+
+ `, () => html`
+ <span style="padding: 14px 0; display: block;">${i18next.t('noAttributesConnected')}</span>
+ `)}
+
+ <!-- Button that opens attribute selection -->
+ <or-mwc-input .type="${InputType.BUTTON}" label="${i18next.t('attribute')}" icon="${(this.multi || this.attributeRefs.length === 0) ? "plus" : "swap-horizontal"}"
+ style="margin-top: 8px;"
+ @or-mwc-input-changed="${() => this.openAttributeSelector(this.attributeRefs, this.multi, this.onlyDataAttrs, this.attributeFilter)}">
+ </or-mwc-input>
+ </div>
+ `;
+ }
+
+}
diff --git a/ui/component/or-dashboard-builder/src/panels/thresholds-panel.ts b/ui/component/or-dashboard-builder/src/panels/thresholds-panel.ts
new file mode 100644
index 000000000..e7826a2f3
--- /dev/null
+++ b/ui/component/or-dashboard-builder/src/panels/thresholds-panel.ts
@@ -0,0 +1,286 @@
+import {InputType, OrInputChangedEvent} from "@openremote/or-mwc-components/or-mwc-input";
+import {css, CSSResult, html, LitElement, PropertyValues, TemplateResult, unsafeCSS} from "lit";
+import {customElement, property} from "lit/decorators.js";
+import {ifDefined} from "lit/directives/if-defined.js";
+import {i18next} from "@openremote/or-translate";
+import {DefaultColor5} from "@openremote/core";
+import {style} from "../style";
+
+export class ThresholdChangeEvent extends CustomEvent<[number, string][]> {
+
+ public static readonly NAME = "threshold-change";
+
+ constructor(thresholds: [number, string][]) {
+ super(ThresholdChangeEvent.NAME, {
+ bubbles: true,
+ composed: true,
+ detail: thresholds
+ });
+ }
+}
+
+export class TextColorsChangeEvent extends CustomEvent<[string, string][]> {
+
+ public static readonly NAME = "text-colors-change";
+
+ constructor(textColors: [string, string][]) {
+ super(TextColorsChangeEvent.NAME, {
+ bubbles: true,
+ composed: true,
+ detail: textColors
+ });
+ }
+}
+
+export class BoolColorsChangeEvent extends CustomEvent<{ type: string, false: string, true: string }> {
+
+ public static readonly NAME = "bool-colors-change";
+
+ constructor(boolColors: { type: string, false: string, true: string }) {
+ super(BoolColorsChangeEvent.NAME, {
+ bubbles: true,
+ composed: true,
+ detail: boolColors
+ });
+ }
+}
+
+const styling = css`
+
+ #thresholds-list {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ }
+
+ .threshold-list-item {
+ display: flex;
+ flex-direction: row;
+ align-items: center;
+ }
+
+ .threshold-list-item-colour {
+ height: 100%;
+ padding: 0 4px 0 0;
+ }
+
+ .threshold-list-item:hover .button-clear {
+ visibility: visible;
+ }
+
+ .button-clear {
+ background: none;
+ visibility: hidden;
+ color: var(--or-app-color5, ${unsafeCSS(DefaultColor5)});
+ --or-icon-fill: var(--or-app-color5, ${unsafeCSS(DefaultColor5)});
+ display: inline-block;
+ border: none;
+ padding: 0;
+ cursor: pointer;
+ }
+
+ .button-clear:hover {
+ --or-icon-fill: var(--or-app-color4);
+ }
+
+`;
+
+@customElement("thresholds-panel")
+export class ThresholdsPanel extends LitElement {
+
+ @property()
+ protected thresholds: [number, string][] = [];
+
+ @property()
+ protected textColors: [string, string][] = [];
+
+ @property()
+ protected boolColors!: { type: string, false: string, true: string };
+
+ @property()
+ protected readonly min?: number;
+
+ @property()
+ protected readonly max?: number;
+
+ @property()
+ protected readonly valueType!: string;
+
+ static get styles(): CSSResult[] {
+ return [styling, style];
+ }
+
+ protected updated(changedProps: PropertyValues) {
+ if (changedProps.has('thresholds') && this.thresholds) {
+ this.dispatchEvent(new ThresholdChangeEvent(this.thresholds));
+ }
+ if (changedProps.has('textColors') && this.textColors) {
+ this.dispatchEvent(new TextColorsChangeEvent(this.textColors));
+ }
+ if (changedProps.has('boolColors') && this.boolColors) {
+ this.dispatchEvent(new BoolColorsChangeEvent(this.boolColors));
+ }
+ }
+
+ protected render(): TemplateResult {
+ return html`
+ <div id="thresholds-list" class="expanded-panel">
+
+ <!-- Thresholds by number -->
+ ${(this.valueType === 'number' || this.valueType === 'positiveInteger'
+ || this.valueType === 'positiveNumber' || this.valueType === 'negativeInteger'
+ || this.valueType === 'negativeNumber') ? html`
+ ${(this.thresholds as [number, string][]).sort((x, y) => (x[0] < y[0]) ? -1 : 1).map((threshold, index) => {
+ return html`
+ <div class="threshold-list-item">
+ <div class="threshold-list-item-colour">
+ <or-mwc-input type="${InputType.COLOUR}" value="${threshold[1]}"
+ @or-mwc-input-changed="${(event: OrInputChangedEvent) => {
+ this.thresholds[index][1] = event.detail.value;
+ this.requestUpdate('thresholds');
+ }}"
+ ></or-mwc-input>
+ </div>
+ <or-mwc-input type="${InputType.NUMBER}" comfortable .value="${threshold[0]}"
+ ?disabled="${index === 0 && this.max}"
+ .min="${ifDefined(this.min)}" .max="${ifDefined(this.max)}"
+ @or-mwc-input-changed="${(event: OrInputChangedEvent) => {
+ if ((!this.min || event.detail.value >= this.min) && (!this.max || event.detail.value <= this.max)) {
+ this.thresholds[index][0] = event.detail.value;
+ this.requestUpdate('thresholds');
+ }
+ }}"
+ ></or-mwc-input>
+ ${index === 0 ? html`
+ <button class="button-clear"
+ style="margin-left: 8px;">
+ <or-icon icon="lock" style="--or-icon-fill: var(--or-app-color5, ${unsafeCSS(DefaultColor5)});"></or-icon>
+ </button>
+ ` : html`
+ <button class="button-clear"
+ style="margin-left: 8px;"
+ @click="${() => {
+ this.removeThreshold(threshold);
+ }}">
+ <or-icon icon="close-circle"></or-icon>
+ </button>
+ `}
+ </div>
+ `
+ })}
+ <or-mwc-input .type="${InputType.BUTTON}" label="${i18next.t('threshold')}" icon="plus"
+ @or-mwc-input-changed="${() => this.addNewThreshold()}">
+ </or-mwc-input>
+ ` : null}
+
+ <!-- Thresholds by boolean -->
+ ${(this.valueType === 'boolean') ? html`
+ <div class="threshold-list-item">
+ <div class="threshold-list-item-colour">
+ <or-mwc-input type="${InputType.COLOUR}" value="${this.boolColors.true}"
+ @or-mwc-input-changed="${(event: OrInputChangedEvent) => {
+ this.boolColors.true = event.detail.value;
+ this.requestUpdate('boolColors');
+ }}"
+ ></or-mwc-input>
+ </div>
+ <or-mwc-input type="${InputType.TEXT}" comfortable .value="${'True'}" .readonly="${true}"
+ ></or-mwc-input>
+ </div>
+ <div class="threshold-list-item">
+ <div class="threshold-list-item-colour">
+ <or-mwc-input type="${InputType.COLOUR}" value="${this.boolColors.false}"
+ @or-mwc-input-changed="${(event: OrInputChangedEvent) => {
+ this.boolColors.false = event.detail.value;
+ this.requestUpdate('boolColors');
+ }}"
+ ></or-mwc-input>
+ </div>
+ <or-mwc-input type="${InputType.TEXT}" comfortable .value="${'False'}" .readonly="${true}"
+ ></or-mwc-input>
+ </div>
+ ` : null}
+
+ <!-- Thresholds by string -->
+ ${(this.valueType === 'text' && this.textColors) ? html`
+ ${(this.textColors as [string, string][]).map((threshold, index) => {
+ return html`
+ <div class="threshold-list-item">
+ <div class="threshold-list-item-colour">
+ <or-mwc-input type="${InputType.COLOUR}" value="${threshold[1]}"
+ @or-mwc-input-changed="${(event: OrInputChangedEvent) => {
+ this.textColors[index][1] = event.detail.value;
+ this.requestUpdate('textColors');
+ }}"
+ ></or-mwc-input>
+ </div>
+ <or-mwc-input type="${InputType.TEXT}" comfortable .value="${threshold[0]}"
+ @or-mwc-input-changed="${(event: OrInputChangedEvent) => {
+ this.textColors[index][0] = event.detail.value;
+ this.requestUpdate('textColors');
+ }}"
+
+ ></or-mwc-input>
+ ${index === 0 ? html`
+ <button class="button-clear"
+ style="margin-left: 8px;">
+ <or-icon icon="lock" style="--or-icon-fill: var(--or-app-color5, ${unsafeCSS(DefaultColor5)});"></or-icon>
+ </button>
+ ` : html`
+ <button class="button-clear"
+ style="margin-left: 8px;"
+ @click="${() => {
+ this.removeThreshold(threshold);
+ }}">
+ <or-icon icon="close-circle"></or-icon>
+ </button>
+ `}
+ </div>
+ `
+ })}
+ <or-mwc-input .type="${InputType.BUTTON}" label="${i18next.t('threshold')}" icon="plus"
+ @or-mwc-input-changed="${() => this.addNewThreshold()}">
+ </or-mwc-input>
+ ` : null}
+ </div>
+ `
+ }
+
+ protected removeThreshold(threshold: [any, string]) {
+ switch (typeof threshold[0]) {
+ case "number":
+ this.thresholds = (this.thresholds as [number, string][]).filter((x) => x !== threshold);
+ break;
+ default:
+ this.textColors = (this.textColors as [string, string][]).filter((x) => x !== threshold);
+ break;
+ }
+ }
+
+ protected addThreshold(threshold: [any, string]) {
+ switch (typeof threshold[0]) {
+ case "number":
+ (this.thresholds as [number, string][]).push(threshold as [number, string]);
+ this.requestUpdate('thresholds');
+ break;
+ default:
+ (this.textColors as [string, string][]).push(threshold as [string, string]);
+ this.requestUpdate('textColors');
+ break;
+ }
+ }
+
+ protected addNewThreshold() {
+ if (this.valueType === 'text') {
+ this.addThreshold(["new", "#000000"]);
+ } else {
+ const suggestedValue = (this.thresholds[this.thresholds.length - 1][0] + 10);
+ this.addThreshold([(!this.max || suggestedValue <= this.max ? suggestedValue : this.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');
+ })
+ }
+}
diff --git a/ui/component/or-dashboard-builder/src/service/dashboard-service.ts b/ui/component/or-dashboard-builder/src/service/dashboard-service.ts
new file mode 100644
index 000000000..50239c8f3
--- /dev/null
+++ b/ui/component/or-dashboard-builder/src/service/dashboard-service.ts
@@ -0,0 +1,83 @@
+import {Dashboard, DashboardRefreshInterval, DashboardScalingPreset, DashboardScreenPreset} from "@openremote/model";
+import manager from "@openremote/core";
+import {i18next} from "@openremote/or-translate";
+
+export enum DashboardSizeOption {
+ DESKTOP, MOBILE
+}
+
+export class DashboardService {
+
+ public static async create(dashboard?: Dashboard, size: DashboardSizeOption = DashboardSizeOption.DESKTOP, realm: string = manager.displayRealm, post = true): Promise<Dashboard> {
+ if(!dashboard) {
+ const randomId = (Math.random() + 1).toString(36).substring(2);
+ dashboard = {
+ realm: realm,
+ displayName: this.getDefaultDisplayName(size),
+ template: {
+ id: randomId,
+ columns: this.getDefaultColumns(size),
+ maxScreenWidth: this.getDefaultMaxScreenWidth(size),
+ refreshInterval: DashboardRefreshInterval.OFF,
+ screenPresets: this.getDefaultScreenPresets(size),
+ }
+ } as Dashboard;
+ }
+
+ if(post) {
+ return (await manager.rest.api.DashboardResource.create(dashboard)).data;
+ } else {
+ return dashboard;
+ }
+ }
+
+ public static async delete(id: string, realm: string = manager.displayRealm) {
+ return (await manager.rest.api.DashboardResource.delete(realm, id)).data;
+ }
+
+
+ /* -------------------------------------------------------- */
+
+ private static getDefaultColumns(preset: DashboardSizeOption): number {
+ switch (preset) {
+ case DashboardSizeOption.MOBILE: { return 4; }
+ case DashboardSizeOption.DESKTOP: { return 12; }
+ default: { return 12; }
+ }
+ }
+
+ private static getDefaultDisplayName(preset: DashboardSizeOption): string {
+ switch (preset) {
+ case DashboardSizeOption.DESKTOP: { return i18next.t('dashboard.initialName'); }
+ case DashboardSizeOption.MOBILE: { return i18next.t('dashboard.initialName') + " (" + i18next.t('dashboard.size.mobile') + ")"; }
+ }
+ }
+
+ private static getDefaultScreenPresets(preset: DashboardSizeOption): DashboardScreenPreset[] {
+ switch (preset) {
+ case DashboardSizeOption.MOBILE: {
+ return [{
+ id: "mobile",
+ displayName: 'dashboard.size.mobile',
+ breakpoint: 640,
+ scalingPreset: DashboardScalingPreset.KEEP_LAYOUT
+ }];
+ }
+ default: { // DashboardSizeOption.DESKTOP since that is the default
+ return [{
+ id: "mobile",
+ displayName: 'dashboard.size.mobile',
+ breakpoint: 640,
+ scalingPreset: DashboardScalingPreset.WRAP_TO_SINGLE_COLUMN
+ }];
+ }
+ }
+ }
+
+ private static getDefaultMaxScreenWidth(preset: DashboardSizeOption): number {
+ switch (preset) {
+ case DashboardSizeOption.DESKTOP: return 4000;
+ case DashboardSizeOption.MOBILE: return 640;
+ }
+ }
+}
diff --git a/ui/component/or-dashboard-builder/src/service/widget-service.ts b/ui/component/or-dashboard-builder/src/service/widget-service.ts
new file mode 100644
index 000000000..03af1f2df
--- /dev/null
+++ b/ui/component/or-dashboard-builder/src/service/widget-service.ts
@@ -0,0 +1,48 @@
+import {DashboardWidget} from "@openremote/model";
+import {widgetTypes} from "../index";
+import {WidgetConfig} from "../util/widget-config";
+import {Util} from "@openremote/core";
+import {WidgetManifest} from "../util/or-widget";
+
+export class WidgetService {
+
+ public static getManifest(widgetTypeId: string) {
+ const manifest = widgetTypes.get(widgetTypeId);
+ if(!manifest) {
+ throw new Error("Widget manifest could not be found during widget creation.");
+ }
+ return manifest;
+ }
+
+ public static async placeNew(widgetTypeId: string, x: number, y: number): Promise<DashboardWidget> {
+ const randomId = (Math.random() + 1).toString(36).substring(2);
+ const manifest = this.getManifest(widgetTypeId);
+ const widget = {
+ id: randomId,
+ displayName: manifest.displayName,
+ gridItem: {
+ id: randomId,
+ x: x,
+ y: y,
+ w: 2,
+ h: 2,
+ minW: manifest.minColumnWidth,
+ minH: manifest.minColumnHeight,
+ minPixelW: manifest.minPixelWidth,
+ minPixelH: manifest.minPixelHeight,
+ noResize: false,
+ noMove: false,
+ locked: false,
+ }, // Left empty until it is generated by or-dashboard-preview
+ widgetConfig: manifest.getDefaultConfig(),
+ widgetTypeId: widgetTypeId
+ } as DashboardWidget;
+ return widget;
+ }
+
+ // Method used to correct the OrWidgetConfig specification
+ // So, if certain fields are removed or invalid, it will be corrected by merging the object with the default OrWidgetConfig.
+ public static correctToConfigSpec(manifest: WidgetManifest, widgetConfig: WidgetConfig) {
+ return Util.mergeObjects(manifest.getDefaultConfig(), widgetConfig, false) as WidgetConfig;
+ }
+}
diff --git a/ui/component/or-dashboard-builder/src/settings/chart-settings.ts b/ui/component/or-dashboard-builder/src/settings/chart-settings.ts
new file mode 100644
index 000000000..618acb24e
--- /dev/null
+++ b/ui/component/or-dashboard-builder/src/settings/chart-settings.ts
@@ -0,0 +1,197 @@
+import {css, html, TemplateResult } from "lit";
+import { customElement } from "lit/decorators.js";
+import {WidgetSettings} from "../util/widget-settings";
+import "../panels/attributes-panel";
+import "../util/settings-panel";
+import {i18next} from "@openremote/or-translate";
+import {AttributesSelectEvent} from "../panels/attributes-panel";
+import {AssetDatapointIntervalQuery, AssetDatapointIntervalQueryFormula, Attribute, AttributeRef} from "@openremote/model";
+import {ChartWidgetConfig} from "../widgets/chart-widget";
+import { InputType, OrInputChangedEvent } from "@openremote/or-mwc-components/or-mwc-input";
+import {TimePresetCallback} from "@openremote/or-chart";
+
+const styling = css`
+ .switch-container {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ }
+`
+
+
+@customElement("chart-settings")
+export class ChartSettings extends WidgetSettings {
+
+ protected readonly widgetConfig!: ChartWidgetConfig
+
+ protected timePresetOptions: Map<string, TimePresetCallback> = new Map<string, TimePresetCallback>();
+ protected samplingOptions: Map<string, string> = new Map<string, string>();
+
+ public setTimePresetOptions(options: Map<string, TimePresetCallback>) {
+ this.timePresetOptions = options;
+ }
+
+ public setSamplingOptions(options: Map<string, string>) {
+ this.samplingOptions = options;
+ }
+
+ static get styles() {
+ return [...super.styles, styling];
+ }
+
+ protected render(): TemplateResult {
+ const attributeFilter: (attr: Attribute<any>) => boolean = (attr): boolean => {
+ return ["boolean", "positiveInteger", "positiveNumber", "number", "long", "integer", "bigInteger", "negativeInteger", "negativeNumber", "bigNumber", "integerByte", "direction"].includes(attr.type!)
+ };
+ const min = this.widgetConfig.chartOptions.options?.scales?.y?.min;
+ const max = this.widgetConfig.chartOptions.options?.scales?.y?.max;
+ const samplingValue = Array.from(this.samplingOptions.entries()).find((entry => entry[1] === this.widgetConfig.datapointQuery.type))![0]
+ return html`
+ <div>
+ <!-- Attribute selection -->
+ <settings-panel displayName="${i18next.t('attributes')}" expanded="${true}">
+ <attributes-panel .attributeRefs="${this.widgetConfig.attributeRefs}" onlyDataAttrs="${true}" .attributeFilter="${attributeFilter}" multi="${true}" style="padding-bottom: 12px;"
+ @attribute-select="${(ev: AttributesSelectEvent) => this.onAttributesSelect(ev)}"
+ ></attributes-panel>
+ </settings-panel>
+
+ <!-- Display options -->
+ <settings-panel displayName="${i18next.t('display')}" expanded="${true}">
+ <div style="padding-bottom: 12px; display: flex; flex-direction: column; gap: 6px;">
+ <!-- Timeframe -->
+ <div>
+ <or-mwc-input .type="${InputType.SELECT}" label="${i18next.t('timeframeDefault')}" style="width: 100%;"
+ .options="${Array.from(this.timePresetOptions.keys())}" value="${this.widgetConfig.defaultTimePresetKey}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onTimePresetSelect(ev)}"
+ ></or-mwc-input>
+ </div>
+ <!-- Y Min/max options -->
+ <div>
+ <div class="switch-container">
+ <span>${i18next.t('dashboard.allowTimerangeSelect')}</span>
+ <or-mwc-input .type="${InputType.SWITCH}" style="margin: 0 -10px;" .value="${!this.widgetConfig.showTimestampControls}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onTimestampControlsToggle(ev)}"
+ ></or-mwc-input>
+ </div>
+ <div class="switch-container">
+ <span>${i18next.t('dashboard.showLegend')}</span>
+ <or-mwc-input .type="${InputType.SWITCH}" style="margin: 0 -10px;" .value="${this.widgetConfig.showLegend}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onShowLegendToggle(ev)}"
+ ></or-mwc-input>
+ </div>
+ </div>
+ </div>
+ </settings-panel>
+
+ <!-- Chart configuration -->
+ <settings-panel displayName="${i18next.t('dashboard.chartConfig')}" expanded="${true}">
+ <div style="padding-bottom: 12px;">
+ <div style="display: flex;">
+ ${max !== undefined ? html`
+ <or-mwc-input .type="${InputType.NUMBER}" label="${i18next.t('yAxis') + ' ' + i18next.t('max')}" .value="${max}" style="width: 100%;"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onMinMaxValueChange('max', ev)}"
+ ></or-mwc-input>
+ ` : html`
+ <or-mwc-input .type="${InputType.TEXT}" label="${i18next.t('yAxis') + ' ' + i18next.t('max')}" disabled="true" value="auto" style="width: 100%;"></or-mwc-input>
+ `}
+ <or-mwc-input .type="${InputType.SWITCH}" style="margin: 0 -10px 0 0;" .value="${max !== undefined}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onMinMaxValueToggle('max', ev)}"
+ ></or-mwc-input>
+ </div>
+ <div style="display: flex; margin-top: 12px;">
+ ${min !== undefined ? html`
+ <or-mwc-input .type="${InputType.NUMBER}" label="${i18next.t('yAxis') + ' ' + i18next.t('min')}" .value="${min}" style="width: 100%;"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onMinMaxValueChange('min', ev)}"
+ ></or-mwc-input>
+ ` : html`
+ <or-mwc-input .type="${InputType.TEXT}" label="${i18next.t('yAxis') + ' ' + i18next.t('min')}" disabled="true" value="auto" style="width: 100%;"></or-mwc-input>
+ `}
+ <or-mwc-input .type="${InputType.SWITCH}" style="margin: 0 -10px 0 0;" .value="${min !== undefined}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onMinMaxValueToggle('min', ev)}"
+ ></or-mwc-input>
+ </div>
+ </div>
+ </settings-panel>
+
+ <!-- Data sampling options -->
+ <settings-panel displayName="${i18next.t('dataSampling')}" expanded="${true}">
+ <div style="padding-bottom: 12px; display: flex; flex-direction: column; gap: 12px;">
+ <div>
+ <or-mwc-input .type="${InputType.SELECT}" style="width: 100%" .options="${Array.from(this.samplingOptions.keys())}" .value="${samplingValue}"
+ label="${i18next.t('algorithm')}" @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onSamplingQueryChange(ev)}"
+ ></or-mwc-input>
+ </div>
+ <div>
+ ${this.getSamplingOptionsTemplate(this.widgetConfig.datapointQuery.type)}
+ </div>
+ </div>
+ </settings-panel>
+ </div>
+ `;
+ }
+
+ protected getSamplingOptionsTemplate(type: any): TemplateResult {
+ switch (type) {
+ case 'interval': {
+ const intervalQuery = this.widgetConfig.datapointQuery as AssetDatapointIntervalQuery;
+ const formulaOptions = [AssetDatapointIntervalQueryFormula.AVG, AssetDatapointIntervalQueryFormula.MIN, AssetDatapointIntervalQueryFormula.MAX];
+ return html`
+ <or-mwc-input .type="${InputType.SELECT}" style="width: 100%;" .options="${formulaOptions}"
+ .value="${intervalQuery.formula}" label="${i18next.t('algorithmMethod')}" @or-mwc-input-changed="${(event: OrInputChangedEvent) => {
+ intervalQuery.formula = event.detail.value;
+ this.notifyConfigUpdate();
+ }}"
+ ></or-mwc-input>
+ `;
+ }
+ default:
+ return html``;
+ }
+ }
+
+
+ protected onAttributesSelect(ev: AttributesSelectEvent) {
+ this.widgetConfig.attributeRefs = ev.detail as AttributeRef[];
+ this.notifyConfigUpdate();
+ }
+
+ protected onTimePresetSelect(ev: OrInputChangedEvent) {
+ this.widgetConfig.defaultTimePresetKey = ev.detail.value.toString();
+ this.notifyConfigUpdate();
+ }
+
+ protected onTimestampControlsToggle(ev: OrInputChangedEvent) {
+ this.widgetConfig.showTimestampControls = !ev.detail.value;
+ this.notifyConfigUpdate();
+ }
+
+ protected onShowLegendToggle(ev: OrInputChangedEvent) {
+ this.widgetConfig.showLegend = ev.detail.value;
+ this.notifyConfigUpdate();
+ }
+
+ protected onMinMaxValueChange(type: 'min' | 'max', ev: OrInputChangedEvent) {
+ switch (type) {
+ case "max":
+ this.widgetConfig.chartOptions.options.scales.y.max = ev.detail.value; break;
+ case "min":
+ this.widgetConfig.chartOptions.options.scales.y.min = ev.detail.value; break;
+ }
+ this.notifyConfigUpdate();
+ }
+
+ protected onMinMaxValueToggle(type: 'min' | 'max', ev: OrInputChangedEvent) {
+ switch (type) {
+ case "max":
+ this.widgetConfig.chartOptions.options.scales.y.max = (ev.detail.value ? 100 : undefined); break;
+ case "min":
+ this.widgetConfig.chartOptions.options.scales.y.min = (ev.detail.value ? 0 : undefined); break;
+ }
+ this.notifyConfigUpdate();
+ }
+
+ protected onSamplingQueryChange(ev: OrInputChangedEvent) {
+ this.widgetConfig.datapointQuery.type = this.samplingOptions.get(ev.detail.value)! as any;
+ this.notifyConfigUpdate();
+ }
+}
diff --git a/ui/component/or-dashboard-builder/src/settings/gauge-settings.ts b/ui/component/or-dashboard-builder/src/settings/gauge-settings.ts
new file mode 100644
index 000000000..e8f1cd09a
--- /dev/null
+++ b/ui/component/or-dashboard-builder/src/settings/gauge-settings.ts
@@ -0,0 +1,86 @@
+import {html, TemplateResult} from "lit";
+import {customElement} from "lit/decorators.js";
+import {WidgetSettings} from "../util/widget-settings";
+import {i18next} from "@openremote/or-translate";
+import {GaugeWidgetConfig} from "../widgets/gauge-widget";
+import {AttributesSelectEvent} from "../panels/attributes-panel";
+import {Attribute, AttributeRef} from "@openremote/model";
+import { InputType, OrInputChangedEvent } from "@openremote/or-mwc-components/or-mwc-input";
+import {ThresholdChangeEvent} from "../panels/thresholds-panel";
+import "../panels/thresholds-panel";
+
+@customElement("gauge-settings")
+export class GaugeSettings extends WidgetSettings {
+
+ // Override of widgetConfig with extended type
+ protected widgetConfig!: GaugeWidgetConfig;
+
+ protected render(): TemplateResult {
+ const attributeFilter: (attr: Attribute<any>) => boolean = (attr): boolean => {
+ return ["positiveInteger", "positiveNumber", "number", "long", "integer", "bigInteger", "negativeInteger", "negativeNumber", "bigNumber", "integerByte", "direction"].includes(attr.type!)
+ };
+ return html`
+ <div>
+ <!-- Attribute selection -->
+ <settings-panel displayName="${i18next.t('attributes')}" expanded="${true}">
+ <attributes-panel .attributeRefs="${this.widgetConfig.attributeRefs}" onlyDataAttrs="${false}" .attributeFilter="${attributeFilter}" style="padding-bottom: 12px;"
+ @attribute-select="${(ev: AttributesSelectEvent) => this.onAttributesSelect(ev)}"
+ ></attributes-panel>
+ </settings-panel>
+
+ <!-- Min/max and decimals options-->
+ <settings-panel displayName="${i18next.t('values')}" expanded="${true}">
+ <div style="padding-bottom: 12px; display: flex; flex-direction: column; gap: 12px;">
+ <div style="display: flex; gap: 8px;">
+ <or-mwc-input type="${InputType.NUMBER}" label="${i18next.t('min')}" .max="${this.widgetConfig.max}" .value="${this.widgetConfig.min}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onMinMaxValueChange('min', ev)}"
+ ></or-mwc-input>
+ <or-mwc-input type="${InputType.NUMBER}" label="${i18next.t('max')}" .min="${this.widgetConfig.min}" .value="${this.widgetConfig.max}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onMinMaxValueChange('max', ev)}"
+ ></or-mwc-input>
+ </div>
+ <div>
+ <or-mwc-input type="${InputType.NUMBER}" style="width: 100%;" .value="${this.widgetConfig.decimals}" label="${i18next.t('decimals')}" .min="${0}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onDecimalsChange(ev)}"
+ ></or-mwc-input>
+ </div>
+ </div>
+ </settings-panel>
+
+ <!-- Thresholds panel -->
+ <settings-panel displayName="${i18next.t('thresholds')}" expanded="${true}">
+ <thresholds-panel .thresholds="${this.widgetConfig.thresholds}" .valueType="${'number'}" style="padding-bottom: 12px;"
+ .min="${this.widgetConfig.min}" .max="${this.widgetConfig.max}"
+ @threshold-change="${(ev: ThresholdChangeEvent) => this.onThresholdChange(ev)}">
+ </thresholds-panel>
+ </settings-panel>
+ </div>
+ `;
+ }
+
+ protected onAttributesSelect(ev: AttributesSelectEvent) {
+ this.widgetConfig.attributeRefs = ev.detail as AttributeRef[];
+ this.notifyConfigUpdate();
+ }
+
+ protected onMinMaxValueChange(type: 'min' | 'max', ev: OrInputChangedEvent) {
+ switch (type) {
+ case "max":
+ this.widgetConfig.max = ev.detail.value; break;
+ case "min":
+ this.widgetConfig.min = ev.detail.value; break;
+ }
+ this.notifyConfigUpdate();
+ }
+
+ protected onDecimalsChange(ev: OrInputChangedEvent) {
+ this.widgetConfig.decimals = ev.detail.value;
+ this.notifyConfigUpdate();
+ }
+
+ protected onThresholdChange(ev: ThresholdChangeEvent) {
+ this.widgetConfig.thresholds = ev.detail;
+ this.notifyConfigUpdate();
+ }
+
+}
diff --git a/ui/component/or-dashboard-builder/src/settings/image-settings.ts b/ui/component/or-dashboard-builder/src/settings/image-settings.ts
new file mode 100644
index 000000000..fd21f684f
--- /dev/null
+++ b/ui/component/or-dashboard-builder/src/settings/image-settings.ts
@@ -0,0 +1,175 @@
+import {css, html, PropertyValues, TemplateResult } from "lit";
+import { customElement, state } from "lit/decorators.js";
+import {ImageWidgetConfig} from "../widgets/image-widget";
+import {i18next} from "@openremote/or-translate";
+import {AttributesSelectEvent} from "../panels/attributes-panel";
+import {Asset, AssetModelUtil, AttributeRef} from "@openremote/model";
+import { map } from "lit/directives/map.js";
+import { InputType, OrInputChangedEvent } from "@openremote/or-mwc-components/or-mwc-input";
+import {Util} from "@openremote/core";
+import { when } from "lit/directives/when.js";
+import {AssetWidgetSettings} from "../util/or-asset-widget";
+
+const styling = css`
+ #marker-container {
+ display: flex;
+ justify-content: flex-end;
+ align-items: center;
+ }
+`;
+
+@customElement("image-settings")
+export class ImageSettings extends AssetWidgetSettings {
+
+ // Override of widgetConfig with extended type
+ protected readonly widgetConfig!: ImageWidgetConfig;
+
+ static get styles() {
+ return [...super.styles, styling]
+ }
+
+ protected willUpdate(changedProps: PropertyValues) {
+ super.willUpdate(changedProps);
+ if(changedProps.has('widgetConfig') && this.widgetConfig) {
+ this.updateCoordinateMap(this.widgetConfig);
+ this.loadAssets();
+ }
+ }
+
+ protected loadAssets() {
+ const missingAssets = this.widgetConfig.attributeRefs.filter(ref => !this.isAttributeRefLoaded(ref));
+ if(missingAssets.length > 0) {
+ this.fetchAssets(this.widgetConfig.attributeRefs).then((assets) => {
+ if(assets === undefined) {
+ this.loadedAssets = [];
+ } else {
+ this.loadedAssets = assets;
+ }
+ });
+ }
+ }
+
+ protected render(): TemplateResult {
+ return html`
+ <div>
+ <!-- Attributes selector -->
+ <settings-panel displayName="${i18next.t('attributes')}" expanded="${true}">
+ <attributes-panel .attributeRefs="${this.widgetConfig.attributeRefs}" onlyDataAttrs="${false}" multi="${true}"
+ @attribute-select="${(ev: AttributesSelectEvent) => this.onAttributesSelect(ev)}"
+ ></attributes-panel>
+ </settings-panel>
+
+ <!-- Marker coordinates -->
+ <settings-panel displayName="${i18next.t('dashboard.markerCoordinates')}" expanded="${true}">
+ <div style="display: flex; flex-direction: column; gap: 8px;">
+ ${map(this.draftCoordinateEntries(this.widgetConfig), template => template)}
+ </div>
+ </settings-panel>
+
+ <!-- Image settings -->
+ <settings-panel displayName="${i18next.t('dashboard.imageSettings')}" expanded="${true}">
+ <div>
+ <or-mwc-input style="width: 100%;" type="${InputType.TEXT}" label="${i18next.t('dashboard.imageUrl')}" .value="${this.widgetConfig.imagePath}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onImageUrlUpdate(ev)}"
+ ></or-mwc-input>
+ </div>
+ </settings-panel>
+ </div>
+ `;
+ }
+
+ protected onAttributesSelect(ev: AttributesSelectEvent) {
+ this.widgetConfig.attributeRefs = ev.detail as AttributeRef[];
+ this.notifyConfigUpdate();
+ }
+
+ protected onImageUrlUpdate(ev: OrInputChangedEvent) {
+ this.widgetConfig.imagePath = ev.detail.value;
+ this.notifyConfigUpdate();
+ }
+
+
+ /* -------------------------------------- */
+
+ // updates coordinate map according to the attributeRef entries per id
+ updateCoordinateMap(config: ImageWidgetConfig) {
+ for (let i = 0; i < config.attributeRefs.length; i++) {
+ const attributeRef = config.attributeRefs[i];
+ if (attributeRef === undefined) {
+ console.error('attributeRef is undefined');
+ return;
+ }
+ const index = config.markers.findIndex(m => m.attributeRef.id === attributeRef.id && m.attributeRef.name === attributeRef.name);
+ if (index === -1) {
+ config.markers.push({
+ attributeRef: attributeRef,
+ coordinates: [50, 50]
+ });
+ }
+ }
+ }
+
+ private draftCoordinateEntries(config: ImageWidgetConfig): TemplateResult[] {
+ const min = 0;
+ const max = 100;
+
+ if (config.markers.length > 0) {
+ return config.attributeRefs.map((attributeRef) => {
+ const marker = config.markers.find(m => m.attributeRef.id === attributeRef.id && m.attributeRef.name === attributeRef.name);
+ if(marker === undefined) {
+ console.error("A marker could not be found during drafting coordinate entries.");
+ return html``;
+ }
+ const index = config.markers.indexOf(marker);
+ const coordinates = marker.coordinates;
+ const asset = this.loadedAssets?.find(a => a.id === attributeRef.id);
+ let label: string | undefined;
+ if(asset) {
+ const attribute = asset.attributes![attributeRef.name!];
+ const descriptors = AssetModelUtil.getAttributeAndValueDescriptors(asset.type, attributeRef.name, attribute);
+ label = Util.getAttributeLabel(attribute, descriptors[0], asset.type, false);
+ }
+ return html`
+ <div id="marker-container">
+ <div style="flex: 1; display: flex; flex-direction: column;">
+ <span>${this.loadedAssets?.find(a => a.id === attributeRef.id)?.name}</span>
+ ${when(label, () => html`
+ <span style="color: gray;">${label}</span>
+ `)}
+ </div>
+ <div style="display: flex; gap: 8px;">
+ <or-mwc-input .disableSliderNumberInput="${true}" compact style="max-width: 64px;"
+ .type="${InputType.NUMBER}" .min="${min}" .max="${max}" .value="${coordinates[0]}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onCoordinateUpdate(index, 'x', ev.detail.value)}"
+ ></or-mwc-input>
+
+ <or-mwc-input .disableSliderNumberInput="${true}" compact style="max-width: 64px;"
+ .type="${InputType.NUMBER}" .min="${min}" .max="${max}" .value="${coordinates[1]}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onCoordinateUpdate(index, 'y', ev.detail.value)}"
+ ></or-mwc-input>
+ </div>
+ </div>
+ `;
+ });
+ } else {
+ return [
+ html`<span>${i18next.t('noAttributeConnected')}</span>`
+ ];
+ }
+ }
+
+ protected onCoordinateUpdate(index: number, coordinate: 'x' | 'y', value: number) {
+ let coords = this.widgetConfig.markers[index].coordinates;
+ if(!coords) {
+ coords = [0, 0];
+ }
+ if(coordinate === 'x') {
+ coords[0] = value;
+ } else if(coordinate === 'y') {
+ coords[1] = value;
+ }
+ this.widgetConfig.markers[index].coordinates = coords;
+ this.notifyConfigUpdate();
+ }
+
+}
diff --git a/ui/component/or-dashboard-builder/src/settings/kpi-settings.ts b/ui/component/or-dashboard-builder/src/settings/kpi-settings.ts
new file mode 100644
index 000000000..6eca69b8f
--- /dev/null
+++ b/ui/component/or-dashboard-builder/src/settings/kpi-settings.ts
@@ -0,0 +1,99 @@
+import {css, html, TemplateResult } from "lit";
+import { customElement } from "lit/decorators.js";
+import {AssetWidgetSettings} from "../util/or-asset-widget";
+import {i18next} from "@openremote/or-translate";
+import {KpiWidgetConfig} from "../widgets/kpi-widget";
+import {AttributesSelectEvent} from "../panels/attributes-panel";
+import {Attribute, AttributeRef} from "@openremote/model";
+import { InputType, OrInputChangedEvent } from "@openremote/or-mwc-components/or-mwc-input";
+
+const styling = css`
+ .switchMwcInputContainer {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ }
+`;
+
+@customElement("kpi-settings")
+export class KpiSettings extends AssetWidgetSettings {
+
+ protected widgetConfig!: KpiWidgetConfig;
+
+ static get styles() {
+ return [...super.styles, styling];
+ }
+
+ protected render(): TemplateResult {
+ const attributeFilter: (attr: Attribute<any>) => boolean = (attr): boolean => {
+ return ["positiveInteger", "positiveNumber", "number", "long", "integer", "bigInteger", "negativeInteger", "negativeNumber", "bigNumber", "integerByte", "direction"].includes(attr.type!)
+ };
+ return html`
+ <div>
+ <!-- Attribute selector -->
+ <settings-panel displayName="${i18next.t('attributes')}" expanded="${true}">
+ <attributes-panel .attributeRefs="${this.widgetConfig.attributeRefs}" onlyDataAttrs="${false}" .attributeFilter="${attributeFilter}" style="padding-bottom: 12px;"
+ @attribute-select="${(ev: AttributesSelectEvent) => this.onAttributesSelect(ev)}"
+ ></attributes-panel>
+ </settings-panel>
+
+ <!-- Display settings -->
+ <settings-panel displayName="${i18next.t('display')}" expanded="${true}">
+ <div style="display: flex; flex-direction: column; gap: 8px;">
+ <or-mwc-input .type="${InputType.SELECT}" style="width: 100%;"
+ .options="${['year', 'month', 'week', 'day', 'hour']}"
+ .value="${this.widgetConfig.period}" label="${i18next.t('timeframe')}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onTimeframeSelect(ev)}"
+ ></or-mwc-input>
+ <div class="switchMwcInputContainer">
+ <span>${i18next.t('dashboard.allowTimerangeSelect')}</span>
+ <or-mwc-input .type="${InputType.SWITCH}" style="margin: 0 -10px;" .value="${this.widgetConfig.showTimestampControls}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onTimeframeToggle(ev)}"
+ ></or-mwc-input>
+ </div>
+ </div>
+ </settings-panel>
+
+ <settings-panel displayName="${i18next.t('values')}" expanded="${true}">
+ <div style="display: flex; flex-direction: column; gap: 8px;">
+ <or-mwc-input .type="${InputType.SELECT}" style="width: 100%;" .options="${['absolute', 'percentage']}" .value="${this.widgetConfig.deltaFormat}"
+ label="${i18next.t('dashboard.showValueAs')}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onDeltaFormatSelect(ev)}"
+ ></or-mwc-input>
+ <or-mwc-input .type="${InputType.NUMBER}" style="width: 100%;" .value="${this.widgetConfig.decimals}" label="${i18next.t('decimals')}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onDecimalsChange(ev)}"
+ ></or-mwc-input>
+ </div>
+ </settings-panel>
+
+ <!-- -->
+ </div>
+ `;
+ }
+
+ protected onAttributesSelect(ev: AttributesSelectEvent) {
+ this.widgetConfig.attributeRefs = ev.detail as AttributeRef[];
+ this.notifyConfigUpdate();
+ }
+
+ protected onTimeframeSelect(ev: OrInputChangedEvent) {
+ this.widgetConfig.period = ev.detail.value;
+ this.notifyConfigUpdate();
+ }
+
+ protected onTimeframeToggle(ev: OrInputChangedEvent) {
+ this.widgetConfig.showTimestampControls = ev.detail.value;
+ this.notifyConfigUpdate();
+ }
+
+ protected onDeltaFormatSelect(ev: OrInputChangedEvent) {
+ this.widgetConfig.deltaFormat = ev.detail.value;
+ this.notifyConfigUpdate();
+ }
+
+ protected onDecimalsChange(ev: OrInputChangedEvent) {
+ this.widgetConfig.decimals = ev.detail.value;
+ this.notifyConfigUpdate();
+ }
+
+}
diff --git a/ui/component/or-dashboard-builder/src/settings/map-settings.ts b/ui/component/or-dashboard-builder/src/settings/map-settings.ts
new file mode 100644
index 000000000..d72050789
--- /dev/null
+++ b/ui/component/or-dashboard-builder/src/settings/map-settings.ts
@@ -0,0 +1,152 @@
+import {html, TemplateResult } from "lit";
+import { customElement } from "lit/decorators.js";
+import {AssetWidgetSettings} from "../util/or-asset-widget";
+import {i18next} from "@openremote/or-translate";
+import { InputType, OrInputChangedEvent } from "@openremote/or-mwc-components/or-mwc-input";
+import {MapWidgetConfig} from "../widgets/map-widget";
+import { LngLatLike } from "@openremote/or-map";
+import "../panels/assettypes-panel";
+import "../panels/thresholds-panel";
+import {LngLat} from "maplibre-gl"; // TODO: Replace this import
+import { when } from "lit/directives/when.js";
+import {AssetTypeSelectEvent, AttributeNameSelectEvent, ShowLabelsToggleEvent, ShowUnitsToggleEvent} from "../panels/assettypes-panel";
+import manager from "@openremote/core";
+import { showSnackbar } from "@openremote/or-mwc-components/or-mwc-snackbar";
+import {ThresholdChangeEvent} from "../panels/thresholds-panel";
+
+@customElement("map-settings")
+export class MapSettings extends AssetWidgetSettings {
+
+ protected widgetConfig!: MapWidgetConfig;
+
+ protected render(): TemplateResult {
+ const allowedValueTypes = ["boolean", "number", "positiveInteger", "positiveNumber", "negativeInteger", "negativeNumber", "text"];
+ return html`
+ <div>
+
+ <!-- Map settings -->
+ <settings-panel displayName="${i18next.t('configuration.mapSettings')}" expanded="${true}">
+ <div style="display: flex; flex-direction: column; gap: 8px;">
+ <div>
+ <or-mwc-input .type="${InputType.NUMBER}" style="width: 100%;"
+ .value="${this.widgetConfig.zoom}" label="${i18next.t('dashboard.zoom')}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onZoomUpdate(ev)}"
+ ></or-mwc-input>
+ </div>
+ <div style="display: flex; gap: 8px;">
+ <or-mwc-input .type="${InputType.TEXT}" style="width: 100%;"
+ .value="${this.widgetConfig.center ? (Object.values(this.widgetConfig.center))[0] + ', ' + (Object.values(this.widgetConfig.center))[1] : undefined}"
+ label="${i18next.t('dashboard.center')}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onCenterUpdate(ev)}"
+ ></or-mwc-input>
+ </div>
+ <div style="display: flex; justify-content: space-between; align-items: center;">
+ <span>${i18next.t('dashboard.showGeoJson')}</span>
+ <or-mwc-input .type="${InputType.SWITCH}" style="width: 70px;"
+ .value="${this.widgetConfig.showGeoJson}"
+ @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onGeoJsonToggle(ev)}"
+ ></or-mwc-input>
+ </div>
+ </div>
+ </settings-panel>
+
+ <!-- Panel where Asset type and the selected attribute can be customized -->
+ <settings-panel displayName="${i18next.t('attributes')}" expanded="${true}">
+ <assettypes-panel .assetType="${this.widgetConfig.assetType}" .attributeName="${this.widgetConfig.attributeName}"
+ .showLabels="${this.widgetConfig.showLabels}" .showUnits="${this.widgetConfig.showUnits}"
+ .valueTypes="${allowedValueTypes}"
+ @assettype-select="${(ev: AssetTypeSelectEvent) => this.onAssetTypeSelect(ev)}"
+ @attributename-select="${(ev: AttributeNameSelectEvent) => this.onAttributeNameSelect(ev)}"
+ @showlabels-toggle="${(ev: ShowLabelsToggleEvent) => this.onShowLabelsToggle(ev)}"
+ @showunits-toggle="${(ev: ShowUnitsToggleEvent) => this.onShowUnitsToggle(ev)}"
+ ></assettypes-panel>
+ </settings-panel>
+
+ <!-- List of customizable thresholds -->
+ ${when(this.widgetConfig.assetIds.length > 0, () => html`
+ <settings-panel displayName="${i18next.t('thresholds')}" expanded="${true}">
+ <thresholds-panel .thresholds="${this.widgetConfig.thresholds}" .valueType="${this.widgetConfig.valueType}" style="padding-bottom: 12px;"
+ .min="${this.widgetConfig.min}" .max="${this.widgetConfig.max}"
+ @threshold-change="${(ev: ThresholdChangeEvent) => this.onThresholdsChange(ev)}">
+ </thresholds-panel>
+ </settings-panel>
+ `)}
+ </div>
+ `;
+ }
+
+ protected onZoomUpdate(ev: OrInputChangedEvent) {
+ this.widgetConfig.zoom = ev.detail.value;
+ this.notifyConfigUpdate();
+ }
+
+ protected onCenterUpdate(ev: OrInputChangedEvent) {
+ if (ev.detail.value) {
+ const lngLatArr = (ev.detail.value as string).split(/[, ]/).filter(v => !!v);
+ if (lngLatArr.length === 2) {
+ const value = new LngLat(
+ Number.parseFloat(lngLatArr[0]),
+ Number.parseFloat(lngLatArr[1])
+ );
+ this.widgetConfig.center = value as LngLatLike;
+ this.notifyConfigUpdate();
+ }
+ }
+ }
+
+ protected onGeoJsonToggle(ev: OrInputChangedEvent) {
+ this.widgetConfig.showGeoJson = ev.detail.value;
+ this.notifyConfigUpdate();
+ }
+
+ protected onAssetTypeSelect(ev: AssetTypeSelectEvent) {
+ if (this.widgetConfig.assetType !== ev.detail) {
+ this.widgetConfig.attributeName = undefined;
+ this.widgetConfig.assetIds = [];
+ this.widgetConfig.showLabels = false;
+ this.widgetConfig.showUnits = false;
+ this.widgetConfig.boolColors = {type: 'boolean', 'false': '#ef5350', 'true': '#4caf50'};
+ this.widgetConfig.textColors = [['example', "#4caf50"], ['example2', "#ff9800"]];
+ this.widgetConfig.thresholds = [[0, "#4caf50"], [75, "#ff9800"], [90, "#ef5350"]];
+ this.widgetConfig.assetType = ev.detail;
+ this.notifyConfigUpdate();
+ }
+ }
+
+ protected async onAttributeNameSelect(ev: AttributeNameSelectEvent) {
+ this.widgetConfig.attributeName = ev.detail;
+ await manager.rest.api.AssetResource.queryAssets({
+ realm: {
+ name: manager.displayRealm
+ },
+ select: {
+ attributes: [ev.detail, 'location']
+ },
+ types: [this.widgetConfig.assetType!],
+ }).then(response => {
+ this.widgetConfig.assetIds = response.data.map((a) => a.id!);
+ this.widgetConfig.valueType = (response.data.length > 0) ? response.data[0].attributes![ev.detail].type : "text"; // sometimes no asset exists of that assetType, so using 'text' as fallback.
+ }).catch((reason) => {
+ console.error(reason);
+ showSnackbar(undefined, i18next.t('errorOccurred'));
+ });
+
+ this.notifyConfigUpdate()
+ }
+
+ protected onShowLabelsToggle(ev: ShowLabelsToggleEvent) {
+ this.widgetConfig.showLabels = ev.detail;
+ this.notifyConfigUpdate();
+ }
+
+ protected onShowUnitsToggle(ev: ShowUnitsToggleEvent) {
+ this.widgetConfig.showUnits = ev.detail;
+ this.notifyConfigUpdate();
+ }
+
+ protected onThresholdsChange(ev: ThresholdChangeEvent) {
+ this.widgetConfig.thresholds = ev.detail;
+ this.notifyConfigUpdate();
+ }
+
+}
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.ts
new file mode 100644
index 000000000..ec9da8300
--- /dev/null
+++ b/ui/component/or-dashboard-builder/src/util/or-asset-widget.ts
@@ -0,0 +1,89 @@
+import {OrWidget} from "./or-widget";
+import {Asset, Attribute, AttributeRef} from "@openremote/model";
+import { state } from "lit/decorators.js";
+import manager from "@openremote/core";
+import {i18next} from "@openremote/or-translate";
+import { showSnackbar } from "@openremote/or-mwc-components/or-mwc-snackbar";
+import {WidgetConfig} from "./widget-config";
+import {WidgetSettings} from "./widget-settings";
+import { CSSResult } from "lit";
+
+/*
+* OrAssetWidget class
+*
+* It is an extension on base class OrWidget,
+* where some asset-specific methods such as fetching, are already defined for ease of use.
+* For example it is used in the chart-, gauge- and kpi widget
+* */
+export abstract class OrAssetWidget extends OrWidget {
+
+ @state() // cached assets
+ protected loadedAssets: Asset[] = [];
+
+ @state() // cached attribute list; [asset index of the loadedAssets array, attribute]
+ protected assetAttributes: [number, Attribute<any>][] = [];
+
+ static get styles(): CSSResult[] {
+ return [...super.styles];
+ }
+
+ // Fetching the assets according to the AttributeRef[] input in DashboardWidget if required.
+ protected async fetchAssets(attributeRefs: AttributeRef[] = []) {
+ return fetchAssets(attributeRefs);
+ }
+
+ protected isAttributeRefLoaded(attributeRef: AttributeRef) {
+ return isAttributeRefLoaded(this.loadedAssets, attributeRef);
+ }
+
+}
+
+/*
+* AssetWidgetSettings class
+*
+* It is an extension on base class WidgetSettings
+* where some asset-specific methods such as fetching, are already defined for ease of use.
+* For example it is used in the chart-, gauge- and kpi widget settings
+* */
+export abstract class AssetWidgetSettings extends WidgetSettings {
+
+ @state() // cached assets
+ protected loadedAssets: Asset[] = [];
+
+ protected async fetchAssets(attributeRefs: AttributeRef[] = []) {
+ return fetchAssets(attributeRefs);
+ }
+
+ protected isAttributeRefLoaded(attributeRef: AttributeRef) {
+ return isAttributeRefLoaded(this.loadedAssets, attributeRef);
+ }
+
+}
+
+
+
+/* ---------------------------------------------------------- */
+
+// GENERIC FUNCTIONS
+
+// Simple async function for fetching assets by attributeRefs
+async function fetchAssets(attributeRefs: AttributeRef[] = []) {
+ let assets: Asset[] = [];
+ await manager.rest.api.AssetResource.queryAssets({
+ ids: attributeRefs?.map((x: AttributeRef) => x.id) as string[],
+ realm: { name: manager.displayRealm },
+ select: {
+ attributes: attributeRefs?.map((x: AttributeRef) => x.name) as string[]
+ }
+ }).then(response => {
+ assets = response.data;
+ }).catch((reason) => {
+ console.error(reason);
+ showSnackbar(undefined, i18next.t('errorOccurred'));
+ });
+ return assets;
+}
+
+function isAttributeRefLoaded(loadedAssets: Asset[] | undefined, attrRef: AttributeRef) {
+ return loadedAssets?.find((asset) => asset.id === attrRef.id) !== undefined;
+}
diff --git a/ui/component/or-dashboard-builder/src/util/or-widget.ts b/ui/component/or-dashboard-builder/src/util/or-widget.ts
new file mode 100644
index 000000000..a837ecfa9
--- /dev/null
+++ b/ui/component/or-dashboard-builder/src/util/or-widget.ts
@@ -0,0 +1,55 @@
+import {CSSResult, LitElement, TemplateResult } from "lit";
+import { property } from "lit/decorators.js";
+import {WidgetConfig} from "./widget-config";
+import {WidgetSettings} from "./widget-settings";
+
+export interface WidgetManifest {
+ displayName: string,
+ displayIcon: string,
+ minColumnWidth?: number,
+ minColumnHeight?: number,
+ minPixelWidth?: number,
+ minPixelHeight?: number
+ getContentHtml(config: WidgetConfig): OrWidget,
+ getSettingsHtml(config: WidgetConfig): WidgetSettings,
+ getDefaultConfig(): WidgetConfig
+}
+
+// Main OrWidget class where all widgets extend their functionality on.
+// It contains several methods used for rendering by the parent component; OrDashboardWidget
+export abstract class OrWidget extends LitElement {
+
+ protected static manifest: WidgetManifest;
+
+ @property({type: Object})
+ protected readonly widgetConfig!: WidgetConfig;
+
+ constructor(config: WidgetConfig) {
+ super();
+ this.widgetConfig = config;
+ }
+
+ static get styles(): CSSResult[] {
+ return [];
+ }
+
+ /* --------------------------- */
+
+ static getManifest(): WidgetManifest {
+ if (!this.manifest) {
+ throw new Error(`No manifest present on ${this.name}`);
+ }
+ return this.manifest;
+ }
+
+ // Method used for refreshing the content in a widget.
+ // This can be customized to lower the performance- and/or visual impact of a refresh.
+ public abstract refreshContent(force: boolean): void;
+
+ // WebComponent lifecycle method to render HTML content
+ protected abstract render(): TemplateResult;
+
+
+ /* ------------------------------------- */
+
+}
diff --git a/ui/component/or-dashboard-builder/src/util/settings-panel.ts b/ui/component/or-dashboard-builder/src/util/settings-panel.ts
new file mode 100644
index 000000000..612553477
--- /dev/null
+++ b/ui/component/or-dashboard-builder/src/util/settings-panel.ts
@@ -0,0 +1,93 @@
+import {css, html, LitElement, TemplateResult } from "lit";
+import { customElement, property } from "lit/decorators.js";
+import { until } from "lit/directives/until.js";
+import { when } from "lit/directives/when.js";
+import { classMap } from "lit/directives/class-map.js";
+import {style} from "../style";
+
+const styling = css`
+ :host {
+ height: auto !important;
+ }
+
+ #panel-wrapper {
+ border-top: 1px solid #E0E0E0;
+ border-bottom: 1px solid #E0E0E0;
+ }
+
+ #panel-header {
+ display: flex;
+ align-items: center;
+ cursor: pointer;
+ padding: 12px;
+ gap: 8px;
+ }
+
+ #panel-title {
+ line-height: 100%;
+ font-weight: 700;
+ }
+
+ .panel-content {
+ padding: 0 16px;
+ max-height: 0;
+ overflow: hidden;
+ transition: max-height 0.2s cubic-bezier(0.4, 0.0, 0.2, 1) 0s, visibility 0s 0.2s; /* expanded -> collapsed */
+ }
+
+ .panel-content--expanded {
+ max-height: 100vh;
+ overflow: visible;
+ transition: max-height 0.25s cubic-bezier(0.4, 0.0, 0.2, 1) 0s; /* collapsed -> expanded */
+ }
+`;
+
+@customElement("settings-panel")
+export class SettingsPanel extends LitElement {
+
+ @property()
+ protected expanded: boolean = false;
+
+ @property()
+ protected displayName?: string;
+
+ static get styles() {
+ return [styling, style]
+ }
+
+ protected render(): TemplateResult {
+ const contentClasses = {
+ "panel-content": true,
+ "panel-content--expanded": this.expanded
+ }
+ return html`
+ <div id="panel-wrapper">
+ ${until(this.generateHeader(this.expanded, this.displayName), html``)}
+ <div class="${classMap(contentClasses)}">
+ <div style="padding-bottom: 16px;">
+ <slot></slot>
+ </div>
+ </div>
+ </div>
+ `;
+ }
+
+ public toggle(state?: boolean) {
+ this.expanded = state || !this.expanded
+ }
+
+ protected async generateHeader(expanded: boolean, title?: string): Promise<TemplateResult> {
+ return html`
+ <div id="panel-header" @click="${() => this.toggle()}">
+ <div id="panel-chevron">
+ <or-icon icon="${expanded ? 'chevron-down' : 'chevron-right'}"></or-icon>
+ </div>
+ ${when(title, () => html`
+ <div id="panel-title">
+ <span>${this.displayName}</span>
+ </div>
+ `)}
+ </div>
+ `
+ }
+}
diff --git a/ui/component/or-dashboard-builder/src/util/widget-config.ts b/ui/component/or-dashboard-builder/src/util/widget-config.ts
new file mode 100644
index 000000000..0217f2127
--- /dev/null
+++ b/ui/component/or-dashboard-builder/src/util/widget-config.ts
@@ -0,0 +1,2 @@
+export interface WidgetConfig {
+}
diff --git a/ui/component/or-dashboard-builder/src/util/widget-settings.ts b/ui/component/or-dashboard-builder/src/util/widget-settings.ts
new file mode 100644
index 000000000..c7fd85f22
--- /dev/null
+++ b/ui/component/or-dashboard-builder/src/util/widget-settings.ts
@@ -0,0 +1,47 @@
+import {LitElement, PropertyValues, TemplateResult } from "lit";
+import { property } from "lit/decorators.js";
+import {WidgetConfig} from "./widget-config";
+import {style} from "../style";
+
+export class WidgetSettingsChangedEvent extends CustomEvent<WidgetConfig> {
+
+ public static readonly NAME = "settings-changed";
+
+ constructor(widgetConfig: WidgetConfig) {
+ super(WidgetSettingsChangedEvent.NAME, {
+ bubbles: true,
+ composed: true,
+ detail: widgetConfig
+ });
+ }
+
+}
+
+export abstract class WidgetSettings extends LitElement {
+
+ @property()
+ protected readonly widgetConfig: WidgetConfig;
+
+ static get styles() {
+ return [style];
+ }
+
+ protected abstract render(): TemplateResult
+
+ constructor(config: WidgetConfig) {
+ super();
+ this.widgetConfig = config;
+ }
+
+
+ // Lit lifecycle for "on every update" which triggers on every property/state change
+ protected willUpdate(changedProps: PropertyValues) {
+ if(changedProps.has('widgetConfig') && this.widgetConfig) {
+ this.dispatchEvent(new WidgetSettingsChangedEvent(this.widgetConfig));
+ }
+ }
+
+ protected notifyConfigUpdate() {
+ this.requestUpdate('widgetConfig');
+ }
+}
diff --git a/ui/component/or-dashboard-builder/src/widgets/chart-widget.ts b/ui/component/or-dashboard-builder/src/widgets/chart-widget.ts
new file mode 100644
index 000000000..afe23dc84
--- /dev/null
+++ b/ui/component/or-dashboard-builder/src/widgets/chart-widget.ts
@@ -0,0 +1,199 @@
+import {AssetDatapointLTTBQuery, AssetDatapointQueryUnion, Attribute, AttributeRef} from "@openremote/model";
+import {html, PropertyValues, TemplateResult } from "lit";
+import { when } from "lit/directives/when.js";
+import {i18next} from "@openremote/or-translate";
+import {TimePresetCallback} from "@openremote/or-chart";
+import moment from "moment";
+import {OrAssetWidget} from "../util/or-asset-widget";
+import { customElement, state } from "lit/decorators.js";
+import {WidgetConfig} from "../util/widget-config";
+import {OrWidget, WidgetManifest} from "../util/or-widget";
+import {ChartSettings} from "../settings/chart-settings";
+import {WidgetSettings} from "../util/widget-settings";
+
+export interface ChartWidgetConfig extends WidgetConfig {
+ attributeRefs: AttributeRef[];
+ datapointQuery: AssetDatapointQueryUnion;
+ chartOptions?: any; // ChartConfiguration<"line", ScatterDataPoint[]>
+ showTimestampControls: boolean;
+ defaultTimePresetKey: string;
+ showLegend: boolean;
+}
+
+function getDefaultTimePresetOptions(): Map<string, TimePresetCallback> {
+ return new Map<string, TimePresetCallback>([
+ ["lastHour", (date: Date) => [moment(date).subtract(1, 'hour').toDate(), date]],
+ ["last24Hours", (date: Date) => [moment(date).subtract(24, 'hours').toDate(), date]],
+ ["last7Days", (date: Date) => [moment(date).subtract(7, 'days').toDate(), date]],
+ ["last30Days", (date: Date) => [moment(date).subtract(30, 'days').toDate(), date]],
+ ["last90Days", (date: Date) => [moment(date).subtract(90, 'days').toDate(), date]],
+ ["last6Months", (date: Date) => [moment(date).subtract(6, 'months').toDate(), date]],
+ ["lastYear", (date: Date) => [moment(date).subtract(1, 'year').toDate(), date]],
+ ["thisHour", (date: Date) => [moment(date).startOf('hour').toDate(), moment(date).endOf('hour').toDate()]],
+ ["thisDay", (date: Date) => [moment(date).startOf('day').toDate(), moment(date).endOf('day').toDate()]],
+ ["thisWeek", (date: Date) => [moment(date).startOf('isoWeek').toDate(), moment(date).endOf('isoWeek').toDate()]],
+ ["thisMonth", (date: Date) => [moment(date).startOf('month').toDate(), moment(date).endOf('month').toDate()]],
+ ["thisYear", (date: Date) => [moment(date).startOf('year').toDate(), moment(date).endOf('year').toDate()]],
+ ["yesterday", (date: Date) => [moment(date).subtract(24, 'hours').startOf('day').toDate(), moment(date).subtract(24, 'hours').endOf('day').toDate()]],
+ ["thisDayLastWeek", (date: Date) => [moment(date).subtract(1, 'week').startOf('day').toDate(), moment(date).subtract(1, 'week').endOf('day').toDate()]],
+ ["previousWeek", (date: Date) => [moment(date).subtract(1, 'week').startOf('isoWeek').toDate(), moment(date).subtract(1, 'week').endOf('isoWeek').toDate()]],
+ ["previousMonth", (date: Date) => [moment(date).subtract(1, 'month').startOf('month').toDate(), moment(date).subtract(1, 'month').endOf('month').toDate()]],
+ ["previousYear", (date: Date) => [moment(date).subtract(1, 'year').startOf('year').toDate(), moment(date).subtract(1, 'year').endOf('year').toDate()]]
+ ]);
+}
+
+function getDefaultSamplingOptions(): Map<string, string> {
+ return new Map<string, string>([["lttb", 'lttb'], ["withInterval", 'interval']]);
+}
+
+function getDefaultWidgetConfig(): ChartWidgetConfig {
+ const preset = "last24Hours"
+ const dateFunc = getDefaultTimePresetOptions().get(preset) as TimePresetCallback;
+ const dates = dateFunc(new Date());
+ return {
+ attributeRefs: [],
+ datapointQuery: {
+ type: "lttb",
+ fromTimestamp: dates[0].getTime(),
+ toTimestamp: dates[1].getTime(),
+ amountOfPoints: 100
+ },
+ chartOptions: {
+ options: {
+ scales: {
+ y: {
+ min: undefined,
+ max: undefined
+ }
+ }
+ },
+ },
+ showTimestampControls: false,
+ defaultTimePresetKey: preset,
+ showLegend: true
+ };
+}
+
+/* --------------------------------------------------- */
+
+@customElement('chart-widget')
+export class ChartWidget extends OrAssetWidget {
+
+ @state()
+ protected datapointQuery!: AssetDatapointQueryUnion;
+
+ // Override of widgetConfig with extended type
+ protected widgetConfig!: ChartWidgetConfig;
+
+ static getManifest(): WidgetManifest {
+ return {
+ displayName: "Line Chart",
+ displayIcon: "chart-line",
+ minColumnWidth: 2,
+ minColumnHeight: 2,
+ getContentHtml(config: ChartWidgetConfig): OrWidget {
+ return new ChartWidget(config);
+ },
+ getSettingsHtml(config: ChartWidgetConfig): WidgetSettings {
+ const settings = new ChartSettings(config);
+ settings.setTimePresetOptions(getDefaultTimePresetOptions());
+ settings.setSamplingOptions(getDefaultSamplingOptions());
+ return settings;
+ },
+ getDefaultConfig(): ChartWidgetConfig {
+ return getDefaultWidgetConfig();
+ }
+ }
+ }
+
+ // Method called on every refresh/reload of the widget
+ // We either refresh the datapointQuery or the full widgetConfig depending on the force parameter.
+ // TODO: Improve this to a more efficient approach, instead of duplicating the object
+ public refreshContent(force: boolean) {
+ if(!force) {
+ const datapointQuery = JSON.parse(JSON.stringify(this.widgetConfig.datapointQuery)) as AssetDatapointQueryUnion;
+ datapointQuery.fromTimestamp = undefined;
+ datapointQuery.toTimestamp = undefined;
+ this.datapointQuery = datapointQuery;
+ } else {
+ this.widgetConfig = JSON.parse(JSON.stringify(this.widgetConfig)) as ChartWidgetConfig;
+ }
+ }
+
+
+ /* ---------------------------------- */
+
+ // WebComponent lifecycle method, that occurs DURING every state update
+ protected willUpdate(changedProps: PropertyValues) {
+
+ // Add datapointQuery if not set yet (due to migration)
+ if(!this.widgetConfig.datapointQuery) {
+ this.widgetConfig.datapointQuery = this.getDefaultQuery();
+ if(!changedProps.has("widgetConfig")) {
+ changedProps.set("widgetConfig", this.widgetConfig);
+ }
+ }
+
+ if(changedProps.has('widgetConfig') && this.widgetConfig) {
+ this.datapointQuery = this.widgetConfig.datapointQuery;
+ }
+
+ return super.willUpdate(changedProps);
+ }
+
+ // WebComponent lifecycle method, that occurs AFTER every state update
+ protected updated(changedProps: Map<string, any>) {
+ super.updated(changedProps);
+
+ // If widgetConfig, and the attributeRefs of them have changed...
+ if(changedProps.has("widgetConfig") && this.widgetConfig) {
+ const attributeRefs = this.widgetConfig.attributeRefs;
+ const missingAssets = attributeRefs?.filter((attrRef: AttributeRef) => !this.isAttributeRefLoaded(attrRef));
+ if (missingAssets.length > 0) {
+
+ // Fetch the new list of assets
+ this.fetchAssets(attributeRefs).then((assets) => {
+ this.loadedAssets = assets;
+ this.assetAttributes = attributeRefs?.map((attrRef: AttributeRef) => {
+ const assetIndex = assets.findIndex((asset) => asset.id === attrRef.id);
+ 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>][];
+ });
+
+ }
+ }
+ return super.updated(changedProps);
+ }
+
+ protected render(): TemplateResult {
+ return html`
+ ${when(this.loadedAssets && this.assetAttributes && this.loadedAssets.length > 0 && this.assetAttributes.length > 0, () => {
+ return html`
+ <or-chart .assets="${this.loadedAssets}" .assetAttributes="${this.assetAttributes}"
+ .showLegend="${(this.widgetConfig?.showLegend != null) ? this.widgetConfig?.showLegend : true}"
+ .attributeControls="${false}" .timestampControls="${!this.widgetConfig?.showTimestampControls}"
+ .timePresetOptions="${getDefaultTimePresetOptions()}" .timePresetKey="${this.widgetConfig?.defaultTimePresetKey}"
+ .datapointQuery="${this.datapointQuery}" .chartOptions="${this.widgetConfig?.chartOptions}"
+ style="height: 100%"
+ ></or-chart>
+ `;
+ }, () => {
+ return html`
+ <div style="height: 100%; display: flex; justify-content: center; align-items: center;">
+ <span>${i18next.t('noAttributesConnected')}</span>
+ </div>
+ `
+ })}
+ `;
+ }
+
+ protected getDefaultQuery(): AssetDatapointLTTBQuery {
+ return {
+ type: "lttb",
+ fromTimestamp: moment().set('minute', -60).toDate().getTime(),
+ toTimestamp: moment().set('minute', 60).toDate().getTime(),
+ amountOfPoints: 100
+ }
+ }
+}
diff --git a/ui/component/or-dashboard-builder/src/widgets/gauge-widget.ts b/ui/component/or-dashboard-builder/src/widgets/gauge-widget.ts
new file mode 100644
index 000000000..9b5d83f24
--- /dev/null
+++ b/ui/component/or-dashboard-builder/src/widgets/gauge-widget.ts
@@ -0,0 +1,112 @@
+import {html, TemplateResult} from "lit";
+import {customElement, state} from "lit/decorators.js";
+import {OrAssetWidget} from "../util/or-asset-widget";
+import {WidgetConfig} from "../util/widget-config";
+import {Asset, Attribute, AttributeRef} from "@openremote/model";
+import {OrWidget, WidgetManifest} from "../util/or-widget";
+import {WidgetSettings} from "../util/widget-settings";
+import {GaugeSettings} from "../settings/gauge-settings";
+import {when} from "lit/directives/when.js";
+import {i18next} from "@openremote/or-translate";
+import "@openremote/or-gauge";
+
+export interface GaugeWidgetConfig extends WidgetConfig {
+ attributeRefs: AttributeRef[];
+ thresholds: [number, string][];
+ decimals: number;
+ min: number;
+ max: number;
+ valueType: string;
+}
+
+function getDefaultWidgetConfig(): GaugeWidgetConfig {
+ return {
+ attributeRefs: [],
+ 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,
+ valueType: 'number',
+ };
+}
+
+@customElement("gauge-widget")
+export class GaugeWidget extends OrAssetWidget {
+
+ // Override of widgetConfig with extended type
+ protected widgetConfig!: GaugeWidgetConfig;
+
+ static getManifest(): WidgetManifest {
+ return {
+ displayName: "Gauge",
+ displayIcon: "gauge",
+ minColumnWidth: 1,
+ minColumnHeight: 1,
+ getContentHtml(config: GaugeWidgetConfig): OrWidget {
+ return new GaugeWidget(config);
+ },
+ getSettingsHtml(config: GaugeWidgetConfig): WidgetSettings {
+ return new GaugeSettings(config);
+ },
+ getDefaultConfig(): GaugeWidgetConfig {
+ return getDefaultWidgetConfig();
+ }
+ }
+ }
+
+ public refreshContent(force: boolean) {
+ this.loadAssets(this.widgetConfig.attributeRefs);
+ }
+
+ // WebComponent lifecycle method, that occurs AFTER every state update
+ protected updated(changedProps: Map<string, any>) {
+ super.updated(changedProps);
+
+ // If widgetConfig, and the attributeRefs of them have changed...
+ if(changedProps.has("widgetConfig") && this.widgetConfig) {
+ const attributeRefs = this.widgetConfig.attributeRefs;
+
+ // Check if list of attributes has changed, based on the cached assets
+ const loadedRefs: AttributeRef[] = attributeRefs?.filter((attrRef: AttributeRef) => this.isAttributeRefLoaded(attrRef));
+ if (loadedRefs?.length !== (attributeRefs ? attributeRefs.length : 0)) {
+
+ // Fetch the new list of assets
+ this.loadAssets(attributeRefs);
+
+ }
+ }
+ return super.updated(changedProps);
+ }
+
+ protected loadAssets(attributeRefs: AttributeRef[]) {
+ this.fetchAssets(attributeRefs).then((assets) => {
+ this.loadedAssets = assets;
+ this.assetAttributes = attributeRefs?.map((attrRef: AttributeRef) => {
+ const assetIndex = assets.findIndex((asset) => asset.id === attrRef.id);
+ 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>][];
+ });
+ }
+
+
+ protected render(): TemplateResult {
+ return html`
+ ${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}"
+ .decimals="${this.widgetConfig.decimals}" .min="${this.widgetConfig.min}" .max="${this.widgetConfig.max}"
+ style="height: 100%; overflow: hidden;">
+ </or-gauge>
+ `;
+ }, () => {
+ return html`
+ <div style="height: 100%; display: flex; justify-content: center; align-items: center;">
+ <span>${i18next.t('noAttributeConnected')}</span>
+ </div>
+ `
+ })}
+ `;
+ }
+
+}
diff --git a/ui/component/or-dashboard-builder/src/widgets/image-widget.ts b/ui/component/or-dashboard-builder/src/widgets/image-widget.ts
new file mode 100644
index 000000000..e51362bbc
--- /dev/null
+++ b/ui/component/or-dashboard-builder/src/widgets/image-widget.ts
@@ -0,0 +1,181 @@
+import {WidgetConfig} from "../util/widget-config";
+import {AssetModelUtil, Attribute, AttributeRef, WellknownValueTypes} from "@openremote/model";
+import {OrWidget, WidgetManifest} from "../util/or-widget";
+import { customElement } from "lit/decorators.js";
+import {WidgetSettings} from "../util/widget-settings";
+import {css, CSSResult, html, PropertyValues, TemplateResult, unsafeCSS } from "lit";
+import {OrAssetWidget} from "../util/or-asset-widget";
+import {ImageSettings} from "../settings/image-settings";
+import { when } from "lit/directives/when.js";
+import {i18next} from "@openremote/or-translate";
+import {DefaultColor2, DefaultColor3, Util} from "@openremote/core";
+import { styleMap } from "lit/directives/style-map.js";
+
+const styling = css`
+ #img-wrapper {
+ height: 100%;
+ width: 100%;
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ overflow: hidden;
+ z-index: 1;
+ }
+
+ #img-container {
+ position: relative;
+ max-height: 100%;
+ }
+
+ #img-content {
+ height: 100%;
+ max-height: 100%;
+ max-width: 100%;
+ }
+
+ #overlay {
+ position: absolute;
+ z-index: 3;
+
+ /* additional marker styling */
+ color: var(--or-app-color2, ${unsafeCSS(DefaultColor2)});
+ background-color: var(--or-app-color3, ${unsafeCSS(DefaultColor3)});
+ border-radius: 15px;
+ padding: 3px 8px 5px 8px;
+ object-fit: contain;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+`;
+
+export interface ImageAssetMarker {
+ attributeRef: AttributeRef,
+ coordinates: [number, number]
+}
+
+export interface ImageWidgetConfig extends WidgetConfig {
+ attributeRefs: AttributeRef[];
+ markers: ImageAssetMarker[];
+ showTimestampControls: boolean;
+ imagePath: string;
+}
+
+function getDefaultWidgetConfig(): ImageWidgetConfig {
+ return {
+ attributeRefs: [],
+ showTimestampControls: false,
+ imagePath: '',
+ markers: [],
+ };
+}
+
+@customElement("image-widget")
+export class ImageWidget extends OrAssetWidget {
+
+ // Override of widgetConfig with extended type
+ protected readonly widgetConfig!: ImageWidgetConfig;
+
+ static getManifest(): WidgetManifest {
+ return {
+ displayName: "Image",
+ displayIcon: "file-image-marker",
+ minColumnWidth: 1,
+ minColumnHeight: 1,
+ getContentHtml(config: ImageWidgetConfig): OrWidget {
+ return new ImageWidget(config);
+ },
+ getSettingsHtml(config: ImageWidgetConfig): WidgetSettings {
+ return new ImageSettings(config);
+ },
+ getDefaultConfig(): ImageWidgetConfig {
+ return getDefaultWidgetConfig();
+ }
+ }
+ }
+
+ public refreshContent(force: boolean) {
+ this.loadAssets();
+ }
+
+ static get styles(): CSSResult[] {
+ return [...super.styles, styling];
+ }
+
+ updated(changedProps: PropertyValues) {
+
+ if(changedProps.has('widgetConfig') && this.widgetConfig) {
+ const attributeRefs = this.widgetConfig.attributeRefs;
+ const missingAssets = attributeRefs?.filter((attrRef: AttributeRef) => !this.isAttributeRefLoaded(attrRef));
+ if (missingAssets.length > 0) {
+ this.loadAssets();
+ }
+ }
+ }
+
+ protected loadAssets() {
+ this.fetchAssets(this.widgetConfig.attributeRefs).then(assets => {
+ this.loadedAssets = assets!;
+ this.assetAttributes = this.widgetConfig.attributeRefs.map((attrRef: AttributeRef) => {
+ const assetIndex = assets!.findIndex(asset => asset.id === attrRef.id);
+ 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>][];
+ });
+ }
+
+ // method to render and update the markers on the image
+ protected handleMarkerPlacement(config: ImageWidgetConfig) {
+ if (this.assetAttributes.length && config.attributeRefs.length > 0) {
+
+ if(config.markers.length === 0) {
+ console.error("No markers found!");
+ return [];
+ }
+ return config.attributeRefs.map((attributeRef, index) => {
+ const marker = config.markers.find(m => m.attributeRef.id === attributeRef.id && m.attributeRef.name === attributeRef.name);
+ const asset = this.loadedAssets.find(a => a.id === attributeRef.id);
+ let value: string | undefined;
+ const styles: any = {
+ "left": `${marker!.coordinates[0]}%`,
+ "top": `${marker!.coordinates[1]}%`
+ };
+ if(asset) {
+ const attribute = asset.attributes![attributeRef.name!];
+ const descriptors = AssetModelUtil.getAttributeAndValueDescriptors(asset.type, attributeRef.name, attribute);
+ value = Util.getAttributeValueAsString(attribute, descriptors[0], asset.type, true, "-");
+ if(attribute?.type === WellknownValueTypes.COLOURRGB && value !== "-") {
+ styles.backgroundColor = value;
+ styles.minHeight = "21px";
+ styles.minWidth = "13px";
+ value = undefined;
+ }
+ }
+ return html`
+ <span id="overlay" style="${styleMap(styles)}">
+ ${value}
+ </span>
+ `;
+ });
+ }
+ }
+
+ protected render(): TemplateResult {
+ const imagePath = this.widgetConfig.imagePath;
+ return html`
+ <div id="img-wrapper">
+ ${when(imagePath, () => html`
+ <div id="img-container">
+ <img id="img-content" src="${imagePath}" alt=""/>
+ <div>
+ ${this.handleMarkerPlacement(this.widgetConfig)}
+ </div>
+ </div>
+ `, () => html`
+ <span>${i18next.t('dashboard.noImageSelected')}</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.ts
new file mode 100644
index 000000000..fc8e90ae9
--- /dev/null
+++ b/ui/component/or-dashboard-builder/src/widgets/kpi-widget.ts
@@ -0,0 +1,94 @@
+import { customElement } 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 {WidgetConfig} from "../util/widget-config";
+import {Attribute, AttributeRef} from "@openremote/model";
+import {html, TemplateResult } from "lit";
+import {KpiSettings} from "../settings/kpi-settings";
+
+export interface KpiWidgetConfig extends WidgetConfig {
+ attributeRefs: AttributeRef[];
+ period?: 'year' | 'month' | 'week' | 'day' | 'hour';
+ decimals: number;
+ deltaFormat: "absolute" | "percentage";
+ showTimestampControls: boolean;
+}
+
+function getDefaultWidgetConfig(): KpiWidgetConfig {
+ return {
+ attributeRefs: [],
+ period: "day",
+ decimals: 0,
+ deltaFormat: "absolute",
+ showTimestampControls: false
+ };
+}
+
+@customElement("kpi-widget")
+export class KpiWidget extends OrAssetWidget {
+
+ protected widgetConfig!: KpiWidgetConfig;
+
+ static getManifest(): WidgetManifest {
+ return {
+ displayName: "KPI",
+ displayIcon: "label",
+ minColumnWidth: 1,
+ minColumnHeight: 1,
+ getContentHtml(config: KpiWidgetConfig): OrWidget {
+ return new KpiWidget(config);
+ },
+ getSettingsHtml(config: KpiWidgetConfig): WidgetSettings {
+ return new KpiSettings(config);
+ },
+ getDefaultConfig(): KpiWidgetConfig {
+ return getDefaultWidgetConfig();
+ }
+ }
+ }
+
+ refreshContent(force: boolean): void {
+ this.loadAssets(this.widgetConfig.attributeRefs);
+ }
+
+ protected updated(changedProps: Map<string, any>) {
+ super.updated(changedProps);
+
+ // If widgetConfig, and the attributeRefs of them have changed...
+ if(changedProps.has("widgetConfig") && this.widgetConfig) {
+ const attributeRefs = this.widgetConfig.attributeRefs;
+
+ // Check if list of attributes has changed, based on the cached assets
+ const loadedRefs: AttributeRef[] = attributeRefs?.filter((attrRef: AttributeRef) => this.isAttributeRefLoaded(attrRef));
+ if (loadedRefs?.length !== (attributeRefs ? attributeRefs.length : 0)) {
+
+ // Fetch the new list of assets
+ this.loadAssets(attributeRefs);
+
+ }
+ }
+ return super.updated(changedProps);
+ }
+
+ protected loadAssets(attributeRefs: AttributeRef[]) {
+ this.fetchAssets(attributeRefs).then((assets) => {
+ this.loadedAssets = assets;
+ this.assetAttributes = attributeRefs?.map((attrRef: AttributeRef) => {
+ const assetIndex = assets.findIndex((asset) => asset.id === attrRef.id);
+ 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>][];
+ });
+ }
+
+ protected render(): TemplateResult {
+ return html`
+ <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%;">
+ </or-attribute-card>
+ `;
+ }
+
+}
diff --git a/ui/component/or-dashboard-builder/src/widgets/map-widget.ts b/ui/component/or-dashboard-builder/src/widgets/map-widget.ts
new file mode 100644
index 000000000..22e35ae95
--- /dev/null
+++ b/ui/component/or-dashboard-builder/src/widgets/map-widget.ts
@@ -0,0 +1,188 @@
+import {html, PropertyValues, TemplateResult} from "lit";
+import {customElement} 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 {WidgetConfig} from "../util/widget-config";
+import {Asset, AssetDescriptor, Attribute, AttributeRef, 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 {i18next} from "@openremote/or-translate";
+import { showSnackbar } from "@openremote/or-mwc-components/or-mwc-snackbar";
+import "@openremote/or-map";
+
+export interface MapWidgetConfig extends WidgetConfig {
+ // General values
+ attributeRefs: AttributeRef[];
+ // Map related values
+ zoom?: number,
+ center?: LngLatLike,
+ lat?: number,
+ lng?: number,
+ // Map marker related values
+ showLabels: boolean,
+ showUnits: boolean,
+ showGeoJson: 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[],
+ assetIds: string[],
+ attributes: string[],
+}
+
+function getDefaultWidgetConfig(): MapWidgetConfig {
+ return {
+ attributeRefs: [],
+ showLabels: false,
+ showUnits: false,
+ showGeoJson: true,
+ boolColors: {type: 'boolean', 'false': '#ef5350', 'true': '#4caf50'},
+ textColors: [['example', '4caf50'], ['example2', 'ef5350']],
+ thresholds: [[0, "#4caf50"], [75, "#ff9800"], [90, "#ef5350"]],
+ assetTypes: [],
+ assetType: undefined,
+ assetIds: [],
+ attributes: [],
+ } as MapWidgetConfig;
+}
+
+@customElement("map-widget")
+export class MapWidget extends OrAssetWidget {
+
+ protected widgetConfig!: MapWidgetConfig
+
+ private markers: MapMarkerAssetConfig = {};
+
+ static getManifest(): WidgetManifest {
+ return {
+ displayName: "Map",
+ displayIcon: "map",
+ minColumnWidth: 2,
+ minColumnHeight: 2,
+ getContentHtml(config: MapWidgetConfig): OrWidget {
+ return new MapWidget(config);
+ },
+ getSettingsHtml(config: MapWidgetConfig): WidgetSettings {
+ return new MapSettings(config);
+ },
+ getDefaultConfig(): MapWidgetConfig {
+ return getDefaultWidgetConfig();
+ }
+ }
+ }
+
+ refreshContent(force: boolean): void {
+ this.loadAssets();
+ }
+
+ protected updated(changedProps: PropertyValues) {
+ if(changedProps.has('widgetConfig') && this.widgetConfig) {
+ this.loadAssets();
+ }
+ }
+
+ protected async loadAssets() {
+ if(this.widgetConfig.assetType && this.widgetConfig.attributeName) {
+ this.fetchAssetsByType([this.widgetConfig.assetType], this.widgetConfig.attributeName).then((assets) => {
+ this.loadedAssets = 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) => {
+ console.error(reason);
+ showSnackbar(undefined, i18next.t('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();
+ })}
+ </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
+ };
+ this.markers[asset.type!].colours = colorsNum;
+ }
+ }
+ return html`
+ <or-map-marker-asset .asset="${asset}" .config="${this.markers}"></or-map-marker-asset>
+ `
+ })
+ }
+
+
+}
diff --git a/ui/component/or-dashboard-builder/src/widgets/or-base-widget.ts b/ui/component/or-dashboard-builder/src/widgets/or-base-widget.ts
deleted file mode 100644
index 3e2520b59..000000000
--- a/ui/component/or-dashboard-builder/src/widgets/or-base-widget.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import {DashboardWidget} from "@openremote/model";
-import {TemplateResult} from "lit";
-
-export interface OrWidgetConfig {
-
-}
-
-export interface OrWidgetEntity {
- DISPLAY_NAME: string,
- DISPLAY_MDI_ICON: string; // https://materialdesignicons.com;
- MIN_COLUMN_WIDTH: number;
- MIN_PIXEL_WIDTH: number;
- MIN_PIXEL_HEIGHT: number;
-
- getDefaultConfig: (widget: DashboardWidget) => OrWidgetConfig;
- verifyConfigSpec: (widget: DashboardWidget) => OrWidgetConfig;
-
- getWidgetHTML: (widget: DashboardWidget, editMode: boolean, realm: string) => TemplateResult;
- getSettingsHTML: (widget: DashboardWidget, realm: string) => TemplateResult;
-}
diff --git a/ui/component/or-dashboard-builder/src/widgets/or-chart-widget.ts b/ui/component/or-dashboard-builder/src/widgets/or-chart-widget.ts
deleted file mode 100644
index 37d769bac..000000000
--- a/ui/component/or-dashboard-builder/src/widgets/or-chart-widget.ts
+++ /dev/null
@@ -1,482 +0,0 @@
-import {Asset, AssetDatapointIntervalQuery, AssetDatapointIntervalQueryFormula, AssetDatapointLTTBQuery, AssetDatapointQueryUnion, Attribute, AttributeRef, DashboardWidget} 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} from "lit/decorators.js";
-import {when} from "lit/directives/when.js";
-import {choose} from 'lit/directives/choose.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 moment from "moment";
-import {TimePresetCallback} from "@openremote/or-chart";
-
-export interface ChartWidgetConfig extends OrWidgetConfig {
- displayName: string;
- attributeRefs: AttributeRef[];
- datapointQuery: AssetDatapointQueryUnion;
- chartOptions?: any; // ChartConfiguration<"line", ScatterDataPoint[]>
- showTimestampControls: boolean;
- defaultTimePresetKey: string;
- showLegend: boolean;
-}
-
-const timePresetOptions = new Map<string, TimePresetCallback>([
- ["lastHour", (date: Date) => [moment(date).subtract(1, 'hour').toDate(), date]],
- ["last24Hours", (date: Date) => [moment(date).subtract(24, 'hours').toDate(), date]],
- ["last7Days", (date: Date) => [moment(date).subtract(7, 'days').toDate(), date]],
- ["last30Days", (date: Date) => [moment(date).subtract(30, 'days').toDate(), date]],
- ["last90Days", (date: Date) => [moment(date).subtract(90, 'days').toDate(), date]],
- ["last6Months", (date: Date) => [moment(date).subtract(6, 'months').toDate(), date]],
- ["lastYear", (date: Date) => [moment(date).subtract(1, 'year').toDate(), date]],
- ["thisHour", (date: Date) => [moment(date).startOf('hour').toDate(), moment(date).endOf('hour').toDate()]],
- ["thisDay", (date: Date) => [moment(date).startOf('day').toDate(), moment(date).endOf('day').toDate()]],
- ["thisWeek", (date: Date) => [moment(date).startOf('isoWeek').toDate(), moment(date).endOf('isoWeek').toDate()]],
- ["thisMonth", (date: Date) => [moment(date).startOf('month').toDate(), moment(date).endOf('month').toDate()]],
- ["thisYear", (date: Date) => [moment(date).startOf('year').toDate(), moment(date).endOf('year').toDate()]],
- ["yesterday", (date: Date) => [moment(date).subtract(24, 'hours').startOf('day').toDate(), moment(date).subtract(24, 'hours').endOf('day').toDate()]],
- ["thisDayLastWeek", (date: Date) => [moment(date).subtract(1, 'week').startOf('day').toDate(), moment(date).subtract(1, 'week').endOf('day').toDate()]],
- ["previousWeek", (date: Date) => [moment(date).subtract(1, 'week').startOf('isoWeek').toDate(), moment(date).subtract(1, 'week').endOf('isoWeek').toDate()]],
- ["previousMonth", (date: Date) => [moment(date).subtract(1, 'month').startOf('month').toDate(), moment(date).subtract(1, 'month').endOf('month').toDate()]],
- ["previousYear", (date: Date) => [moment(date).subtract(1, 'year').startOf('year').toDate(), moment(date).subtract(1, 'year').endOf('year').toDate()]]
-])
-
-export class OrChartWidget implements OrWidgetEntity {
-
- // Properties
- readonly DISPLAY_NAME: string = "Line Chart";
- readonly DISPLAY_MDI_ICON: string = "chart-bell-curve-cumulative"; // https://materialdesignicons.com;
- readonly MIN_COLUMN_WIDTH: number = 2;
- readonly MIN_PIXEL_WIDTH: number = 0;
- readonly MIN_PIXEL_HEIGHT: number = 0;
-
- getDefaultConfig(widget: DashboardWidget): ChartWidgetConfig {
- const preset = "last24Hours"
- const dateFunc = timePresetOptions.get(preset);
- const dates = dateFunc!(new Date());
- return {
- displayName: widget?.displayName,
- attributeRefs: [],
- datapointQuery: {
- type: "lttb",
- fromTimestamp: dates[0].getTime(),
- toTimestamp: dates[1].getTime(),
- amountOfPoints: 100
- },
- chartOptions: {
- options: {
- scales: {
- y: {
- min: undefined,
- max: undefined
- }
- }
- },
- },
- showTimestampControls: false,
- defaultTimePresetKey: preset,
- showLegend: true
- } as ChartWidgetConfig;
- }
-
- // Triggered every update to double check if the specification.
- // It will merge missing values, or you can add custom logic to process here.
- verifyConfigSpec(widget: DashboardWidget): ChartWidgetConfig {
- const defaultConfig = this.getDefaultConfig(widget);
- return Util.mergeObjects(defaultConfig, widget.widgetConfig, false) as ChartWidgetConfig;
- }
-
- getWidgetHTML(widget: DashboardWidget, editMode: boolean, realm: string): TemplateResult {
- return html`<or-chart-widget .widget="${widget}" .editMode="${editMode}" .realm="${realm}"></or-chart-widget>`;
- }
-
- getSettingsHTML(widget: DashboardWidget, realm: string): TemplateResult {
- return html`<or-chart-widgetsettings .widget="${widget}" .realm="${realm}"></or-chart-widgetsettings>`;
- }
-
-}
-
-
-
-
-@customElement('or-chart-widget')
-export class OrChartWidgetContent extends LitElement {
-
- @property()
- public readonly widget?: DashboardWidget;
-
- @property()
- public editMode?: boolean;
-
- @property()
- public realm?: string;
-
- @state()
- private assets: Asset[] = [];
-
- @state()
- private assetAttributes: [number, Attribute<any>][] = [];
-
- /* ---------- */
-
- render() {
- return html`
- ${when(this.assets && this.assetAttributes && this.assets.length > 0 && this.assetAttributes.length > 0, () => {
- return html`
- <or-chart .assets="${this.assets}" .assetAttributes="${this.assetAttributes}" .realm="${this.realm}"
- .showLegend="${(this.widget?.widgetConfig?.showLegend != null) ? this.widget?.widgetConfig?.showLegend : true}"
- .attributeControls="${false}" .timestampControls="${!this.editMode && this.widget?.widgetConfig?.showTimestampControls}" .algorithm="${this.widget?.widgetConfig?.algorithm}"
- .timePresetOptions="${timePresetOptions}" .timePresetKey="${this.widget?.widgetConfig?.defaultTimePresetKey}"
- .datapointQuery="${this.widget?.widgetConfig?.datapointQuery}" .chartOptions="${this.widget?.widgetConfig?.chartOptions}"
- style="height: 100%"
- ></or-chart>
- `;
- }, () => {
- return html`
- <div style="height: 100%; display: flex; justify-content: center; align-items: center;">
- <span>${i18next.t('noAttributesConnected')}</span>
- </div>
- `
- })}
- `
- }
-
- willUpdate(changedProperties: Map<string, any>) {
-
- // Add datapointQuery if not set yet (due to migration)
- if(this.widget && this.widget.widgetConfig.datapointQuery == undefined) {
- this.widget.widgetConfig.datapointQuery = {
- type: "lttb",
- fromTimestamp: moment().set('minute', -60).toDate().getTime(),
- toTimestamp: moment().set('minute', 60).toDate().getTime(),
- amountOfPoints: 100
- };
- if(!changedProperties.has("widget")) {
- changedProperties.set("widget", this.widget);
- }
- }
- super.willUpdate(changedProperties);
- }
-
- updated(changedProperties: Map<string, any>) {
-
- // Fetch assets
- if(changedProperties.has("widget") || changedProperties.has("editMode")) {
- if(this.assetAttributes.length != this.widget!.widgetConfig.attributeRefs.length) {
- this.fetchAssets(this.widget?.widgetConfig).then((assets) => {
- this.assets = assets!;
- this.assetAttributes = this.widget?.widgetConfig.attributeRefs.map((attrRef: AttributeRef) => {
- const assetIndex = assets!.findIndex((asset) => asset.id === attrRef.id);
- 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>][];
- });
- }
- }
- }
-
- // Fetching the assets according to the AttributeRef[] input in DashboardWidget if required. TODO: Simplify this to only request data needed for attribute list
- async fetchAssets(config: OrWidgetConfig | any): Promise<Asset[] | undefined> {
- if(config.attributeRefs && config.attributeRefs.length > 0) {
- let assets: Asset[] = [];
- await manager.rest.api.AssetResource.queryAssets({
- ids: config.attributeRefs?.map((x: AttributeRef) => x.id) as string[],
- select: {
- attributes: config.attributeRefs?.map((x: AttributeRef) => x.name) as string[]
- }
- }).then(response => {
- assets = response.data;
- }).catch((reason) => {
- console.error(reason);
- showSnackbar(undefined, i18next.t('errorOccurred'));
- });
- return assets;
- }
- }
-
-
- /* --------------------------- */
-
- // Caching and generation of mockData, to prevent API call to be made.
- // Is currently not used anymore, but can be used with the dataProvider on or-chart.
-
- @state()
- private cachedMockData?: Map<string, { period: any, data: any[] }> = new Map<string, { period: any, data: any[] }>();
-
- generateMockData(widget: DashboardWidget, startOfPeriod: number, _endOfPeriod: number, amount: number = 10) {
- const mockTime: number = startOfPeriod;
- const chartData: any[] = [];
- const interval = (Date.now() - startOfPeriod) / amount;
-
- // Generating random coordinates on the chart
- let data: any[] = [];
- const cached: { period: any, data: any[] } | undefined = this.cachedMockData?.get(widget.id!);
- if(cached && (cached.data.length == widget.widgetConfig?.attributeRefs?.length) && (cached.period == widget.widgetConfig?.period)) {
- data = this.cachedMockData?.get(widget.id!)!.data!;
- } else {
- widget.widgetConfig?.attributeRefs?.forEach((_attrRef: AttributeRef) => {
- let valueEntries: any[] = [];
- let prevValue: number = 100;
- for(let i = 0; i < amount; i++) {
- const value = Math.floor(Math.random() * ((prevValue + 2) - (prevValue - 2)) + (prevValue - 2))
- valueEntries.push({
- x: (mockTime + (i * interval)),
- y: value
- });
- prevValue = value;
- }
- data.push(valueEntries);
- });
- this.cachedMockData?.set(widget.id!, { period: widget.widgetConfig?.period, data: data });
- }
-
- // Making a line for each attribute
- widget.widgetConfig?.attributeRefs?.forEach((attrRef: AttributeRef) => {
- chartData.push({
- backgroundColor: ["#3869B1", "#DA7E30", "#3F9852", "#CC2428", "#6B4C9A", "#922427", "#958C3D", "#535055"][chartData.length],
- borderColor: ["#3869B1", "#DA7E30", "#3F9852", "#CC2428", "#6B4C9A", "#922427", "#958C3D", "#535055"][chartData.length],
- data: data[chartData.length],
- fill: false,
- label: attrRef.name,
- pointRadius: 2
- });
- });
- return chartData;
- }
-}
-
-
-
-
-
-
-
-@customElement("or-chart-widgetsettings")
-class OrChartWidgetSettings extends LitElement {
-
- @property()
- public widget?: DashboardWidget;
-
- // Default values
- private expandedPanels: string[] = [i18next.t('attributes'), i18next.t('dataSampling'), i18next.t('display'), i18next.t('dashboard.chartConfig')];
-
-
- static get styles() {
- return [style, widgetSettingsStyling];
- }
-
- willUpdate(changedProperties: Map<string, any>) {
-
- // Add datapointQuery if not set yet (due to migration)
- if(this.widget && this.widget.widgetConfig.datapointQuery == undefined) {
- this.widget.widgetConfig.datapointQuery = {
- type: "lttb",
- fromTimestamp: moment().set('minute', -60).toDate().getTime(),
- toTimestamp: moment().set('minute', 60).toDate().getTime(),
- amountOfPoints: 100
- };
- if(!changedProperties.has("widget")) {
- changedProperties.set("widget", this.widget);
- }
- }
- super.willUpdate(changedProperties);
- }
-
- // UI Rendering
- render() {
- const config = JSON.parse(JSON.stringify(this.widget!.widgetConfig)) as ChartWidgetConfig; // duplicate to edit, to prevent parent updates. Please trigger updateConfig()
- return html`
- <div>
- ${this.generateExpandableHeader(i18next.t('attributes'))}
- </div>
- <div>
- ${this.expandedPanels.includes(i18next.t('attributes')) ? html`
- <or-dashboard-settingspanel .type="${SettingsPanelType.MULTI_ATTRIBUTE}" .widgetConfig="${this.widget?.widgetConfig}"
- .attributeFilter="${(attribute: Attribute<any>) => {
- return ["positiveInteger", "positiveNumber", "number", "long", "integer", "bigInteger", "negativeInteger", "negativeNumber", "bigNumber", "integerByte", "direction", "boolean"]
- .includes(attribute.type!)}}"
- @updated="${(event: CustomEvent) => { this.updateConfig(this.widget!, event.detail.changes.get('config')) }}"
- ></or-dashboard-settingspanel>
- ` : null}
- </div>
- <div>
- ${this.generateExpandableHeader(i18next.t('display'))}
- </div>
- <div>
- ${this.expandedPanels.includes(i18next.t('display')) ? html`
- <div class="expanded-panel">
- <div>
- <or-mwc-input .type="${InputType.SELECT}" label="${i18next.t('timeframeDefault')}" style="width: 100%;"
- .options="${Array.from(timePresetOptions.keys())}" value="${config.defaultTimePresetKey}"
- @or-mwc-input-changed="${(event: OrInputChangedEvent) => {
- config.defaultTimePresetKey = event.detail.value.toString();
- this.updateConfig(this.widget!, config);
- }}"
- ></or-mwc-input>
- </div>
- <div>
- <div class="switchMwcInputContainer">
- <span>${i18next.t('dashboard.allowTimerangeSelect')}</span>
- <or-mwc-input .type="${InputType.SWITCH}" style="margin: 0 -10px;" .value="${config.showTimestampControls}"
- @or-mwc-input-changed="${(event: OrInputChangedEvent) => {
- config.showTimestampControls = event.detail.value;
- this.updateConfig(this.widget!, config);
- }}"
- ></or-mwc-input>
- </div>
- <div class="switchMwcInputContainer">
- <span>${i18next.t('dashboard.showLegend')}</span>
- <or-mwc-input .type="${InputType.SWITCH}" style="margin: 0 -10px;" .value="${config.showLegend}"
- @or-mwc-input-changed="${(event: OrInputChangedEvent) => {
- config.showLegend = event.detail.value;
- this.updateConfig(this.widget!, config);
- }}"
- ></or-mwc-input>
- </div>
- </div>
- </div>
- ` : null}
- </div>
- <div>
- ${this.generateExpandableHeader(i18next.t('dashboard.chartConfig'))}
- </div>
- <div>
- ${when(this.expandedPanels.includes(i18next.t('dashboard.chartConfig')), () => {
- const min = config.chartOptions.options?.scales?.y?.min;
- const max = config.chartOptions.options?.scales?.y?.max;
- return html`
- <div class="expanded-panel">
- <div>
- <div style="display: flex;">
- ${max != undefined ? html`
- <or-mwc-input .type="${InputType.NUMBER}" label="${i18next.t('yAxis') + ' ' + i18next.t('max')}" .value="${max}" style="width: 100%;"
- @or-mwc-input-changed="${(event: OrInputChangedEvent) => {
- config.chartOptions.options.scales.y.max = event.detail.value;
- this.updateConfig(this.widget!, config);
- }}"
- ></or-mwc-input>
- ` : html`
- <or-mwc-input .type="${InputType.TEXT}" label="${i18next.t('yAxis') + ' ' + i18next.t('max')}" disabled="true" value="auto" style="width: 100%;"></or-mwc-input>
- `}
- <or-mwc-input .type="${InputType.SWITCH}" style="margin: 0 -10px 0 0;" .value="${max != undefined}"
- @or-mwc-input-changed="${() => {
- config.chartOptions.options!.scales!.y!.max = (max == undefined) ? 100 : undefined;
- this.updateConfig(this.widget!, config);
- }}"
- ></or-mwc-input>
- </div>
- <div style="display: flex; margin-top: 12px;">
- ${min != undefined ? html`
- <or-mwc-input .type="${InputType.NUMBER}" label="${i18next.t('yAxis') + ' ' + i18next.t('min')}" .value="${min}" style="width: 100%;"
- @or-mwc-input-changed="${(event: OrInputChangedEvent) => {
- config.chartOptions.options.scales.y.min = event.detail.value;
- this.updateConfig(this.widget!, config);
- }}"
- ></or-mwc-input>
- ` : html`
- <or-mwc-input .type="${InputType.TEXT}" label="${i18next.t('yAxis') + ' ' + i18next.t('min')}" disabled="true" value="auto" style="width: 100%;"></or-mwc-input>
- `}
- <or-mwc-input .type="${InputType.SWITCH}" style="margin: 0 -10px 0 0;" .value="${min != undefined}"
- @or-mwc-input-changed="${() => {
- config.chartOptions.options!.scales!.y!.min = (min == undefined) ? 0 : undefined;
- this.updateConfig(this.widget!, config);
- }}"
- ></or-mwc-input>
- </div>
- </div>
- </div>
- `
- })}
- </div>
- <div>
- ${this.generateExpandableHeader(i18next.t('dataSampling'))}
- </div>
- <div>
- ${this.expandedPanels.includes(i18next.t('dataSampling')) ? html`
- ${when(config.datapointQuery, () => {
- const typeOptions = new Map<string, string>([["lttb", 'lttb'], ["withInterval", 'interval']]);
- const typeValue = Array.from(typeOptions.entries()).find((entry => entry[1] == config.datapointQuery.type))![0]
- return html`
- <div class="expanded-panel">
- <or-mwc-input .type="${InputType.SELECT}" style="width: 100%" .options="${Array.from(typeOptions.keys())}"
- .value="${typeValue}" label="${i18next.t('algorithm')}" @or-mwc-input-changed="${(event: OrInputChangedEvent) => {
- config.datapointQuery.type = typeOptions.get(event.detail.value)! as any;
- this.updateConfig(this.widget!, config, true);
- }}"
- ></or-mwc-input>
- ${choose(config.datapointQuery.type, [
- ['interval', () => {
- const intervalQuery = config.datapointQuery as AssetDatapointIntervalQuery;
- const formulaOptions = [AssetDatapointIntervalQueryFormula.AVG, AssetDatapointIntervalQueryFormula.MIN, AssetDatapointIntervalQueryFormula.MAX];
- return html`
- <or-mwc-input .type="${InputType.SELECT}" style="width: 100%;" .options="${formulaOptions}"
- .value="${intervalQuery.formula}" label="${i18next.t('algorithmMethod')}" @or-mwc-input-changed="${(event: OrInputChangedEvent) => {
- intervalQuery.formula = event.detail.value;
- this.updateConfig(this.widget!, config, true);
- }}"
- ></or-mwc-input>
- `;
- }]
- ])}
- </div>
- `
- }, () => {
- console.error(config);
- return html`${i18next.t('errorOccurred')}`;
- })}
- ` : null}
- </div>
- `
- }
-
- updateConfig(widget: DashboardWidget, config: OrWidgetConfig | any, force: boolean = false) {
- const oldWidget = JSON.parse(JSON.stringify(widget)) as DashboardWidget;
-
- if(config.datapointQuery) {
- switch (config.datapointQuery.type) {
- case 'lttb': {
- const query = config.datapointQuery as AssetDatapointLTTBQuery;
- if(!query.amountOfPoints) { query.amountOfPoints = 100; }
- break;
- }
- case 'interval': {
- const query = config.datapointQuery as AssetDatapointIntervalQuery;
- if(!query.interval) { query.interval = "1 hour"; }
- if(!query.gapFill) { query.gapFill = false; }
- if(!query.formula) { query.formula = AssetDatapointIntervalQueryFormula.AVG; }
- }
- }
- }
-
- 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.
- 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" @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-dashboard-builder/src/widgets/or-gauge-widget.ts b/ui/component/or-dashboard-builder/src/widgets/or-gauge-widget.ts
deleted file mode 100644
index b8b68ebb1..000000000
--- a/ui/component/or-dashboard-builder/src/widgets/or-gauge-widget.ts
+++ /dev/null
@@ -1,265 +0,0 @@
-import {OrWidgetConfig, OrWidgetEntity} from "./or-base-widget";
-import {style} from "../style";
-import {SettingsPanelType, widgetSettingsStyling} from "../or-dashboard-settingspanel";
-import {Asset, Attribute, AttributeRef, DashboardWidget } from "@openremote/model";
-import { html, LitElement, TemplateResult } from "lit";
-import { customElement, property, state } from "lit/decorators.js";
-import "@openremote/or-gauge";
-import { i18next } from "@openremote/or-translate";
-import manager, { Util } from "@openremote/core";
-import { showSnackbar } from "@openremote/or-mwc-components/or-mwc-snackbar";
-import {InputType} from "@openremote/or-mwc-components/or-mwc-input";
-import { when } from "lit/directives/when.js";
-
-export interface GaugeWidgetConfig extends OrWidgetConfig {
- displayName: string;
- attributeRefs: AttributeRef[];
- thresholds: [number, string][];
- decimals: number;
- min: number,
- max: number,
- valueType: string,
-}
-
-export class OrGaugeWidget implements OrWidgetEntity {
-
- readonly DISPLAY_MDI_ICON: string = "gauge";
- readonly DISPLAY_NAME: string = "Gauge";
- readonly MIN_COLUMN_WIDTH: number = 2;
- readonly MIN_PIXEL_HEIGHT: number = 0;
- readonly MIN_PIXEL_WIDTH: number = 0;
-
- getDefaultConfig(widget: DashboardWidget): OrWidgetConfig {
- return {
- displayName: widget.displayName,
- attributeRefs: [],
- 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,
- valueType: 'number',
- } as GaugeWidgetConfig;
- }
-
- // Triggered every update to double check if the specification.
- // It will merge missing values, or you can add custom logic to process here.
- verifyConfigSpec(widget: DashboardWidget): GaugeWidgetConfig {
- return Util.mergeObjects(this.getDefaultConfig(widget), widget.widgetConfig, false) as GaugeWidgetConfig;
- }
-
- getWidgetHTML(widget: DashboardWidget, editMode: boolean, realm: string) {
- return html`<or-gauge-widget .widget="${widget}" .editMode="${editMode}" realm="${realm}"></or-gauge-widget>`;
- }
-
- getSettingsHTML(widget: DashboardWidget, realm: string) {
- return html`<or-gauge-widgetsettings .widget="${widget}" realm="${realm}"></or-gauge-widgetsettings>`;
- }
-
-}
-
-@customElement("or-gauge-widget")
-export class OrGaugeWidgetContent extends LitElement {
-
- @property()
- public readonly widget?: DashboardWidget;
-
- @property()
- public editMode?: boolean;
-
- @property()
- public realm?: string;
-
- @state()
- private assets: Asset[] = [];
-
- @state()
- private assetAttributes: [number, Attribute<any>][] = [];
-
-
- render() {
- return html`
- ${when(this.assets && this.assetAttributes && this.assets.length > 0 && this.assetAttributes.length > 0, () => {
- return html`
- <or-gauge .asset="${this.assets[0]}" .assetAttribute="${this.assetAttributes[0]}" .thresholds="${this.widget?.widgetConfig.thresholds}"
- .decimals="${this.widget?.widgetConfig.decimals}" .min="${this.widget?.widgetConfig.min}" .max="${this.widget?.widgetConfig.max}"
- style="height: 100%; overflow: hidden;"></or-gauge>
- `;
- }, () => {
- return html`
- <div style="height: 100%; display: flex; justify-content: center; align-items: center;">
- <span>${i18next.t('noAttributeConnected')}</span>
- </div>
- `
- })}
- <!--<or-gauge .attrRef="${this.widget?.widgetConfig.attributeRefs[0]}"></or-gauge>-->
- `
- }
-
- updated(changedProperties: Map<string, any>) {
- if(changedProperties.has("widget") || changedProperties.has("editMode")) {
- this.fetchAssets(this.widget?.widgetConfig).then((assets) => {
- this.assets = assets!;
- this.assetAttributes = this.widget?.widgetConfig.attributeRefs.map((attrRef: AttributeRef) => {
- const assetIndex = assets!.findIndex((asset) => asset.id === attrRef.id);
- 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>][];
- this.requestUpdate();
- });
- }
- }
-
- // Fetching the assets according to the AttributeRef[] input in DashboardWidget if required. TODO: Simplify this to only request data needed for attribute list
- async fetchAssets(config: OrWidgetConfig | any): Promise<Asset[] | undefined> {
- if(config.attributeRefs && config.attributeRefs.length > 0) {
- let assets: Asset[] = [];
- await manager.rest.api.AssetResource.queryAssets({
- ids: config.attributeRefs?.map((x: AttributeRef) => x.id) as string[],
- select: {
- attributes: config.attributeRefs?.map((x: AttributeRef) => x.name) as string[]
- }
- }).then(response => {
- assets = response.data;
- }).catch((reason) => {
- console.error(reason);
- showSnackbar(undefined, i18next.t('errorOccurred'));
- });
- return assets;
- }
- }
-}
-
-
-
-@customElement("or-gauge-widgetsettings")
-export class OrGaugeWidgetSettings extends LitElement {
-
- @property()
- public readonly widget?: DashboardWidget;
-
- // Default values
- private expandedPanels: string[] = [i18next.t('attributes'), i18next.t('values'), i18next.t('thresholds')];
- private loadedAsset?: Asset;
-
- static get styles() {
- return [style, widgetSettingsStyling];
- }
-
- // UI Rendering
- render() {
- const config = JSON.parse(JSON.stringify(this.widget!.widgetConfig)) as GaugeWidgetConfig; // duplicate to edit, to prevent parent updates. Please trigger updateConfig()
- return html`
- <div>
- ${this.generateExpandableHeader(i18next.t('attributes'))}
- </div>
- <div>
- ${this.expandedPanels.includes(i18next.t('attributes')) ? html`
- <or-dashboard-settingspanel .type="${SettingsPanelType.SINGLE_ATTRIBUTE}" .onlyDataAttrs="${false}" .widgetConfig="${this.widget?.widgetConfig}"
- .attributeFilter="${(attribute: Attribute<any>) => {
- return ["positiveInteger", "positiveNumber", "number", "long", "integer", "bigInteger", "negativeInteger", "negativeNumber", "bigNumber", "integerByte", "direction"]
- .includes(attribute.type!)}}"
- @updated="${(event: CustomEvent) => {
- this.updateConfig(this.widget!, event.detail.changes.get('config'));
- this.onAttributesUpdate(event.detail.changes);
- }}"
- ></or-dashboard-settingspanel>
- ` : null}
- </div>
- <div>
- ${this.generateExpandableHeader(i18next.t('values'))}
- </div>
- <div>
- ${this.expandedPanels.includes(i18next.t('values')) ? html`
- <div class="expanded-panel">
- <div style="display: flex; gap: 8px;">
- <or-mwc-input type="${InputType.NUMBER}" label="${i18next.t('min')}" .max="${this.widget?.widgetConfig.max}" .value="${this.widget?.widgetConfig.min}"
- @or-mwc-input-changed="${(event: CustomEvent) => {
- if(event.detail.value < this.widget?.widgetConfig.max) {
- config.min = event.detail.value;
- if(config.thresholds[1][0] > event.detail.value) {
- config.thresholds[0][0] = event.detail.value;
- }
- this.updateConfig(this.widget!, config);
- }
- }}"
- ></or-mwc-input>
- <or-mwc-input type="${InputType.NUMBER}" label="${i18next.t('max')}" .min="${this.widget?.widgetConfig.min}" .value="${this.widget?.widgetConfig.max}"
- @or-mwc-input-changed="${(event: CustomEvent) => {
- if(event.detail.value > this.widget?.widgetConfig.min) {
- config.max = event.detail.value;
- this.updateConfig(this.widget!, config);
- }
- }}"
- ></or-mwc-input>
- </div>
- <div>
- <or-mwc-input type="${InputType.NUMBER}" style="width: 100%;" .value="${config.decimals}" label="${i18next.t('decimals')}" .min="${0}"
- @or-mwc-input-changed="${(event: CustomEvent) => {
- config.decimals = event.detail.value;
- this.updateConfig(this.widget!, config);
- }}"
- ></or-mwc-input>
- </div>
- </div>
- ` : null}
- </div>
- <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>
- `
- }
-
- 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);
- }
-
-
- /* ------------------------------ */
-
- onAttributesUpdate(changes: Map<string, any>) {
- if(changes.has('loadedAssets')) {
- this.loadedAsset = changes.get('loadedAssets')[0];
- }
- if(changes.has('config')) {
- const config = changes.get('config') as GaugeWidgetConfig;
- if(config.attributeRefs.length > 0) {
- this.widget!.displayName = this.loadedAsset?.name + " - " + this.loadedAsset?.attributes![config.attributeRefs[0].name!].name;
- }
- }
- }
-
- // Method to update the Grid. For example after changing a setting.
- 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" @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-dashboard-builder/src/widgets/or-image-widget.ts b/ui/component/or-dashboard-builder/src/widgets/or-image-widget.ts
deleted file mode 100644
index 587df5d16..000000000
--- a/ui/component/or-dashboard-builder/src/widgets/or-image-widget.ts
+++ /dev/null
@@ -1,446 +0,0 @@
-import manager, {DefaultColor2, DefaultColor3, Util} from '@openremote/core';
-import {
- Asset,
- AssetModelUtil,
- Attribute,
- AttributeRef,
- DashboardWidget, WellknownValueTypes
-} from "@openremote/model";
-import {showSnackbar} from '@openremote/or-mwc-components/or-mwc-snackbar';
-import {i18next} from '@openremote/or-translate';
-import {css, html, LitElement, TemplateResult, unsafeCSS} from 'lit';
-import {customElement, property, state} from 'lit/decorators.js';
-import {OrWidgetConfig, OrWidgetEntity} from './or-base-widget';
-import {when} from 'lit/directives/when.js';
-import {map} from 'lit/directives/map.js';
-import {styleMap} from 'lit/directives/style-map.js';
-import {style} from '../style';
-import {SettingsPanelType, widgetSettingsStyling} from '../or-dashboard-settingspanel';
-import {InputType, OrInputChangedEvent} from '@openremote/or-mwc-components/or-mwc-input';
-
-export interface ImageAssetMarker {
- attributeRef: AttributeRef,
- coordinates: [number, number]
-}
-
-export interface ImageWidgetConfig extends OrWidgetConfig {
- displayName: string;
- attributeRefs: AttributeRef[];
- markers: ImageAssetMarker[];
- showTimestampControls: boolean;
- imagePath: string;
-}
-
-export class OrImageWidget implements OrWidgetEntity {
-
- readonly DISPLAY_MDI_ICON: string = 'file-image-marker'; // https://materialdesignicons.com;
- readonly DISPLAY_NAME: string = 'Image';
- readonly MIN_COLUMN_WIDTH: number = 2;
- readonly MIN_PIXEL_HEIGHT: number = 0;
- readonly MIN_PIXEL_WIDTH: number = 0;
-
- getDefaultConfig(widget: DashboardWidget): OrWidgetConfig {
- return {
- displayName: widget?.displayName,
- attributeRefs: [],
- showTimestampControls: false,
- imagePath: '',
- markers: [],
- } as unknown as ImageWidgetConfig;
- }
-
- getSettingsHTML(widget: DashboardWidget, realm: string) {
- return html`
- <or-image-widgetsettings .widget="${widget}" realm="${realm}"></or-image-widgetsettings>`;
- }
-
- getWidgetHTML(widget: DashboardWidget, editMode: boolean, realm: string) {
- return html`
- <or-image-widget .widget="${widget}" .editMode="${editMode}" realm="${realm}" style="height: 100%; overflow: hidden;"></or-image-widget>`;
- }
-
-// Triggered every update to double check if the specification.
- // It will merge missing values, or you can add custom logic to process here.
- verifyConfigSpec(widget: DashboardWidget): ImageWidgetConfig {
- return Util.mergeObjects(this.getDefaultConfig(widget), widget.widgetConfig, false) as ImageWidgetConfig;
- }
-}
-
-const contentStyling = css`
- #img-wrapper {
- height: 100%;
- width: 100%;
- display: flex;
- flex-direction: column;
- justify-content: center;
- align-items: center;
- overflow: hidden;
- z-index: 1;
- }
-
- #img-container {
- position: relative;
- max-height: 100%;
- }
-
- #img-content {
- height: 100%;
- max-height: 100%;
- max-width: 100%;
- }
-
- #overlay {
- position: absolute;
- z-index: 3;
-
- /*additional marker styling*/
- color: var(--or-app-color2, ${unsafeCSS(DefaultColor2)});
- background-color: var(--or-app-color3, ${unsafeCSS(DefaultColor3)});
- border-radius: 15px;
- padding: 3px 8px 5px 8px;
- object-fit: contain;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
-`;
-
-@customElement('or-image-widget')
-export class OrImageWidgetContent extends LitElement {
-
- @property()
- public realm?: string;
-
- @property()
- public readonly widget?: DashboardWidget;
-
- @property()
- public editMode?: boolean;
-
- @state()
- protected assets: Asset[] = [];
-
- @state()
- protected assetAttributes: [number, Attribute<any>][] = [];
-
- static styles = contentStyling;
-
- // method to render and update the markers on the image
- private handleMarkerPlacement(config: ImageWidgetConfig) {
- if (this.assetAttributes.length && config.attributeRefs.length > 0) {
-
- if(config.markers.length === 0) {
- console.error("No markers found!");
- return [];
- }
- return config.attributeRefs.map((attributeRef, index) => {
- const marker = config.markers.find(m => m.attributeRef.id === attributeRef.id && m.attributeRef.name === attributeRef.name);
- const asset = this.assets.find(a => a.id === attributeRef.id);
- let value: string | undefined;
- const styles: any = {
- "left": `${marker!.coordinates[0]}%`,
- "top": `${marker!.coordinates[1]}%`
- };
- if(asset) {
- const attribute = asset.attributes![attributeRef.name!];
- const descriptors = AssetModelUtil.getAttributeAndValueDescriptors(asset.type, attributeRef.name, attribute);
- value = Util.getAttributeValueAsString(attribute, descriptors[0], asset.type, true, "-");
- if(attribute?.type === WellknownValueTypes.COLOURRGB && value !== "-") {
- styles.backgroundColor = value;
- styles.minHeight = "21px";
- styles.minWidth = "13px";
- value = undefined;
- }
- }
- return html`
- <span id="overlay" style="${styleMap(styles)}">
- ${value}
- </span>
- `;
- });
- }
- }
-
-
- render() {
- const imagePath = this.widget?.widgetConfig.imagePath;
- return html`
- <div id="img-wrapper">
- ${when(imagePath, () => html`
- <div id="img-container">
- <img id="img-content" src="${imagePath}" alt=""/>
- <div>
- ${this.handleMarkerPlacement(this.widget?.widgetConfig)}
- </div>
- </div>
- `, () => html`
- <span>${i18next.t('dashboard.noImageSelected')}</span>
- `)}
- </div>
- `;
- }
-
- updated(changedProperties: Map<string, any>) {
- if (changedProperties.has('widget') || changedProperties.has('editMode')) {
- if (this.assetAttributes.length !== this.widget!.widgetConfig.attributeRefs.length) {
- this.fetchAssets(this.widget?.widgetConfig).then(assets => {
- this.assets = assets!;
- this.assetAttributes = this.widget?.widgetConfig.attributeRefs.map((attrRef: AttributeRef) => {
- const assetIndex = assets!.findIndex(asset => asset.id === attrRef.id);
- 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>][];
- });
- }
- }
- }
-
-
- // Fetching the assets according to the AttributeRef[] input in DashboardWidget if required. TODO: Simplify this to only request data needed for attribute list
- async fetchAssets(config: OrWidgetConfig | any): Promise<Asset[] | undefined> {
- if (config.attributeRefs && config.attributeRefs.length > 0) {
- let assets: Asset[] = [];
- await manager.rest.api.AssetResource.queryAssets({
- ids: config.attributeRefs?.map((x: AttributeRef) => x.id) as string[],
- realm: {
- name: this.realm
- },
- select: {
- attributes: config.attributeRefs?.map((x: AttributeRef) => x.name) as string[]
- }
- }).then(response => {
- assets = response.data;
- }).catch(reason => {
- console.error(reason);
- showSnackbar(undefined, i18next.t('errorOccurred'));
- });
- return assets;
- }
- }
-}
-
-const markerContainerStyling = css`
- #marker-container {
- display: flex;
- justify-content: flex-end;
- align-items: center;
- }
-`;
-
-@customElement('or-image-widgetsettings')
-export class OrImageWidgetSettings extends LitElement {
-
- static get styles() {
- return [style, widgetSettingsStyling, markerContainerStyling];
- }
-
- private expandedPanels: string[] = [i18next.t('attributes'), i18next.t('dashboard.markerCoordinates'), i18next.t('dashboard.imageSettings')];
-
- @state()
- private loadedAssets?: Asset[];
-
- @property()
- public readonly widget?: DashboardWidget;
-
- protected updated(changedProps: Map<string, any>) {
- if(this.loadedAssets === undefined) {
- this.fetchAssets(this.widget?.widgetConfig).then((assets) => {
- if(assets === undefined) {
- this.loadedAssets = [];
- } else {
- this.loadedAssets = assets;
- }
- });
- }
- }
-
- // Fetching the assets according to the AttributeRef[] input in DashboardWidget if required. TODO: Simplify this to only request data needed for attribute list
- async fetchAssets(config: OrWidgetConfig | any): Promise<Asset[] | undefined> {
- if (config.attributeRefs && config.attributeRefs.length > 0) {
- let assets: Asset[] = [];
- await manager.rest.api.AssetResource.queryAssets({
- ids: config.attributeRefs?.map((x: AttributeRef) => x.id) as string[],
- realm: {
- name: manager.displayRealm // TODO: Improve this
- },
- select: {
- attributes: config.attributeRefs?.map((x: AttributeRef) => x.name) as string[]
- }
- }).then(response => {
- assets = response.data;
- }).catch((reason) => {
- console.error(reason);
- showSnackbar(undefined, i18next.t('errorOccurred'));
- });
- return assets;
- }
- }
-
- // UI Rendering
- render() {
- const config = JSON.parse(JSON.stringify(this.widget!.widgetConfig)) as ImageWidgetConfig; // duplicate to edit, to prevent parent updates. Please trigger updateConfig()
- return html`
- <div>
- ${this.generateExpandableHeader(i18next.t('attributes'))}
- </div>
- <div>
- ${this.expandedPanels.includes(i18next.t('attributes')) ? html`
- <or-dashboard-settingspanel .type="${SettingsPanelType.MULTI_ATTRIBUTE}" .onlyDataAttrs="${false}" .widgetConfig="${this.widget!.widgetConfig}"
- @updated="${(event: CustomEvent) => {
- this.onAttributesUpdate(event.detail.changes);
- this.updateConfig(this.widget!, event.detail.changes.get('config'));
- }}"
- ></or-dashboard-settingspanel>
- ` : null}
- </div>
- <div>
- ${this.generateExpandableHeader(i18next.t('dashboard.markerCoordinates'))}
- </div>
- <div>
- ${when(this.expandedPanels.includes(i18next.t('dashboard.markerCoordinates')), () => html`
- <div class="expanded-panel" style="gap: 8px;">
- ${map(this.draftCoordinateEntries(config), template => template)}
- </div>
- `)}
- </div>
- <div>
- ${this.generateExpandableHeader(i18next.t('dashboard.imageSettings'))}
- </div>
- <div>
- ${this.expandedPanels.includes(i18next.t('dashboard.imageSettings')) ? html`
- <div class="expanded-panel">
- <or-mwc-input style="width: 100%;" type="${InputType.TEXT}" label="${i18next.t('dashboard.imageUrl')}" .value="${config.imagePath}"
- @or-mwc-input-changed="${(event: OrInputChangedEvent) => {
- config.imagePath = event.detail.value;
- this.updateConfig(this.widget!, config);
- }}"
- ></or-mwc-input>
- </div>
- ` : null}
- </div>
- `;
- }
-
-
- private draftCoordinateEntries(config: ImageWidgetConfig): TemplateResult[] {
- const min = 0;
- const max = 100;
-
- if (config.markers.length > 0) {
- return config.attributeRefs.map((attributeRef) => {
- const marker = config.markers.find(m => m.attributeRef.id === attributeRef.id && m.attributeRef.name === attributeRef.name);
- if(marker === undefined) {
- console.error("A marker could not be found during drafting coordinate entries.");
- return html``;
- }
- const index = config.markers.indexOf(marker);
- const coordinates = marker.coordinates;
- const asset = this.loadedAssets?.find(a => a.id === attributeRef.id);
- let label: string | undefined;
- if(asset) {
- const attribute = asset.attributes![attributeRef.name!];
- const descriptors = AssetModelUtil.getAttributeAndValueDescriptors(asset.type, attributeRef.name, attribute);
- label = Util.getAttributeLabel(attribute, descriptors[0], asset.type, false);
- }
- return html`
- <div id="marker-container">
- <div style="flex: 1; display: flex; flex-direction: column;">
- <span>${this.loadedAssets?.find(a => a.id === attributeRef.id)?.name}</span>
- ${when(label, () => html`
- <span style="color: gray;">${label}</span>
- `)}
- </div>
- <div style="display: flex; gap: 8px;">
- <or-mwc-input .disableSliderNumberInput="${true}" compact style="max-width: 64px;"
- .type="${InputType.NUMBER}" .min="${min}" .max="${max}" .value="${coordinates[0]}"
- @or-mwc-input-changed="${(event: OrInputChangedEvent) => {
- config.markers[index].coordinates = [event.detail.value, coordinates[1]];
- this.updateConfig(this.widget!, config);
- }}"
- ></or-mwc-input>
-
- <or-mwc-input .disableSliderNumberInput="${true}" compact style="max-width: 64px;"
- .type="${InputType.NUMBER}" .min="${min}" .max="${max}" .value="${coordinates[1]}"
- @or-mwc-input-changed="${(event: OrInputChangedEvent) => {
- config.markers[index].coordinates = [coordinates[0], event.detail.value];
- this.updateConfig(this.widget!, config);
- }}"
- ></or-mwc-input>
- </div>
- </div>
- `;
- });
- } else {
- return [
- html`<span>${i18next.t('noAttributeConnected')}</span>`
- ];
- }
- }
-
- // updates coordinate map according to the attributeRef entries per id
- updateCoordinateMap(config: ImageWidgetConfig) {
- for (let i = 0; i < config.attributeRefs.length; i++) {
- const attributeRef = config.attributeRefs[i];
- if (attributeRef === undefined) {
- console.error('attributeRef is undefined');
- return;
- }
- const index = config.markers.findIndex(m => m.attributeRef.id === attributeRef.id && m.attributeRef.name === attributeRef.name);
- if (index === -1) {
- config.markers.push({
- attributeRef: attributeRef,
- coordinates: [50, 50]
- });
- }
- }
- }
-
- private updateConfig(widget: DashboardWidget, config: OrWidgetConfig | any, force = 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);
- }
-
-
- private onAttributesUpdate(changes: Map<string, any>) {
- if (changes.has('loadedAssets')) {
- this.loadedAssets = changes.get('loadedAssets');
- }
- if (changes.has('config')) {
- const config = changes.get('config') as ImageWidgetConfig;
- this.updateCoordinateMap(config);
- }
- }
-
-
- // Method to update the Grid. For example after changing a setting.
- private forceParentUpdate(changes: Map<string, any>, force = false) {
- this.requestUpdate();
- this.dispatchEvent(new CustomEvent('updated', {detail: {changes: changes, force: force}}));
- }
-
-
- private generateExpandableHeader(name: string): TemplateResult {
- return html`
- <span class="expandableHeader" @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>
- `;
- }
-
-
- private 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-dashboard-builder/src/widgets/or-kpi-widget.ts b/ui/component/or-dashboard-builder/src/widgets/or-kpi-widget.ts
deleted file mode 100644
index 9d805d650..000000000
--- a/ui/component/or-dashboard-builder/src/widgets/or-kpi-widget.ts
+++ /dev/null
@@ -1,255 +0,0 @@
-import manager, { Util } from "@openremote/core";
-import {Asset, Attribute, AttributeRef, DashboardWidget } from "@openremote/model";
-import { showSnackbar } from "@openremote/or-mwc-components/or-mwc-snackbar";
-import { i18next } from "@openremote/or-translate";
-import { html, LitElement, TemplateResult } from "lit";
-import { customElement, property, state } from "lit/decorators.js";
-import {OrWidgetConfig, OrWidgetEntity} from "./or-base-widget";
-import {style} from "../style";
-import {SettingsPanelType, widgetSettingsStyling} from "../or-dashboard-settingspanel";
-import {InputType, OrInputChangedEvent } from "@openremote/or-mwc-components/or-mwc-input";
-
-export interface KpiWidgetConfig extends OrWidgetConfig {
- displayName: string;
- attributeRefs: AttributeRef[];
- period?: 'year' | 'month' | 'week' | 'day' | 'hour';
- decimals: number;
- deltaFormat: "absolute" | "percentage";
- showTimestampControls: boolean;
-}
-
-export class OrKpiWidget implements OrWidgetEntity {
-
- readonly DISPLAY_MDI_ICON: string = "label";
- readonly DISPLAY_NAME: string = "KPI";
- readonly MIN_COLUMN_WIDTH: number = 2;
- readonly MIN_PIXEL_HEIGHT: number = 0;
- readonly MIN_PIXEL_WIDTH: number = 0;
-
- getDefaultConfig(widget: DashboardWidget): OrWidgetConfig {
- return {
- displayName: widget.displayName,
- attributeRefs: [],
- period: "day",
- decimals: 0,
- deltaFormat: "absolute",
- showTimestampControls: false
- } as KpiWidgetConfig;
- }
-
- // Triggered every update to double check if the specification.
- // It will merge missing values, or you can add custom logic to process here.
- verifyConfigSpec(widget: DashboardWidget): KpiWidgetConfig {
- return Util.mergeObjects(this.getDefaultConfig(widget), widget.widgetConfig, false) as KpiWidgetConfig;
- }
-
-
- getSettingsHTML(widget: DashboardWidget, realm: string) {
- return html`<or-kpi-widgetsettings .widget="${widget}" realm="${realm}"></or-kpi-widgetsettings>`;
- }
-
- getWidgetHTML(widget: DashboardWidget, editMode: boolean, realm: string) {
- return html`<or-kpi-widget .widget="${widget}" .editMode="${editMode}" realm="${realm}" style="height: 100%; overflow: hidden;"></or-kpi-widget>`;
- }
-
-}
-
-@customElement("or-kpi-widget")
-export class OrKpiWidgetContent extends LitElement {
-
- @property()
- public readonly widget?: DashboardWidget;
-
- @property()
- public editMode?: boolean;
-
- @property()
- public realm?: string;
-
- @state()
- private loadedAssets: Asset[] = [];
-
- @state()
- private assetAttributes: [number, Attribute<any>][] = [];
-
- render() {
- return html`
- <or-attribute-card .assets="${this.loadedAssets}" .assetAttributes="${this.assetAttributes}" .period="${this.widget?.widgetConfig.period}"
- .deltaFormat="${this.widget?.widgetConfig.deltaFormat}" .mainValueDecimals="${this.widget?.widgetConfig.decimals}"
- showControls="${!this.editMode && this.widget?.widgetConfig?.showTimestampControls}" showTitle="${false}" realm="${this.realm}" style="height: 100%;">
- </or-attribute-card>
- `
- }
-
- updated(changedProperties: Map<string, any>) {
- if(changedProperties.has("widget") || changedProperties.has("editMode")) {
- this.fetchAssets(this.widget?.widgetConfig).then((assets) => {
- this.loadedAssets = (assets ? assets : []);
- this.assetAttributes = this.widget?.widgetConfig.attributeRefs.map((attrRef: AttributeRef) => {
- const assetIndex = assets!.findIndex((asset) => asset.id === attrRef.id);
- 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>][];
- this.requestUpdate();
- });
- }
- }
-
- // Fetching the assets according to the AttributeRef[] input in DashboardWidget if required. TODO: Simplify this to only request data needed for attribute list
- async fetchAssets(config: OrWidgetConfig | any): Promise<Asset[] | undefined> {
- if(config.attributeRefs && config.attributeRefs.length > 0) {
- let assets: Asset[] = [];
- await manager.rest.api.AssetResource.queryAssets({
- ids: config.attributeRefs?.map((x: AttributeRef) => x.id) as string[],
- select: {
- attributes: config.attributeRefs?.map((x: AttributeRef) => x.name) as string[]
- }
- }).then(response => {
- assets = response.data;
- }).catch((reason) => {
- console.error(reason);
- showSnackbar(undefined, i18next.t('errorOccurred'));
- });
- return assets;
- }
- }
-}
-
-
-
-@customElement("or-kpi-widgetsettings")
-export class OrKpiWidgetSettings extends LitElement {
-
- @property()
- public readonly widget?: DashboardWidget;
-
- // Default values
- private expandedPanels: string[] = [i18next.t('attributes'), i18next.t('display'), i18next.t('values')];
- private loadedAsset?: Asset;
-
-
- static get styles() {
- return [style, widgetSettingsStyling];
- }
-
- // UI Rendering
- render() {
- const config = JSON.parse(JSON.stringify(this.widget!.widgetConfig)) as KpiWidgetConfig; // duplicate to edit, to prevent parent updates. Please trigger updateConfig()
- return html`
- <div>
- ${this.generateExpandableHeader(i18next.t('attributes'))}
- </div>
- <div>
- ${this.expandedPanels.includes(i18next.t('attributes')) ? html`
- <or-dashboard-settingspanel .type="${SettingsPanelType.SINGLE_ATTRIBUTE}" .widgetConfig="${this.widget!.widgetConfig}"
- .attributeFilter="${(attribute: Attribute<any>) => {
- return ["positiveInteger", "positiveNumber", "number", "long", "integer", "bigInteger", "negativeInteger", "negativeNumber", "bigNumber", "integerByte", "direction"]
- .includes(attribute.type!)}}"
- @updated="${(event: CustomEvent) => {
- this.onAttributesUpdate(event.detail.changes);
- this.updateConfig(this.widget!, event.detail.changes.get('config'));
- }}"
- ></or-dashboard-settingspanel>
- ` : null}
- </div>
- <div>
- ${this.generateExpandableHeader(i18next.t('display'))}
- </div>
- <div>
- ${this.expandedPanels.includes(i18next.t('display')) ? html`
- <div class="expanded-panel">
- <div>
- <or-mwc-input .type="${InputType.SELECT}" style="width: 100%;"
- .options="${['year', 'month', 'week', 'day', 'hour']}"
- .value="${config.period}" label="${i18next.t('timeframe')}"
- @or-mwc-input-changed="${(event: OrInputChangedEvent) => {
- config.period = event.detail.value;
- this.updateConfig(this.widget!, config);
- }}"
- ></or-mwc-input>
- </div>
- <div class="switchMwcInputContainer">
- <span>${i18next.t('dashboard.allowTimerangeSelect')}</span>
- <or-mwc-input .type="${InputType.SWITCH}" style="margin: 0 -10px;" .value="${config.showTimestampControls}"
- @or-mwc-input-changed="${(event: OrInputChangedEvent) => {
- config.showTimestampControls = event.detail.value;
- this.updateConfig(this.widget!, config);
- }}"
- ></or-mwc-input>
- </div>
- </div>
- ` : null}
- </div>
- <div>
- ${this.generateExpandableHeader(i18next.t('values'))}
- </div>
- <div>
- ${this.expandedPanels.includes(i18next.t('values')) ? html`
- <div class="expanded-panel">
- <div>
- <or-mwc-input .type="${InputType.SELECT}" style="width: 100%;" .options="${['absolute', 'percentage']}" .value="${config.deltaFormat}" label="${i18next.t('dashboard.showValueAs')}"
- @or-mwc-input-changed="${(event: OrInputChangedEvent) => {
- config.deltaFormat = event.detail.value;
- this.updateConfig(this.widget!, config);
- }}"
- ></or-mwc-input>
- </div>
- <div>
- <or-mwc-input .type="${InputType.NUMBER}" style="width: 100%;" .value="${config.decimals}" label="${i18next.t('decimals')}"
- @or-mwc-input-changed="${(event: OrInputChangedEvent) => {
- config.decimals = event.detail.value;
- this.updateConfig(this.widget!, config);
- }}"
- ></or-mwc-input>
- </div>
- </div>
- ` : null}
- </div>
- `
- }
-
- 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);
- }
-
- onAttributesUpdate(changes: Map<string, any>) {
- if(changes.has('loadedAssets')) {
- this.loadedAsset = changes.get('loadedAssets')[0];
- }
- if(changes.has('config')) {
- const config = changes.get('config') as KpiWidgetConfig;
- if(config.attributeRefs.length > 0) {
- this.widget!.displayName = this.loadedAsset?.name + " - " + this.loadedAsset?.attributes![config.attributeRefs[0].name!].name;
- }
- }
- }
-
- // Method to update the Grid. For example after changing a setting.
- forceParentUpdate(changes: Map<string, any>, force: boolean = false) {
- this.requestUpdate();
- this.dispatchEvent(new CustomEvent('updated', {detail: {changes: changes, force: force}}));
- }
-
- generateExpandableHeader(name: string): TemplateResult {
- return html`
- <span class="expandableHeader" @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-dashboard-builder/src/widgets/or-map-widget.ts b/ui/component/or-dashboard-builder/src/widgets/or-map-widget.ts
deleted file mode 100644
index c5615df29..000000000
--- a/ui/component/or-dashboard-builder/src/widgets/or-map-widget.ts
+++ /dev/null
@@ -1,364 +0,0 @@
-import {
- Asset,
- Attribute,
- AttributeRef,
- DashboardWidget,
- WellknownAttributes,
- WellknownMetaItems,
- GeoJSONPoint,
- AssetDescriptor,
-} 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 {
- OrMap,
- MapMarkerAssetConfig,
- LngLatLike,
- AttributeMarkerColours,
- RangeAttributeMarkerColours,
- AttributeMarkerColoursRange,
- MapMarkerColours,
-} from "@openremote/or-map";
-import {LngLat} 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,
- showGeoJson: 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[],
- assetIds: string[],
- 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,
- showGeoJson: true,
- boolColors: {type: 'boolean', 'false': '#ef5350', 'true': '#4caf50'},
- textColors: [['example', '4caf50'], ['example2', 'ef5350']],
- thresholds: [[0, "#4caf50"], [75, "#ff9800"], [90, "#ef5350"]],
- assetTypes: [],
- assetType: undefined,
- assetIds: [],
- attributes: [],
- } as MapWidgetConfig;
- }
-
- // Triggered every update to double check if the specification.
- // It will merge missing values, or you can add custom logic to process here.
- verifyConfigSpec(widget: DashboardWidget): MapWidgetConfig {
- return Util.mergeObjects(this.getDefaultConfig(widget), widget.widgetConfig, false) as MapWidgetConfig;
- }
-
- getWidgetHTML(widget: DashboardWidget, editMode: boolean, realm: string): TemplateResult {
- return html`
- <or-map-widget .widget="${widget}" .editMode="${editMode}" .realm="${realm}" style="overflow: hidden;"></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() {
- this.markers = {};
- return html`
- <div style="height: 100%; display: flex; flex-direction: column; overflow: hidden;">
- <or-map id="miniMap" class="or-map" .zoom="${this.widget?.widgetConfig?.zoom}"
- .center="${this.widget?.widgetConfig?.center}" .showGeoJson="${this.widget?.widgetConfig?.showGeoJson}"
- style="flex: 1;">
- ${(this.assets) ?
- this.assets.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.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>
- </div>
- `
- }
-
- updated(changedProperties: Map<string, any>) {
- if (changedProperties.has("widget") || changedProperties.has("editMode")) {
- const areAssetsIncorrect: boolean = this.assets?.find((a) => !this.widget?.widgetConfig?.assetIds?.includes(a.id)) != undefined;
- if (this.assets == undefined || this.assets?.length === 0 || areAssetsIncorrect) {
- 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({
- realm: {
- name: this.realm
- },
- 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('configuration.mapSettings'), i18next.t('attributes'), i18next.t('thresholds')];
-
-
- 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()
- return html`
- <div>
- ${this.generateExpandableHeader(i18next.t('configuration.mapSettings'))}
- </div>
- <div>
- ${this.expandedPanels.includes(i18next.t('configuration.mapSettings')) ? html`
- <div class="expanded-panel">
- <div>
- <or-mwc-input .type="${InputType.NUMBER}" style="width: 100%;"
- .value="${this.widget?.widgetConfig?.zoom}" label="${i18next.t('dashboard.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="${this.widget?.widgetConfig?.center ? (Object.values(this.widget.widgetConfig.center))[0] + ', ' + (Object.values(this.widget.widgetConfig.center))[1] : undefined}"
- label="${i18next.t('dashboard.center')}"
- @or-mwc-input-changed="${(event: OrInputChangedEvent) => {
- if (event.detail.value) {
- const lngLatArr = (event.detail.value as string).split(/[, ]/).filter(v => !!v);
- if (lngLatArr.length === 2) {
- var value = new LngLat(
- Number.parseFloat(lngLatArr[0]),
- Number.parseFloat(lngLatArr[1])
- );
- config.center = value as LngLatLike;
- this.updateConfig(this.widget!, config);
- }
- }
- }}"
- ></or-mwc-input>
- </div>
- <div style="display: flex; justify-content: space-between; align-items: center;">
- <span>${i18next.t('dashboard.showGeoJson')}</span>
- <or-mwc-input .type="${InputType.SWITCH}" style="width: 70px;"
- .value="${config.showGeoJson}"
- @or-mwc-input-changed="${(event: CustomEvent) => {
- config.showGeoJson = event.detail.value;
- this.updateConfig(this.widget!, config, true);
- }}"
- ></or-mwc-input>
- </div>
- </div>
- ` : null}
- </div>
- <div>
- ${this.generateExpandableHeader(i18next.t('attributes'))}
- </div>
- <div>
- ${this.expandedPanels.includes(i18next.t('attributes')) ? 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?.assetIds?.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}
- `
- }
-
- updated(changedProperties: Map<string, any>){
- if(!this.widget?.widgetConfig?.zoom && !this.widget?.widgetConfig?.center){
- manager.rest.api.MapResource.getSettings().then((response) => {
- this.widget!.widgetConfig.zoom = response.data.options.default.zoom;
- this.widget!.widgetConfig.center = response.data.options.default.center;
- this.updateConfig(this.widget!, this.widget!.widgetConfig);
- })
- }
- }
-
- 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" @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();
- }
-}