100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Insights in a standalone app (#994)
Martin Peetersc0461e59a447
diff --git a/manager/src/main/java/org/openremote/manager/web/ManagerWebService.java b/manager/src/main/java/org/openremote/manager/web/ManagerWebService.javaindex 811e55d15..525d0a17c 100644--- a/manager/src/main/java/org/openremote/manager/web/ManagerWebService.java+++ b/manager/src/main/java/org/openremote/manager/web/ManagerWebService.java@@ -82,6 +82,7 @@ public class ManagerWebService extends WebService {public static final String OR_ROOT_REDIRECT_PATH_DEFAULT = "/manager";public static final String API_PATH = "/api";public static final String MANAGER_APP_PATH = "/manager";+ public static final String INSIGHTS_APP_PATH = "/insights";public static final String SWAGGER_APP_PATH = "/swagger";public static final String CONSOLE_LOADER_APP_PATH = "/console_loader";public static final String SHARED_PATH = "/shared";@@ -212,6 +213,7 @@ public class ManagerWebService extends WebService {};deploymentHandler.addPrefixPath(MANAGER_APP_PATH, appFileHandler);+ deploymentHandler.addPrefixPath(INSIGHTS_APP_PATH, appFileHandler);deploymentHandler.addPrefixPath(SWAGGER_APP_PATH, appFileHandler);deploymentHandler.addPrefixPath(CONSOLE_LOADER_APP_PATH, appFileHandler);deploymentHandler.addPrefixPath(SHARED_PATH, appFileHandler);diff --git a/manager/src/web/shared/locales/en/or.json b/manager/src/web/shared/locales/en/or.jsonindex c054f9c36..15a182c19 100644--- a/manager/src/web/shared/locales/en/or.json+++ b/manager/src/web/shared/locales/en/or.json@@ -189,7 +189,8 @@"noRuleStateAttributes": "No attributes with 'rule state' or 'agent link' configuration item found","noDatapointsAttributes": "No attributes with 'store data points' or 'agent link' configuration item found","noAttributesToShow": "No attributes found",- "noAttributesConnected": "No attributes connected.",+ "noAttributeConnected": "No attribute connected",+ "noAttributesConnected": "No attributes connected","noDatapointsOrRuleStateAttributes": "No attributes with 'rule state', 'store data points', or 'agent link' configuration item found","copy": "Copy","paste": "Paste",@@ -579,6 +580,7 @@"thresholds": "Thresholds","threshold": "Threshold","noDashboardSelected": "Please select a dashboard on the left",+ "noDashboardSelected-mobile": "Please select a dashboard in the top left menu","noDashboardFound": "No dashboard could be found.","noDashboardWriteAccess": "You don't have access to edit this dashboard.","confirmContinueDashboardModified": "Dashboard has been edited, do you want to discard the changes?",diff --git a/manager/src/web/shared/locales/nl/or.json b/manager/src/web/shared/locales/nl/or.jsonindex 2753b1383..e318266c0 100644--- a/manager/src/web/shared/locales/nl/or.json+++ b/manager/src/web/shared/locales/nl/or.json@@ -189,6 +189,7 @@"noRuleStateAttributes": "Geen attributen met 'rule state' of 'agent link' configuratie item gevonden","noDatapointsAttributes": "Geen attributen met 'store data points' of 'agent link' configuratie item gevonden","noAttributesToShow": "Geen attributen gevonden",+ "noAttributeConnected": "Geen atribuut verbonden","noAttributesConnected": "Geen attributen verbonden","noDatapointsOrRuleStateAttributes": "Geen attributen met 'rule state', 'store data points', of 'agent link' configuratie item gevonden","copy": "Kopiëren",@@ -579,6 +580,7 @@"thresholds": "Drempelwaardes","threshold": "Drempelwaarde","noDashboardSelected": "Selecteer een dashboard aan de linkerkant",+ "noDashboardSelected-mobile": "Selecteer een dashboard in het menu linksboven","noDashboardFound": "Geen dashboard gevonden.","noDashboardWriteAccess": "U heeft geen rechten om dit dashboard aan te passen.","confirmContinueDashboardModified": "Dashboard is aangepast, wijzigingen negeren?",diff --git a/ui/app/dashboard/.appignore b/ui/app/dashboard/.appignoredeleted file mode 100644index e69de29bb..000000000diff --git a/ui/app/dashboard/src/index.ts b/ui/app/dashboard/src/index.tsdeleted file mode 100644index e956c756b..000000000--- a/ui/app/dashboard/src/index.ts+++ /dev/null@@ -1,39 +0,0 @@-import {combineReducers, configureStore} from "@reduxjs/toolkit";-import {- OrApp,- AppConfig,- appReducer,- getRealmQueryParameter,- PageProvider} from "@openremote/or-app";-import {pageDashboardProvider} from "./pages/page-dashboard";----const rootReducer = combineReducers({- app: appReducer-});--type RootState = ReturnType<typeof rootReducer>;--export const store = configureStore({- reducer: rootReducer-});--const orApp = new OrApp(store);--// Configure manager connection and i18next settings-orApp.managerConfig = {- realm: getRealmQueryParameter(),- autoLogin: false-};--export const DefaultPagesConfig: PageProvider<any>[] = [- pageDashboardProvider(store)-];--// Configure app pages and per realm styling/settings-orApp.appConfig = {- pages: [...DefaultPagesConfig],-};--document.body.appendChild(orApp);diff --git a/ui/app/dashboard/src/pages/page-dashboard.ts b/ui/app/dashboard/src/pages/page-dashboard.tsdeleted file mode 100644index 9215c2358..000000000--- a/ui/app/dashboard/src/pages/page-dashboard.ts+++ /dev/null@@ -1,82 +0,0 @@-import {css, html, PropertyValues, TemplateResult, unsafeCSS} from "lit";-import {customElement, query, state} from "lit/decorators.js";-import {AppStateKeyed, Page, PageProvider, router} from "@openremote/or-app";-import {EnhancedStore} from "@reduxjs/toolkit";-import "@openremote/or-dashboard-builder"-import { Dashboard, DashboardTemplate } from "@openremote/model";-import manager from "@openremote/core";-import "@openremote/or-chart";--export function pageDashboardProvider(store: EnhancedStore<AppStateKeyed>): PageProvider<AppStateKeyed> {- return {- name: "dashboard",- routes: [- "dashboard/:id"- ],- pageCreator: () => {- const page = new PageDashboard(store);- return page;- }- };-}--@customElement("page-dashboard")-export class PageDashboard extends Page<AppStateKeyed> {-- @state()- private template: DashboardTemplate;-- @state()- private dashboardId: string;-- @state()- private isLoading: boolean = true;--- get name(): string {- return "dashboard"- }-- static get styles() {- // language=CSS- return [css`- .text {- height: 100%;- width: 100%;- display: flex;- justify-content: center;- align-items: center;- }- `]- }-- fetchDashboard(dashboardId: string) {- manager.rest.api.DashboardResource.get(dashboardId).then((dashboard) => {- this.template = (dashboard.data as Dashboard).template;- this.isLoading = false;- });- }--- stateChanged(state: AppStateKeyed): void {- if(state.app.params && state.app.params.id) {- this.dashboardId = state.app.params.id;- this.fetchDashboard(state.app.params.id);- }- }-- protected render(): TemplateResult {- return html`- ${this.template != undefined ? html`- <or-dashboard-preview .template="${this.template}" .realm="${manager.displayRealm}"- .editMode="${false}" .readonly="${true}" .fullscreen="${true}"- ></or-dashboard-preview>- ` : (this.isLoading ? html`- <span class="text">Loading..</span>- ` : html`- <span class="text">No dashboard found..</span>- `)}- `- }--}diff --git a/ui/app/dashboard/.babelrc b/ui/app/insights/.babelrcsimilarity index 100%rename from ui/app/dashboard/.babelrcrename to ui/app/insights/.babelrcdiff --git a/ui/app/dashboard/.gitignore b/ui/app/insights/.gitignoresimilarity index 100%rename from ui/app/dashboard/.gitignorerename to ui/app/insights/.gitignorediff --git a/ui/app/dashboard/babel.config.js b/ui/app/insights/babel.config.jssimilarity index 100%rename from ui/app/dashboard/babel.config.jsrename to ui/app/insights/babel.config.jsdiff --git a/ui/app/dashboard/build.gradle b/ui/app/insights/build.gradlesimilarity index 100%rename from ui/app/dashboard/build.gradlerename to ui/app/insights/build.gradlediff --git a/ui/app/insights/images/Icon-128.png b/ui/app/insights/images/Icon-128.pngnew file mode 100644index 000000000..ff533dc13Binary files /dev/null and b/ui/app/insights/images/Icon-128.png differdiff --git a/ui/app/insights/images/Icon-144.png b/ui/app/insights/images/Icon-144.pngnew file mode 100644index 000000000..268fcb42fBinary files /dev/null and b/ui/app/insights/images/Icon-144.png differdiff --git a/ui/app/insights/images/Icon-196.png b/ui/app/insights/images/Icon-196.pngnew file mode 100644index 000000000..97a0a93c0Binary files /dev/null and b/ui/app/insights/images/Icon-196.png differdiff --git a/ui/app/insights/images/Icon-256.png b/ui/app/insights/images/Icon-256.pngnew file mode 100644index 000000000..869c157e2Binary files /dev/null and b/ui/app/insights/images/Icon-256.png differdiff --git a/ui/app/insights/images/Icon-48.png b/ui/app/insights/images/Icon-48.pngnew file mode 100644index 000000000..f73176b9bBinary files /dev/null and b/ui/app/insights/images/Icon-48.png differdiff --git a/ui/app/insights/images/Icon-512.png b/ui/app/insights/images/Icon-512.pngnew file mode 100644index 000000000..a64a845a6Binary files /dev/null and b/ui/app/insights/images/Icon-512.png differdiff --git a/ui/app/insights/images/Icon-72.png b/ui/app/insights/images/Icon-72.pngnew file mode 100644index 000000000..f30af07e2Binary files /dev/null and b/ui/app/insights/images/Icon-72.png differdiff --git a/ui/app/insights/images/favicon.ico b/ui/app/insights/images/favicon.iconew file mode 100644index 000000000..041659d88Binary files /dev/null and b/ui/app/insights/images/favicon.ico differdiff --git a/ui/app/dashboard/index.html b/ui/app/insights/index.htmlsimilarity index 100%rename from ui/app/dashboard/index.htmlrename to ui/app/insights/index.htmldiff --git a/ui/app/dashboard/package.json b/ui/app/insights/package.jsonsimilarity index 84%rename from ui/app/dashboard/package.jsonrename to ui/app/insights/package.jsonindex 91ccd26db..651c8948d 100644--- a/ui/app/dashboard/package.json+++ b/ui/app/insights/package.json@@ -1,7 +1,7 @@{- "name": "@openremote/dashboard",+ "name": "@openremote/insights","version": "1.0.0",- "description": "OpenRemote Dashboard Viewer",+ "description": "OpenRemote Insights App","author": "OpenRemote","license": "AGPL-3.0-or-later","private": true,@@ -20,8 +20,8 @@"modelBuild": "npx orutil build","modelWatch": "npx orutil watch","build": "npx cross-env NODE_OPTIONS=--max_old_space_size=4096 webpack --mode production",- "serve": "npx tsc -b --clean && npx shx rm -rf dist && npx orutil build && npx cross-env NODE_OPTIONS=--max_old_space_size=4096 webpack serve --mode development --env port=9001",- "serveNoModelBuild": "npx tsc -b --clean && npx cross-env NODE_OPTIONS=--max_old_space_size=4096 webpack serve --mode development --env port=9001",+ "serve": "npx tsc -b --clean && npx shx rm -rf dist && npx orutil build && npx cross-env NODE_OPTIONS=--max_old_space_size=4096 webpack serve --mode development",+ "serveNoModelBuild": "npx tsc -b --clean && npx cross-env NODE_OPTIONS=--max_old_space_size=4096 webpack serve --mode development","test": "echo \"Error: no test specified\" && exit 1"},"dependencies": {diff --git a/ui/app/insights/src/components/dashboard-menu.ts b/ui/app/insights/src/components/dashboard-menu.tsnew file mode 100644index 000000000..578921e79--- /dev/null+++ b/ui/app/insights/src/components/dashboard-menu.ts@@ -0,0 +1,190 @@+import { html, css, LitElement, TemplateResult } from "lit";+import { customElement, property, query } from "lit/decorators.js";+import {ListItem} from "@openremote/or-mwc-components/or-mwc-list";+import "@openremote/or-mwc-components/or-mwc-drawer";+import {Dashboard} from "@openremote/model";+import {when} from "lit/directives/when.js";+import {i18next} from "@openremote/or-translate";+import { RealmAppConfig } from "@openremote/or-app";+import { OrMwcDrawer } from "@openremote/or-mwc-components/or-mwc-drawer";+import {style} from "../style"++//language=css+const styling = css`+ #list-container {+ display: flex;+ flex-direction: column;+ gap: 16px;+ }+`+export interface DrawerConfig {+ enabled: boolean,+ showHeader: boolean+}++@customElement("dashboard-menu")+export class DashboardMenu extends LitElement {++ @property()+ protected readonly dashboards!: Dashboard[];++ @property() // id of the selected dashboard+ protected readonly selectedId?: string;++ @property()+ protected readonly userId!: string;++ @property()+ protected readonly realmName?: string;++ @property()+ protected readonly realmConfig?: RealmAppConfig;++ @property()+ protected drawerConfig?: DrawerConfig;++ @property()+ protected readonly loading: boolean = false;++ @query("#drawer")+ protected drawer: OrMwcDrawer;++ @query("#drawer-custom-scrim")+ protected drawerScrim: HTMLElement;++ static get styles() {+ return [style, styling];+ }++ // Set defaults if not set yet+ firstUpdated() {+ if(!this.drawerConfig) {+ this.drawerConfig = {+ enabled: true,+ showHeader: true+ }+ }+ }++ /* ------------------------------------------ */++ // PUBLIC METHODS FOR EXTERNAL CONTROL++ // For toggling drawer elsewhere, such as page-insights.ts+ // Returned value is the new status of the Drawer+ public async toggleDrawer(state?: boolean): Promise<boolean> {+ if(state && state == this.drawer.open) {+ return this.drawer.open;+ }+ if(this.drawer.open) {+ this.drawerScrim?.classList.add("drawer-scrim-fadeout");+ this.drawer.toggle();+ await new Promise(r => setTimeout(r, 250)); // one-liner for waiting until fadeout animation is done+ } else {+ this.drawer.toggle();+ }+ this.requestUpdate(); // to reload the component, which removes the drawerScrim we added earlier from the DOM+ this.dispatchEvent(new CustomEvent('toggle', { detail: { value: this.drawer.open }}))+ return this.drawer.open;+ }++ public isDrawerOpen(): boolean {+ return this.drawer?.open;+ }++++ /* -------------------------------------------------------- */++ protected selectDashboard(id: string) {+ this.dispatchEvent(new CustomEvent('change', { detail: { value: id }}));+ }+++ protected render() {+ let headerTemplate;+ if(this.drawerConfig?.showHeader) {+ // header template with inline styling; limitation of injecting html like this.+ headerTemplate = html`+ <div style="display: flex; padding: 13px 16px; border-bottom: 1px solid #E0E0E0; align-items: center; gap: 16px;">+ <img id="logo-mobile" width="34" height="34" src="${this.realmConfig?.logoMobile}" />+ <span style="font-size: 18px; font-weight: bold;">${this.realmName}</span>+ </div>+ `;+ }+ return html`+ ${when(this.drawerConfig?.enabled, () => html`+ <or-mwc-drawer id="drawer" .header="${headerTemplate}" .dismissible="${true}">+ ${getDashboardListTemplate(this.dashboards, this.selectedId, (id: string) => this.selectDashboard(id), this.userId, this.loading)}+ </or-mwc-drawer>+ ${when(this.isDrawerOpen(), () => html`+ <div id="drawer-custom-scrim" @click="${() => this.toggleDrawer(false)}"></div>+ `)}+ `, () => html`+ ${getDashboardListTemplate(this.dashboards, this.selectedId, (id: string) => this.selectDashboard(id), this.userId, this.loading)}+ `)}+ `+ }+}+++/* --------------------------------------------------------------- */++// TEMPLATE RENDERING FUNCTIONS+// Wrote standalone from the component, to allow external use if needed.++export function getDashboardListTemplate(dashboards: Dashboard[], selectedId: string, onSelect: (id: string) => void, userId: string, loading: boolean = false): TemplateResult {+ return html`+ ${when(loading, () => html`+ <or-loading-indicator></or-loading-indicator>+ `, () => {+ const menuItems = getDashboardMenuItems(dashboards, userId);+ return html`+ <div style="padding: 16px 0;">+ <div id="list-container">+ ${when(menuItems[0] == undefined, () => html`+ <span style="width: 100%; text-align: center;">${i18next.t('noDashboardFound')}</span>+ `, () => html`+ ${when(menuItems[0].length > 0, () => html`+ <div>+ <span style="margin-left: 16px;">${i18next.t('dashboard.myDashboards')}</span>+ <or-mwc-list .listItems="${menuItems[0]}" .values="${selectedId}"+ @or-mwc-list-changed="${(ev: CustomEvent) => onSelect(ev.detail[0].value)}"+ ></or-mwc-list>+ </div>+ `)}+ ${when(menuItems[1].length > 0, () => html`+ <div>+ <span style="margin-left: 16px;">${i18next.t('dashboard.createdByOthers')}</span>+ <or-mwc-list .listItems="${menuItems[1]}" .values="${selectedId}"+ @or-mwc-list-changed="${(ev: CustomEvent) => onSelect(ev.detail[0].value)}"+ ></or-mwc-list>+ </div>+ `)}+ `)}+ </div>+ </div>+ `+ })}+ `+}++export function getDashboardMenuItems(dashboards: Dashboard[], userId: string): ListItem[][] {+ const dashboardItems: ListItem[][] = [];+ if(dashboards.length > 0) {+ if(userId) {+ const myDashboards: Dashboard[] = [];+ const otherDashboards: Dashboard[] = [];+ dashboards?.forEach((d) => {+ (d.ownerId == userId) ? myDashboards.push(d) : otherDashboards.push(d);+ });+ [myDashboards, otherDashboards].forEach((array, index) => {+ dashboardItems[index] = [];+ array.sort((a, b) => a.displayName ? a.displayName.localeCompare(b.displayName!) : 0).forEach((d) => {+ dashboardItems[index].push({ icon: "view-dashboard", text: d.displayName, value: d.id })+ })+ })+ }+ }+ return dashboardItems;+}diff --git a/ui/app/insights/src/index.ts b/ui/app/insights/src/index.tsnew file mode 100644index 000000000..0ed19d0e7--- /dev/null+++ b/ui/app/insights/src/index.ts@@ -0,0 +1,121 @@+import {combineReducers, configureStore} from "@reduxjs/toolkit";+import "@openremote/or-app";+import {AppConfig, appReducer, OrApp, PageProvider, RealmAppConfig} from "@openremote/or-app";+import {pageInsightsProvider} from "./pages/page-insights";+import {ManagerAppConfig} from "@openremote/model";++declare const CONFIG_URL_PREFIX: string;++const rootReducer = combineReducers({+ app: appReducer+});++type RootState = ReturnType<typeof rootReducer>;++export const store = configureStore({+ reducer: rootReducer+});++const orApp = new OrApp(store);++export const DefaultRealmConfig: RealmAppConfig = {+ appTitle: "OpenRemote Insights",+};++export const DefaultAppConfig: AppConfig<RootState> = {+ pages: [],+ realms: {+ default: DefaultRealmConfig+ }+};++// Try and load the app config from JSON and if anything is found amalgamate it with default+const configURL = (CONFIG_URL_PREFIX || "") + "/manager_config.json";++fetch(configURL).then(async (result) => {+ if (!result.ok) {+ return DefaultAppConfig;+ }++ return await result.json() as ManagerAppConfig;++}).then((appConfig: ManagerAppConfig) => {++ // Set locales and load path+ if (!appConfig.manager) {+ appConfig.manager = {};+ }++ if (appConfig.loadLocales) {+ appConfig.manager.loadTranslations = ["app", "or"];++ if (!appConfig.manager.translationsLoadPath) {+ appConfig.manager.translationsLoadPath = "/locales/{{lng}}/{{ns}}.json";+ }+ }++ // Add config prefix if defined (used in dev)+ if (CONFIG_URL_PREFIX) {+ if (appConfig.manager.translationsLoadPath) {+ appConfig.manager.translationsLoadPath = CONFIG_URL_PREFIX + appConfig.manager.translationsLoadPath;+ }+ }++ orApp.managerConfig = appConfig.manager;++ orApp.appConfigProvider = (manager) => {++ // Configure app config+ let pages: PageProvider<any>[] = [];+ const orAppConfig: AppConfig<RootState> = {+ pages: pages,+ };++ // Configure realms+ if (!appConfig.realms) {+ orAppConfig.realms = {+ default: {...DefaultRealmConfig}+ };+ } else {+ orAppConfig.realms = {};+ const defaultRealm = appConfig.realms.default ? {...DefaultRealmConfig,...appConfig.realms.default} : DefaultRealmConfig;+ orAppConfig.realms.default = defaultRealm;++ Object.entries(appConfig.realms).forEach(([name, realmConfig]) => {+ orAppConfig.realms[name] = { ...defaultRealm, ...(realmConfig as RealmAppConfig) };+ });+ }++ // Check local storage for set language, otherwise use language set in config+ manager.console.retrieveData("LANGUAGE").then((value: string | undefined) => {+ manager.language = (value ? value : orAppConfig.realms[manager.displayRealm].language);+ }).catch(() => {+ if (orAppConfig.realms[manager.displayRealm]){+ manager.language = orAppConfig.realms[manager.displayRealm].language+ } else if (orAppConfig.realms['default']){+ manager.language = orAppConfig.realms['default'].language+ } else {+ manager.language = 'en'+ }+ })++ // Add config prefix if defined (used in dev)+ if (CONFIG_URL_PREFIX) {+ Object.values(orAppConfig.realms).forEach((realmConfig) => {+ if (typeof (realmConfig.logo) === "string") {+ realmConfig.logo = CONFIG_URL_PREFIX + realmConfig.logo;+ }+ if (typeof (realmConfig.logoMobile) === "string") {+ realmConfig.logoMobile = CONFIG_URL_PREFIX + realmConfig.logoMobile;+ }+ });+ }++ // Add insights page with correct parameters+ orAppConfig.pages.push(pageInsightsProvider(store, orAppConfig.realms))++ return orAppConfig;+ }++ document.body.appendChild(orApp);+});diff --git a/ui/app/insights/src/pages/page-insights.ts b/ui/app/insights/src/pages/page-insights.tsnew file mode 100644index 000000000..7f8f6a58b--- /dev/null+++ b/ui/app/insights/src/pages/page-insights.ts@@ -0,0 +1,226 @@+import {html, TemplateResult} from "lit";+import {customElement, query, property, state} from "lit/decorators.js";+import {AppStateKeyed, Page, router, PageProvider, RealmAppConfig} from "@openremote/or-app";+import {EnhancedStore} from "@reduxjs/toolkit";+import "@openremote/or-dashboard-builder"+import {Dashboard, Realm} from "@openremote/model";+import manager from "@openremote/core";+import "@openremote/or-chart";+import "@openremote/or-attribute-card";+import {showSnackbar} from "@openremote/or-mwc-components/or-mwc-snackbar";+import {i18next} from "@openremote/or-translate";+import {registerWidgetTypes} from "@openremote/or-dashboard-builder";+import "@openremote/or-components/or-loading-indicator";+import {when} from "lit/directives/when.js";+import {guard} from "lit/directives/guard.js";+import {style} from "../style";+import { InputType } from "@openremote/or-mwc-components/or-mwc-input";+import { styleMap } from 'lit/directives/style-map.js';+import "../components/dashboard-menu";+import {DashboardMenu} from "../components/dashboard-menu";++export function pageInsightsProvider(store: EnhancedStore<AppStateKeyed>, realmConfigs: {[p: string]: RealmAppConfig}): PageProvider<AppStateKeyed> {+ return {+ name: "insights",+ routes: [+ "",+ ":id"+ ],+ pageCreator: () => {+ const page = new PageInsights(store);+ page.realmConfig = realmConfigs[manager.displayRealm];+ return page;+ }+ };+}++@customElement("page-insights")+export class PageInsights extends Page<AppStateKeyed> {++ @property()+ public realmConfig?: RealmAppConfig;++ @state()+ private dashboards?: Dashboard[];++ @state()+ private selectedDashboard?: Dashboard;++ @state()+ private activePromises: Promise<any>[] = [];++ @state()+ private _userId?: string;++ @state()+ private realm?: Realm;++ @state()+ private rerenderPending: boolean = false;++ @query('#dashboard-menu')+ private dashboardMenu: DashboardMenu;+++ get name(): string {+ return "insights"+ }++ static get styles() {+ return [style];+ }++ constructor(props) {+ super(props);++ // Register user+ manager.rest.api.UserResource.getCurrent().then((response: any) => {+ this._userId = response.data.id;+ }).catch((ex) => {+ console.error(ex);+ showSnackbar(undefined, i18next.t('errorOccurred'));+ });++ // Load realm data+ manager.rest.api.RealmResource.get(manager.displayRealm).then((response: any) => {+ this.realm = response.data;+ })++ // Register dashboard related utils+ registerWidgetTypes();+ }++ // Before updating, check whether there are dashboards loaded.+ // If not, fetch them from our backend+ shouldUpdate(changedProps): boolean | any {+ if(!this.dashboards && !this.isLoading()) {+ this.fetchAllDashboards();+ }+ return super.shouldUpdate(changedProps);+ }++ // If URL has a dashboard ID when loading, select it immediately.+ stateChanged(state: AppStateKeyed): void {+ if(state.app.params.id != this.selectedDashboard?.id) {+ this.updateComplete.then(async () => {+ await Promise.all(this.activePromises); // await for dashboard fetches+ if(this.dashboards) {+ this.selectDashboard(state.app.params.id, false);+ } else {+ console.error("No dashboards found!");+ }+ });+ }+ }++ // Update URL if another dashboard is selected.+ updated(changedProperties: Map<string, any>) {+ if(changedProperties.has("selectedDashboard")) {+ this._updateRoute();+ }+ }++ // Util method for updating URL+ protected _updateRoute(silent: boolean = true) {+ if(this.selectedDashboard) {+ router.navigate(this.selectedDashboard.id, {+ callHooks: !silent,+ callHandler: !silent+ });+ }+ }++ isLoading(): boolean {+ return this.activePromises.length > 0;+ }+++ /* -------------------- */++ fetchAllDashboards() {+ const realm = manager.displayRealm;+ const promise = manager.rest.api.DashboardResource.getAllRealmDashboards(realm);+ this.activePromises.push(promise);+ promise.then((response) => {+ this.dashboards = response.data;+ }).finally(() => {+ const index = this.activePromises.indexOf(promise, 0);+ if(index > -1) {+ this.activePromises.splice(index, 1);+ this.requestUpdate("activePromises");+ }+ })+ }++ protected selectDashboard(dashboardId?: string, toggleDrawer: boolean = true) {+ const dashboard = this.dashboards.find((dashboard) => dashboard.id == dashboardId);+ if (dashboard) {+ if (toggleDrawer) {+ this.dashboardMenu?.toggleDrawer(false).then(() => {+ this.selectedDashboard = dashboard;+ });+ } else {+ this.selectedDashboard = dashboard;+ }+ }+ }++ protected render(): TemplateResult {+ const pageStyles = {+ display: 'flex',+ flexDirection: 'column',+ pointerEvents: this.dashboardMenu?.isDrawerOpen() ? 'none' : 'auto'+ }+ return html`+ <dashboard-menu id="dashboard-menu" .dashboards="${this.dashboards}" .selectedId="${this.selectedDashboard?.id}"+ .realmName="${this.realm?.displayName}" .realmConfig="${this.realmConfig}" .userId="${this._userId}" .loading="${this.isLoading()}"+ @change="${(ev: CustomEvent) => this.selectDashboard(ev.detail.value)}"+ ></dashboard-menu>+ <div style="flex: 1; ${styleMap(pageStyles)}">+ ${this.getDashboardHeaderTemplate(() => this.dashboardMenu?.toggleDrawer())}+ <div style="flex: 1;">+ ${guard([this.selectedDashboard, this.rerenderPending], () => html`+ ${when(this.selectedDashboard, () => html`+ <or-dashboard-preview style="background: transparent;" .rerenderPending="${this.rerenderPending}"+ .realm="${manager.displayRealm}" .template="${this.selectedDashboard.template}" .editMode="${false}"+ .fullscreen="${true}" .readonly="${true}"+ @rerenderfinished="${() => this.rerenderPending = false}"+ ></or-dashboard-preview>+ `, () => html`+ <div id="dashboard-error-text">+ <span>${i18next.t('noDashboardSelected-mobile')}</span>+ </div>+ `)}+ `)}+ </div>+ </div>+ `;+ }++++ /* ------------------------------------------------------------ */+++ protected getDashboardHeaderTemplate(onopen: (ev: Event) => void): TemplateResult {+ return html`+ <div id="fullscreen-header">+ <div id="fullscreen-header-wrapper">+ <div>+ <or-mwc-input type="${InputType.BUTTON}" icon="menu" @or-mwc-input-changed="${onopen}"></or-mwc-input>+ </div>+ <div id="fullscreen-header-title">+ <span>${this.selectedDashboard?.displayName}</span>+ </div>+ <div>+ <div>+ <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>+ </div>+ </div>+ </div>+ </div>+ `+ }+}diff --git a/ui/app/insights/src/style.ts b/ui/app/insights/src/style.tsnew file mode 100644index 000000000..b5012bff2--- /dev/null+++ b/ui/app/insights/src/style.ts@@ -0,0 +1,83 @@+import { DefaultColor3 } from "@openremote/core";+import { css, unsafeCSS } from "lit";++// language=CSS+export const style = css`++ @media only screen and (max-width: 768px){+ .hideMobile {+ display: none !important;+ }+ .fullWidthOnMobile {+ flex: 1 !important;+ }+ }+ @media only screen and (min-width: 769px){+ .showMobile {+ display: none !important;+ }+ }++ /* Header related styling */+ #fullscreen-header-wrapper {+ min-height: 36px;+ padding: 6px;+ display: flex;+ align-items: center;+ justify-content: space-between;+ }+ #fullscreen-header-title {+ font-size: 18px;+ font-weight: bold;+ color: var(--or-app-color3, ${unsafeCSS(DefaultColor3)});+ }+ #fullscreen-header-title > or-mwc-input {+ margin-right: 4px;+ --or-icon-fill: ${unsafeCSS(DefaultColor3)};+ }+ #fullscreen-header-actions {+ flex: 1 1 auto;+ text-align: right;+ }+ #fullscreen-header-actions-content {+ display: flex;+ flex-direction: row;+ align-items: center;+ float: right;+ }+ #dashboard-error-text {+ display: flex;+ height: 100%;+ justify-content: center;+ align-items: center;+ }+++ /* Drawer related styling */+ #drawer-custom-scrim {+ position: absolute;+ width: 100%;+ height: 100%;+ z-index: 1;+ animation: bgColorFade 0.3s ease-in-out 0s forwards;+ }+ @keyframes bgColorFade {+ 0% {+ background-color: rgba(0, 0, 0, 0);+ }+ 100% {+ background-color: rgba(0, 0, 0, 0.32);+ }+ }+ .drawer-scrim-fadeout {+ animation: bgColorFadeOut 0.2s ease-in-out 0s forwards !important;+ }+ @keyframes bgColorFadeOut {+ 0% {+ background-color: rgba(0, 0, 0, 0.32);+ }+ 100% {+ background-color: rgba(0, 0, 0, 0);+ }+ }+`diff --git a/ui/app/dashboard/tsconfig.json b/ui/app/insights/tsconfig.jsonsimilarity index 100%rename from ui/app/dashboard/tsconfig.jsonrename to ui/app/insights/tsconfig.jsondiff --git a/ui/app/dashboard/webpack.config.js b/ui/app/insights/webpack.config.jssimilarity index 97%rename from ui/app/dashboard/webpack.config.jsrename to ui/app/insights/webpack.config.jsindex 528f9ed14..0a20c7142 100644--- a/ui/app/dashboard/webpack.config.js+++ b/ui/app/insights/webpack.config.js@@ -47,7 +47,7 @@ module.exports = (env, argv) => {// Add a custom base URL to resolve the config dir to the path of the dev server not rootconfig.plugins.push(new webpack.DefinePlugin({- CONFIG_URL_PREFIX: JSON.stringify(IS_DEV_SERVER && customConfigDir ? "/dashboard" : "")+ CONFIG_URL_PREFIX: JSON.stringify(IS_DEV_SERVER && customConfigDir ? "/insights" : "")}));diff --git a/ui/component/or-attribute-card/src/index.ts b/ui/component/or-attribute-card/src/index.tsindex 9f5f42f9c..625aef27f 100644--- a/ui/component/or-attribute-card/src/index.ts+++ b/ui/component/or-attribute-card/src/index.ts@@ -358,7 +358,7 @@ export class OrAttributeCard extends LitElement {${this.shouldShowControls() ? html`<or-mwc-input class="button" .type="${InputType.BUTTON}" label="${i18next.t("selectAttribute")}" icon="plus" @or-mwc-input-changed="${() => this._openDialog("editAttribute")}"></or-mwc-input>` : html`- <span>${i18next.t('noAttributesConnected')}</span>+ <span>${i18next.t('noAttributeConnected')}</span>`}</div></div>diff --git a/ui/component/or-chart/src/index.ts b/ui/component/or-chart/src/index.tsindex 2a9e8ed34..4e306c270 100644--- a/ui/component/or-chart/src/index.ts+++ b/ui/component/or-chart/src/index.ts@@ -331,7 +331,6 @@ const style = css`}#container {- background-color: black;flex-direction: column;}@@ -1070,7 +1069,10 @@ export class OrChart extends translate(i18next)(LitElement) {query.toTimestamp = this._endOfPeriod;if(query.type == 'lttb') {- query.amountOfPoints = Math.round(this._chartElem.clientWidth / 10); // set amount of datapoints based on current chart width.+ if(this._chartElem.clientWidth == 0) {+ console.error("Could not grab width of the Chart for estimating amount of datapoints. Using 10 points instead.")+ }+ query.amountOfPoints = (this._chartElem.clientWidth == 0) ? 10 : Math.round(this._chartElem.clientWidth / 10); // set amount of datapoints based on current chart width.} else if(query.type == 'interval') {const diffInHours = (this.datapointQuery.toTimestamp! - this.datapointQuery.fromTimestamp!) / 1000 / 60 / 60;const intervalArr = this._getInterval(diffInHours);diff --git a/ui/component/or-dashboard-builder/src/index.ts b/ui/component/or-dashboard-builder/src/index.tsindex ee7fdf86d..b3fe3e0b5 100644--- a/ui/component/or-dashboard-builder/src/index.ts+++ b/ui/component/or-dashboard-builder/src/index.ts@@ -209,6 +209,12 @@ export function getActivePreset(gridWidth: number, presets: DashboardScreenPrese}export const widgetTypes: Map<string, OrWidgetEntity> = new Map<string, OrWidgetEntity>();+export function registerWidgetTypes() {+ widgetTypes.set("linechart", new OrChartWidget());+ widgetTypes.set("kpi", new OrKpiWidget());+ widgetTypes.set("gauge", new OrGaugeWidget());+ widgetTypes.set("map", new OrMapWidget());+}@customElement("or-dashboard-builder")export class OrDashboardBuilder extends LitElement {@@ -284,10 +290,7 @@ export class OrDashboardBuilder extends LitElement {this.hasChanged = false;this.rerenderPending = false;- this.registerWidgetType("linechart", new OrChartWidget());- this.registerWidgetType("kpi", new OrKpiWidget());- this.registerWidgetType("gauge", new OrGaugeWidget());- this.registerWidgetType("map", new OrMapWidget());+ registerWidgetTypes();this.updateComplete.then(async () => {await this.updateDashboards(this.realm!);@@ -661,10 +664,6 @@ export class OrDashboardBuilder extends LitElement {`}- registerWidgetType(name: string, widget: OrWidgetEntity) {- widgetTypes.set(name, widget);- }-/* ======================== */}diff --git a/ui/component/or-dashboard-builder/src/or-dashboard-preview.ts b/ui/component/or-dashboard-builder/src/or-dashboard-preview.tsindex 3f014eee1..7256a77dd 100644--- a/ui/component/or-dashboard-builder/src/or-dashboard-preview.ts+++ b/ui/component/or-dashboard-builder/src/or-dashboard-preview.ts@@ -4,21 +4,16 @@ import {customElement, property, state} from "lit/decorators.js";import {style} from "./style";import "./or-dashboard-widget";import {debounce} from "lodash";-import {- DashboardGridItem,- DashboardScalingPreset,- DashboardScreenPreset,- DashboardTemplate,- DashboardWidget-} from "@openremote/model";-import { getActivePreset } from "./index";+import {DashboardGridItem, DashboardScalingPreset, DashboardScreenPreset, DashboardTemplate, DashboardWidget} from "@openremote/model";+import {getActivePreset} from "./index";import {InputType, OrInputChangedEvent} from "@openremote/or-mwc-components/or-mwc-input";+import "@openremote/or-components/or-loading-indicator";import {repeat} from 'lit/directives/repeat.js';import {GridItemHTMLElement, GridStack, GridStackElement, GridStackNode} from "gridstack";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 {i18next} from "@openremote/or-translate";+import {when} from "lit/directives/when.js";+import {cache} from "lit/directives/cache.js";import {OrDashboardEngine} from "./or-dashboard-engine";// TODO: Add webpack/rollup to build so consumers aren't forced to use the same tooling@@ -28,6 +23,15 @@ const extracss = require('gridstack/dist/gridstack-extra.css');//language=cssconst editorStyling = css`+ #loadingContainer {+ position: absolute;+ width: 100%;+ height: 100%;+ display: flex;+ justify-content: center;+ align-items: center;+ }+#view-options {padding: 24px;display: flex;@@ -202,6 +206,9 @@ export class OrDashboardPreview extends LitElement {@state()private rerenderActive: boolean = false;+ @state()+ private isLoading: boolean = false;+/* ------------------------------------------- */@@ -239,6 +246,26 @@ export class OrDashboardPreview extends LitElement {&& (JSON.stringify((changedProperties.get('latestChanges') as any)?.oldValue)) == (JSON.stringify((changedProperties.get('latestChanges') as any)?.newValue))) {changed.delete('latestChanges');}++ // Do not update UI if the preview size has changed while being fullscreen,+ // since it is only used when in "responsive mode".+ if(this.fullscreen && changedProperties.has('previewWidth')) {+ changed.delete('previewWidth');+ }+ if(this.fullscreen && changedProperties.has('previewHeight')) {+ 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 anythingchanged.delete('latestDragWidgetStart');@@ -309,15 +336,6 @@ export class OrDashboardPreview extends LitElement {}}- if(changedProperties.has("rerenderPending")) {- if(this.rerenderPending) {- this.setupGrid(true, true).then(() => {- this.rerenderPending = false;- this.dispatchEvent(new CustomEvent("rerenderfinished"));- });- }- }-// When parent component requests a forced rerenderif(changedProperties.has("rerenderActive")) {if(this.rerenderActive) {@@ -331,6 +349,7 @@ export class OrDashboardPreview extends LitElement {// Main setup Grid method (often used)async setupGrid(recreate: boolean, force: boolean = false) {+ this.isLoading = true;await this.waitUntil((_: any) => this.shadowRoot?.getElementById("gridElement") != null)let gridElement = this.shadowRoot?.getElementById("gridElement");if(gridElement != null) {@@ -418,6 +437,7 @@ export class OrDashboardPreview extends LitElement {setTimeout(() => { this.latestDragWidgetStart = undefined; }, 200);});}+ this.isLoading = false;}@@ -461,6 +481,10 @@ export class OrDashboardPreview extends LitElement {}}+ isPreviewVisible(): boolean {+ return !this.isLoading && this.activePreset?.scalingPreset != DashboardScalingPreset.BLOCK_DEVICE;+ }+// Renderprotected render() {@@ -478,7 +502,7 @@ export class OrDashboardPreview extends LitElement {let screenPresets = this.template?.screenPresets?.map(s => s.displayName);screenPresets?.push(customPreset);return html`- <div id="buildingArea" style="display: flex; flex-direction: column; height: 100%;" @click="${(event: PointerEvent) => { if((event.composedPath()[1] as HTMLElement).id === 'buildingArea') { this.onGridItemClick(undefined); }}}">+ <div id="buildingArea" style="display: flex; flex-direction: column; height: 100%; position: relative;" @click="${(event: PointerEvent) => { if((event.composedPath()[1] as HTMLElement).id === 'buildingArea') { this.onGridItemClick(undefined); }}}">${this.editMode && !this.fullscreen ? html`<div id="view-options"><or-mwc-input id="fit-btn" type="${InputType.BUTTON}" icon="fit-to-screen"@@ -508,15 +532,21 @@ export class OrDashboardPreview extends LitElement {</div>` : html`<div id="container" style="justify-content: center; position: relative;">- ${this.activePreset?.scalingPreset == DashboardScalingPreset.BLOCK_DEVICE ? html`+ ${when(this.isLoading, () => html`<div style="position: absolute; z-index: 3; height: 100%; display: flex; align-items: center;">- <span>${i18next.t('dashboard.deviceNotSupported')}</span>+ <or-loading-indicator></or-loading-indicator></div>- ` : undefined}- <div class="${this.fullscreen ? 'maingridContainer__fullscreen' : 'maingridContainer'}">+ `, () => html`+ ${this.activePreset?.scalingPreset == DashboardScalingPreset.BLOCK_DEVICE ? html`+ <div style="position: absolute; z-index: 3; height: 100%; display: flex; align-items: center;">+ <span>${i18next.t('dashboard.deviceNotSupported')}</span>+ </div>+ ` : undefined}+ `)}+ <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) }}}"- style="width: ${this.previewWidth}; height: ${this.previewHeight}; visibility: ${this.activePreset?.scalingPreset == DashboardScalingPreset.BLOCK_DEVICE ? 'hidden' : 'visible'}; zoom: ${this.editMode && !this.fullscreen ? this.previewZoom : 'normal'}; ${this.editMode && !this.fullscreen ? ('-moz-transform: scale(' + this.previewZoom + ')') : undefined}; transform-origin: top;"+ 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;">diff --git a/ui/component/or-dashboard-builder/src/or-dashboard-widget.ts b/ui/component/or-dashboard-builder/src/or-dashboard-widget.tsindex 29a00424d..86abb59db 100644--- a/ui/component/or-dashboard-builder/src/or-dashboard-widget.ts+++ b/ui/component/or-dashboard-builder/src/or-dashboard-widget.ts@@ -1,5 +1,4 @@import {DashboardWidget } from "@openremote/model";-import { InputType } from "@openremote/or-mwc-components/or-mwc-input";import { i18next } from "@openremote/or-translate";import {css, html, LitElement, TemplateResult } from "lit";import { customElement, property, query, state } from "lit/decorators.js";@@ -52,7 +51,7 @@ export class OrDashboardWidget extends LitElement {// 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!);+ const widgetType = widgetTypes.get(this.widget.widgetTypeId);if(widgetType) {this.widget.widgetConfig = widgetType.verifyConfigSpec(this.widget);}@@ -108,7 +107,7 @@ export class OrDashboardWidget extends LitElement {const _widget = Object.assign({}, widget);if(_widget.gridItem) {- const widgetEntity = widgetTypes.get(widget.widgetTypeId!);+ const widgetEntity = widgetTypes.get(widget.widgetTypeId);return widgetEntity!.getWidgetHTML(this.widget!, this.editMode!, this.realm!);}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.tsindex 2fc04840e..eeb01cc29 100644--- a/ui/component/or-dashboard-builder/src/widgets/or-chart-widget.ts+++ b/ui/component/or-dashboard-builder/src/widgets/or-chart-widget.ts@@ -53,7 +53,7 @@ export class OrChartWidget implements OrWidgetEntity {readonly MIN_PIXEL_HEIGHT: number = 0;getDefaultConfig(widget: DashboardWidget): ChartWidgetConfig {- const preset = "lastHour"+ const preset = "last24Hours"const dateFunc = timePresetOptions.get(preset);const dates = dateFunc!(new Date());return {@@ -170,7 +170,7 @@ export class OrChartWidgetContent extends LitElement {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;+ return foundAsset && foundAsset.attributes ? [assetIndex, foundAsset.attributes[attrRef.name]] : undefined;}).filter((indexAndAttr: any) => !!indexAndAttr) as [number, Attribute<any>][];});}@@ -212,9 +212,9 @@ export class OrChartWidgetContent extends LitElement {// Generating random coordinates on the chartlet data: any[] = [];- const cached: { period: any, data: any[] } | undefined = this.cachedMockData?.get(widget.id!);+ 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!;+ data = this.cachedMockData?.get(widget.id)!.data!;} else {widget.widgetConfig?.attributeRefs?.forEach((_attrRef: AttributeRef) => {let valueEntries: any[] = [];@@ -229,7 +229,7 @@ export class OrChartWidgetContent extends LitElement {}data.push(valueEntries);});- this.cachedMockData?.set(widget.id!, { period: widget.widgetConfig?.period, data: data });+ this.cachedMockData?.set(widget.id, { period: widget.widgetConfig?.period, data: data });}// Making a line for each attributediff --git a/ui/component/or-dashboard-builder/src/widgets/or-gauge-widget.ts b/ui/component/or-dashboard-builder/src/widgets/or-gauge-widget.tsindex 3a2f37020..4d7bfef1b 100644--- a/ui/component/or-dashboard-builder/src/widgets/or-gauge-widget.ts+++ b/ui/component/or-dashboard-builder/src/widgets/or-gauge-widget.ts@@ -87,7 +87,7 @@ export class OrGaugeWidgetContent extends LitElement {}, () => {return html`<div style="height: 100%; display: flex; justify-content: center; align-items: center;">- <span>${i18next.t('noAttributesConnected')}</span>+ <span>${i18next.t('noAttributeConnected')}</span></div>`})}diff --git a/ui/component/or-gauge/src/index.ts b/ui/component/or-gauge/src/index.tsindex 81d0c755c..77caa83a0 100644--- a/ui/component/or-gauge/src/index.ts+++ b/ui/component/or-gauge/src/index.ts@@ -15,10 +15,18 @@ const styling = css`flex-direction: column;}- .chart-wrapper {+ #chart-wrapper {position: relative;- /*flex: 1;*/width: 100%;+ height: 100%;+ flex-direction: column;+ justify-content: center;+ align-items: center;+ }+ #chart-container {+ display: flex;+ justify-content: center;+ align-items: center;}#chart {@@ -70,6 +78,9 @@ const styling = css`.main-number.xl, .main-number-unit.xl {font-size: 42px;}+ .main-number.unknown, .main-number-unit.unknown {+ font-size: unset;+ }`export interface OrGaugeConfig {attributeRef?: AttributeRef;@@ -117,9 +128,6 @@ export class OrGauge extends LitElement {@property({type: String})public realm?: string;- @property()- private mainValueSize: "xs" | "s" | "m" | "l" | "xl" = "m";-@state()protected loading: boolean = false;@@ -127,9 +135,18 @@ export class OrGauge extends LitElement {@state()private gauge?: Gauge;+ @state()+ private gaugeSize?: { width: number, height: number }+@query("#chart")private _gaugeElem!: HTMLCanvasElement;+ @query("#chart-wrapper")+ private _wrapperElem!: HTMLElement;++ @query("#details-container")+ private _detailsElem!: HTMLElement;+private resizeObserver?: ResizeObserver;@@ -138,26 +155,37 @@ export class OrGauge extends LitElement {if(!this.config) {this.config = this.getDefaultConfig();}+ // Register observer when gauge size changesthis.updateComplete.then(() => {this.resizeObserver = new ResizeObserver(debounce((entries: ResizeObserverEntry[]) => {- this.setupGauge(); // recreate gauge since the library is not 100% responsive.- const gaugeSize = entries[0].devicePixelContentBoxSize[0].blockSize; // since gauge elem width == value elem width- this.setLabelSize(gaugeSize);+ const size = entries[0].contentRect;+ this.gaugeSize = {+ width: size.width,+ height: size.height+ }+ this.updateComplete.then(() => {+ this.setupGauge(); // recreate gauge since the library is not 100% responsive.+ });}, 200))- this.resizeObserver.observe(this.shadowRoot!.getElementById('chart')!);+ this.resizeObserver.observe(this._wrapperElem);})}- updated(changedProperties: Map<string, any>) {- if(changedProperties.has('value')) {- this.gauge?.set(this.value != null ? this.value : NaN);- }- if(changedProperties.has('assetAttribute')) {+ // Processing changes before update, to prevent extra render+ willUpdate(changedProps: Map<string, any>) {+ if(changedProps.has('assetAttribute')) {const attr = this.assetAttribute![1];- const attributeDescriptor = AssetModelUtil.getAttributeDescriptor(attr.name!, this.asset!.type!);+ const attributeDescriptor = AssetModelUtil.getAttributeDescriptor(attr.name, this.asset!.type);this.unit = Util.resolveUnits(Util.getAttributeUnits(attr, attributeDescriptor, this.asset!.type));this.value = attr.value != null ? attr.value : NaN;}+ }++ // After render took place...+ updated(changedProperties: Map<string, any>) {+ if(changedProperties.has('value')) {+ this.gauge?.set(this.value != null ? this.value : NaN);+ }if(changedProperties.has('attrRef')) {if(this.attrRef) {this.loadData(this.attrRef);@@ -216,32 +244,51 @@ export class OrGauge extends LitElement {}}- setLabelSize(blockSize: number) {- if(blockSize < 60) {- this.mainValueSize = "s";- } else if(blockSize < 100) {- this.mainValueSize = "m";- } else if(blockSize < 200) {- this.mainValueSize = "l"+ getGaugeWidth(gaugeSize?: { width: number, height: number }, includeLabelHeight: boolean = true): string {+ if(!gaugeSize) {+ return "unset"+ }+ const width = gaugeSize.width;+ const height = (includeLabelHeight ? (gaugeSize.height - this._detailsElem.clientHeight) : gaugeSize.height) * 1.5;+ return Math.min(width, height) + "px";+ }+ shouldShowLabel(gaugeSize: { width: number, height: number }): boolean {+ return (gaugeSize.width > 70) && (gaugeSize.height > 100);+ }+ getLabelSize(width: number): "s" | "m" | "l" | "xl" {+ if(width < 120) {+ return "s";+ } else if(width < 240) {+ return "m";+ } else if(width < 320) {+ return "l"} else {- this.mainValueSize = "xl"+ return "xl"}}render() {const formattedVal = (this.value != null ? +this.value.toFixed(this.decimals) : NaN); // + operator prevents str return++ // Set width/height values based on size+ const showLabel = this.gaugeSize ? this.shouldShowLabel(this.gaugeSize) : true;+ const labelSize = showLabel && this.gaugeSize ? this.getLabelSize(this.gaugeSize.width) : "unknown"+ const gaugeWidth = this.getGaugeWidth(this.gaugeSize, showLabel);+return html`<div style="position: relative; height: 100%; width: 100%;">- <div class="chart-wrapper" style="display: ${this.loading ? 'none' : 'flex'}; flex-direction: column; justify-content: center; height: 100%;">- <div style="flex: 0 0 0;">+ <div id="chart-wrapper" style="display: ${this.loading ? 'none' : 'flex'};">+ <div id="chart-container" style="flex: 0 0 0; width: ${gaugeWidth};"><canvas id="chart"></canvas></div>- <div>- <div class="mainvalue-wrapper">- <span class="main-number-icon">${this.asset ? getAssetDescriptorIconTemplate(AssetModelUtil.getAssetDescriptor(this.asset.type)) : ""}</span>- <span class="main-number ${this.mainValueSize}">${formattedVal}</span>- <span class="main-number-unit ${this.mainValueSize}">${this.unit ? this.unit : ""}</span>- </div>+ <div id="details-container">+ ${showLabel ? html`+ <div class="mainvalue-wrapper">+ <span class="main-number-icon">${this.asset ? getAssetDescriptorIconTemplate(AssetModelUtil.getAssetDescriptor(this.asset.type)) : ""}</span>+ <span class="main-number ${labelSize}">${formattedVal}</span>+ <span class="main-number-unit ${labelSize}">${this.unit ? this.unit : ""}</span>+ </div>+ ` : undefined}</div></div></div>@@ -252,12 +299,12 @@ export class OrGauge extends LitElement {}async loadData(attrRef: AttributeRef) {- const response = await manager.rest.api.AssetResource.queryAssets({ ids: [attrRef.id!] });+ const response = await manager.rest.api.AssetResource.queryAssets({ ids: [attrRef.id] });const assets = response.data;const assetAttributes = [attrRef].map((attrRef) => {const assetIndex = assets.findIndex((asset) => asset.id === attrRef.id);const asset = assetIndex >= 0 ? assets[assetIndex] : undefined;- return asset && asset.attributes ? [assetIndex, asset.attributes[attrRef.name!]] : undefined;+ return asset && asset.attributes ? [assetIndex, asset.attributes[attrRef.name]] : undefined;}).filter((indexAndAttr) => !!indexAndAttr) as [number, Attribute<any>][];this.asset = assets[0];@@ -287,13 +334,4 @@ export class OrGauge extends LitElement {}}}-- // Wait until function that waits until a boolean returns differently- waitUntil(conditionFunction: any) {- const poll = (resolve: any) => {- if(conditionFunction()) resolve();- else setTimeout((_: any) => poll(resolve), 400);- }- return new Promise(poll);- }}diff --git a/ui/component/or-mwc-components/src/or-mwc-drawer.ts b/ui/component/or-mwc-components/src/or-mwc-drawer.tsindex 190ce4f7a..568de240d 100644--- a/ui/component/or-mwc-components/src/or-mwc-drawer.ts+++ b/ui/component/or-mwc-components/src/or-mwc-drawer.ts@@ -58,9 +58,10 @@ export class OrMwcDrawer extends LitElement {}protected render() {-+ const isModal = !this.dismissible;const classes = {"mdc-drawer--dismissible": this.dismissible,+ "mdc-drawer--modal": isModal,"transparent": this.transparent};diff --git a/yarn.lock b/yarn.lockindex 7cbf699ef..99b547679 100644--- a/yarn.lock+++ b/yarn.lock@@ -2176,15 +2176,6 @@ __metadata:languageName: unknownlinkType: soft-"@openremote/dashboard@workspace:ui/app/dashboard":- version: 0.0.0-use.local- resolution: "@openremote/dashboard@workspace:ui/app/dashboard"- dependencies:- "@openremote/or-app": ^1.1.0- "@openremote/util": "workspace:*"- languageName: unknown- linkType: soft-"@openremote/demo-core@^1.0.4, @openremote/demo-core@workspace:ui/demo/demo-core":version: 0.0.0-use.localresolution: "@openremote/demo-core@workspace:ui/demo/demo-core"@@ -2258,6 +2249,15 @@ __metadata:languageName: unknownlinkType: soft+"@openremote/insights@workspace:ui/app/insights":+ version: 0.0.0-use.local+ resolution: "@openremote/insights@workspace:ui/app/insights"+ dependencies:+ "@openremote/or-app": ^1.1.0+ "@openremote/util": "workspace:*"+ languageName: unknown+ linkType: soft+"@openremote/manager@workspace:ui/app/manager":version: 0.0.0-use.localresolution: "@openremote/manager@workspace:ui/app/manager"