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
Support for public available dashboards (#1054)
Martin Peeters9d20afb69d20
diff --git a/manager/src/main/java/org/openremote/manager/dashboard/DashboardResourceImpl.java b/manager/src/main/java/org/openremote/manager/dashboard/DashboardResourceImpl.javaindex 08eff7b0b..b252c2080 100644--- a/manager/src/main/java/org/openremote/manager/dashboard/DashboardResourceImpl.java+++ b/manager/src/main/java/org/openremote/manager/dashboard/DashboardResourceImpl.java@@ -1,18 +1,19 @@package org.openremote.manager.dashboard;+import jakarta.ws.rs.WebApplicationException;import org.openremote.container.message.MessageBrokerService;import org.openremote.container.timer.TimerService;import org.openremote.manager.security.ManagerIdentityService;import org.openremote.manager.web.ManagerWebResource;+import org.openremote.model.Constants;import org.openremote.model.dashboard.Dashboard;-import org.openremote.model.dashboard.DashboardResource;import org.openremote.model.dashboard.DashboardAccess;+import org.openremote.model.dashboard.DashboardResource;import org.openremote.model.http.RequestParams;+import org.openremote.model.security.ClientRole;import org.openremote.model.util.ValueUtil;-import jakarta.ws.rs.WebApplicationException;--import java.util.List;+import java.util.Collections;import static jakarta.ws.rs.core.Response.Status.*;@@ -30,31 +31,69 @@ public class DashboardResourceImpl extends ManagerWebResource implements Dashboa@Overridepublic Dashboard[] getAllRealmDashboards(RequestParams requestParams, String realm) {-+ boolean publicOnly = true;+ if(realm == null) {+ throw new WebApplicationException(BAD_REQUEST);+ }try {+ // Realm should be enabled. Also takes unauthenticated users into count.if(!isRealmActiveAndAccessible(realm)) {throw new WebApplicationException(FORBIDDEN);}- return this.dashboardStorageService.findAllOfRealm(realm, getUserId());+ // if not authenticated, or having no INSIGHTS access, only fetch public dashboards+ if(isAuthenticated()) {+ publicOnly = (!hasResourceRole(ClientRole.READ_INSIGHTS.getValue(), Constants.KEYCLOAK_CLIENT_ID));+ }+ return this.dashboardStorageService.query(null, realm, getUserId(), publicOnly, false);} catch (IllegalStateException ex) {- throw new WebApplicationException(ex, BAD_REQUEST);+ ex.printStackTrace();+ throw new WebApplicationException(ex, INTERNAL_SERVER_ERROR);}}@Overridepublic Dashboard get(RequestParams requestParams, String dashboardId) {- return this.dashboardStorageService.get(dashboardId);+ boolean publicOnly = true;+ String realm = getRequestRealmName();+ if(realm == null) {+ throw new WebApplicationException(BAD_REQUEST);+ }+ try {+ // Realm should be enabled. Also takes unauthenticated users into count.+ if(!isRealmActiveAndAccessible(realm)) {+ throw new WebApplicationException(FORBIDDEN);+ }+ // if not authenticated, or having no INSIGHTS access, only take public dashboards into count+ if(isAuthenticated()) {+ publicOnly = (!hasResourceRole(ClientRole.READ_INSIGHTS.getValue(), Constants.KEYCLOAK_CLIENT_ID));+ }+ Dashboard[] dashboards = this.dashboardStorageService.query(Collections.singletonList(dashboardId), realm, getUserId(), publicOnly, false);+ if(dashboards.length == 0) {+ if(this.dashboardStorageService.exists(dashboardId, realm)) {+ throw new WebApplicationException(FORBIDDEN); // when no dashboard returned from query, but it does exist.+ } else {+ throw new WebApplicationException(NOT_FOUND); // aka it does not exist+ }+ }+ return dashboards[0]; // only return first entry++ } catch (IllegalStateException ex) {+ ex.printStackTrace();+ throw new WebApplicationException(ex, INTERNAL_SERVER_ERROR);+ }}@Overridepublic Dashboard create(RequestParams requestParams, Dashboard dashboard) {+ String realm = dashboard.getRealm();+ if(realm == null) {+ throw new WebApplicationException(BAD_REQUEST);+ }+ if(!isRealmActiveAndAccessible(dashboard.getRealm())) {+ throw new WebApplicationException(FORBIDDEN);+ }try {-- // Check if access to realm- if(!isRealmActiveAndAccessible(dashboard.getRealm())) {- throw new WebApplicationException(FORBIDDEN);- }dashboard.setOwnerId(getUserId());dashboard.setViewAccess(DashboardAccess.SHARED);dashboard.setEditAccess(DashboardAccess.SHARED);@@ -68,14 +107,18 @@ public class DashboardResourceImpl extends ManagerWebResource implements Dashboa}@Override- public void update(RequestParams requestParams, Dashboard dashboard) {+ public Dashboard update(RequestParams requestParams, Dashboard dashboard) {+ String realm = dashboard.getRealm();+ if(realm == null) {+ throw new WebApplicationException(BAD_REQUEST);+ }+ if(!isRealmActiveAndAccessible(realm)) {+ throw new WebApplicationException(FORBIDDEN);+ }try {-- // Check if access to realm- if(!isRealmActiveAndAccessible(dashboard.getRealm())) {- throw new WebApplicationException(FORBIDDEN);- }- this.dashboardStorageService.update(ValueUtil.clone(dashboard), getUserId());+ return this.dashboardStorageService.update(ValueUtil.clone(dashboard), realm, getUserId());+ } catch (IllegalArgumentException ex) {+ throw new WebApplicationException(ex, NOT_FOUND);} catch (IllegalStateException ex) {ex.printStackTrace();throw new WebApplicationException(ex, INTERNAL_SERVER_ERROR);@@ -83,9 +126,18 @@ public class DashboardResourceImpl extends ManagerWebResource implements Dashboa}@Override- public void delete(RequestParams requestParams, List<String> fields) {+ public void delete(RequestParams requestParams, String dashboardId) {+ String realm = getRequestRealmName();+ if(realm == null) {+ throw new WebApplicationException(BAD_REQUEST);+ }+ if(!isRealmActiveAndAccessible(realm)) {+ throw new WebApplicationException(FORBIDDEN);+ }try {- this.dashboardStorageService.delete(fields, getUserId());+ this.dashboardStorageService.delete(dashboardId, realm, getUserId());+ } catch (IllegalArgumentException ex) {+ throw new WebApplicationException(ex, NOT_FOUND);} catch (IllegalStateException ex) {ex.printStackTrace();throw new WebApplicationException(ex, INTERNAL_SERVER_ERROR);diff --git a/manager/src/main/java/org/openremote/manager/dashboard/DashboardStorageService.java b/manager/src/main/java/org/openremote/manager/dashboard/DashboardStorageService.javaindex f50452134..7d9edd5c4 100644--- a/manager/src/main/java/org/openremote/manager/dashboard/DashboardStorageService.java+++ b/manager/src/main/java/org/openremote/manager/dashboard/DashboardStorageService.java@@ -1,5 +1,10 @@package org.openremote.manager.dashboard;+import jakarta.persistence.Query;+import jakarta.persistence.criteria.CriteriaBuilder;+import jakarta.persistence.criteria.CriteriaQuery;+import jakarta.persistence.criteria.Predicate;+import jakarta.persistence.criteria.Root;import org.apache.camel.builder.RouteBuilder;import org.openremote.container.message.MessageBrokerService;import org.openremote.container.persistence.PersistenceService;@@ -11,19 +16,7 @@ import org.openremote.model.ContainerService;import org.openremote.model.dashboard.Dashboard;import org.openremote.model.dashboard.DashboardAccess;-import jakarta.persistence.Query;-import jakarta.persistence.TypedQuery;-import jakarta.persistence.criteria.CriteriaBuilder;-import jakarta.persistence.criteria.CriteriaQuery;-import jakarta.persistence.criteria.Predicate;-import jakarta.persistence.criteria.Root;-import jakarta.ws.rs.WebApplicationException;-import java.util.ArrayList;-import java.util.Collection;-import java.util.List;--import static jakarta.ws.rs.core.Response.Status.FORBIDDEN;-import static jakarta.ws.rs.core.Response.Status.NOT_FOUND;+import java.util.*;public class DashboardStorageService extends RouteBuilder implements ContainerService {@@ -68,36 +61,50 @@ public class DashboardStorageService extends RouteBuilder implements ContainerSe/* -------------------------- */- // Getting ALL dashboards from a realm- protected <T extends Dashboard> Dashboard[] findAllOfRealm(String realm, String userId) {- return this.findAllOfRealm(realm, userId, false);- }-- @SuppressWarnings("java:S2326")- protected <T extends Dashboard> Dashboard[] findAllOfRealm(String realm, String userId, Boolean editable) {+ // Querying dashboards from the database+ // userId is required for checking dashboard ownership. If userId is NULL, we assume the user is not logged in.+ // editable can be used to only return dashboards where the user has edit access.+ protected Dashboard[] query(List<String> dashboardIds, String realm, String userId, Boolean publicOnly, Boolean editable) {+ if(realm == null) {+ throw new IllegalArgumentException("No realm is specified.");+ }return persistenceService.doReturningTransaction(em -> {try {CriteriaBuilder cb = em.getCriteriaBuilder();CriteriaQuery<Dashboard> cq = cb.createQuery(Dashboard.class);Root<Dashboard> root = cq.from(Dashboard.class);+List<Predicate> predicates = new ArrayList<>();- if(realm != null) {- predicates.add(cb.like(root.get("realm"), realm));+ predicates.add(cb.like(root.get("realm"), realm));++ if(dashboardIds != null) {+ predicates.add(root.get("id").in(dashboardIds));}- if(editable) {- predicates.add(cb.or(- root.get("editAccess").in(DashboardAccess.PUBLIC, DashboardAccess.SHARED),- cb.and(root.get("editAccess").in(DashboardAccess.PRIVATE), root.get("ownerId").in(userId))- ));+ // Apply EDIT ACCESS filters; always return PUBLIC dashboards, SHARED dashboards if access to the realm,+ // and PRIVATE if you are the creator (ownerId) of the dashboard.+ if(Boolean.TRUE.equals(editable)) {+ if(publicOnly) {+ predicates.add(cb.equal(root.get("editAccess"), DashboardAccess.PUBLIC));+ } else {+ predicates.add(cb.or(+ root.get("editAccess").in(DashboardAccess.PUBLIC, (userId != null ? DashboardAccess.SHARED : null)),+ cb.and(root.get("editAccess").in(DashboardAccess.PRIVATE), root.get("ownerId").in(userId))+ ));+ }+ }+ // Apply VIEW ACCESS filters; always return PUBLIC dashboards, SHARED dashboards if access to the realm,+ // and PRIVATE if you are the creator (ownerId) of the dashboard.+ if(publicOnly) {+ predicates.add(cb.equal(root.get("viewAccess"), DashboardAccess.PUBLIC));} else {predicates.add(cb.or(- root.get("viewAccess").in(DashboardAccess.PUBLIC, DashboardAccess.SHARED),+ root.get("viewAccess").in(DashboardAccess.PUBLIC, (userId != null ? DashboardAccess.SHARED : null)),cb.and(root.get("viewAccess").in(DashboardAccess.PRIVATE), root.get("ownerId").in(userId))));}+CriteriaQuery<Dashboard> all = cq.select(root).where(predicates.toArray(new Predicate[]{}));- TypedQuery<Dashboard> allQuery = em.createQuery(all);- return allQuery.getResultList().toArray(new Dashboard[0]);+ return em.createQuery(all).getResultList().toArray(new Dashboard[0]);} catch (Exception e) {e.printStackTrace();@@ -106,14 +113,32 @@ public class DashboardStorageService extends RouteBuilder implements ContainerSe});}- @SuppressWarnings("java:S2326")- protected <T extends Dashboard> Dashboard get(String id) {- return persistenceService.doReturningTransaction(em -> em.find(Dashboard.class, id));+ // Method to check if a dashboardId actually exists in the database+ // Useful for when query() does not return any accessible dashboard for that user, and check if it does however exist.+ protected boolean exists(String dashboardId, String realm) {+ if(dashboardId == null) {+ throw new IllegalArgumentException("No dashboardId is specified.");+ }+ if(realm == null) {+ throw new IllegalArgumentException("No realm is specified.");+ }+ return persistenceService.doReturningTransaction(em -> {+ CriteriaBuilder cb = em.getCriteriaBuilder();+ CriteriaQuery<Dashboard> cq = cb.createQuery(Dashboard.class);+ Root<Dashboard> root = cq.from(Dashboard.class);+ return em.createQuery(cq.select(root)+ .where(cb.like(root.get("realm"), realm))+ .where(cb.like(root.get("id"), dashboardId))+ );+ }) != null;}// Creation of initial dashboard (so no updating!)- protected <T extends Dashboard> T createNew(T dashboard) {+ protected Dashboard createNew(Dashboard dashboard) {+ if(dashboard == null) {+ throw new IllegalArgumentException("No dashboard is specified.");+ }return persistenceService.doReturningTransaction(em -> {if(dashboard.getId() != null && dashboard.getId().length() > 0) {Dashboard d = em.find(Dashboard.class, dashboard.getId()); // checking whether dashboard is already in database@@ -126,43 +151,49 @@ public class DashboardStorageService extends RouteBuilder implements ContainerSe}// Update of an existing dashboard- protected <T extends Dashboard> T update(T dashboard, String userId) {- return persistenceService.doReturningTransaction(em -> {- Dashboard d = em.find(Dashboard.class, dashboard.getId());- if(d != null) {- if(d.getEditAccess() == DashboardAccess.PRIVATE) {- if(!(d.getOwnerId().equals(userId))) {- throw new WebApplicationException("You are not allowed to edit this dashboard!", FORBIDDEN);- }- }- dashboard.setVersion(d.getVersion()); // Always forcing to the correct version, no matter what.+ protected Dashboard update(Dashboard dashboard, String realm, String userId) throws IllegalArgumentException {+ if(dashboard == null) {+ throw new IllegalArgumentException("No dashboard is specified.");+ }+ if(realm == null) {+ throw new IllegalArgumentException("No realm is specified.");+ }+ if(userId == null) {+ throw new IllegalArgumentException("No userId is specified.");+ }+ Dashboard[] dashboards = this.query(Collections.singletonList(dashboard.getId()), realm, userId, false, true); // Get dashboards that userId is able to EDIT.+ if(dashboards != null && dashboards.length > 0) {+ Dashboard d = dashboards[0];+ return persistenceService.doReturningTransaction(em -> {+ dashboard.setVersion(d.getVersion());return em.merge(dashboard);- } else {- throw new WebApplicationException("This dashboard does not exist!", NOT_FOUND);- }- });+ });+ } else {+ throw new IllegalArgumentException("This dashboard does not exist!");+ }}- protected boolean delete(List<String> dashboardIds, String userId) {+ protected boolean delete(String dashboardId, String realm, String userId) throws IllegalArgumentException {+ if(dashboardId == null) {+ throw new IllegalArgumentException("No dashboardId is specified.");+ }+ if(realm == null) {+ throw new IllegalArgumentException("No realm is specified.");+ }+ if(userId == null) {+ throw new IllegalArgumentException("No userId is specified.");+ }return persistenceService.doReturningTransaction(em -> {- try {- Dashboard[] dashboards = this.findAllOfRealm(null, userId, true); // Get dashboards that userId is able to EDIT.- Collection<String> toDelete = new ArrayList<>();- for(Dashboard d : dashboards) {- if(dashboardIds.contains(d.getId())) {- toDelete.add(d.getId());- }- }- if(!toDelete.isEmpty()) {- Query query = em.createQuery("DELETE from Dashboard d WHERE d.id in (?1)");- query.setParameter(1, toDelete);- query.executeUpdate();- }- return true;- } catch (Exception e) {- e.printStackTrace();- return false;++ // Query the dashboards with the same ID (which is only 1), and that userId is able to EDIT+ Dashboard[] dashboards = this.query(Collections.singletonList(dashboardId), realm, userId, false, true);+ if(dashboards == null || dashboards.length == 0) {+ throw new IllegalArgumentException("No dashboards could be found.");}+ Query query = em.createQuery("DELETE from Dashboard d where d.id=?1");+ query.setParameter(1, dashboardId);+ query.executeUpdate();+ return true;});}}diff --git a/manager/src/main/java/org/openremote/manager/datapoint/AssetDatapointResourceImpl.java b/manager/src/main/java/org/openremote/manager/datapoint/AssetDatapointResourceImpl.javaindex 31e98cf5b..1d7674112 100644--- a/manager/src/main/java/org/openremote/manager/datapoint/AssetDatapointResourceImpl.java+++ b/manager/src/main/java/org/openremote/manager/datapoint/AssetDatapointResourceImpl.java@@ -25,6 +25,7 @@ import org.openremote.container.timer.TimerService;import org.openremote.manager.asset.AssetStorageService;import org.openremote.manager.security.ManagerIdentityService;import org.openremote.manager.web.ManagerWebResource;+import org.openremote.model.Constants;import org.openremote.model.asset.Asset;import org.openremote.model.attribute.Attribute;import org.openremote.model.attribute.AttributeRef;@@ -33,6 +34,7 @@ import org.openremote.model.datapoint.AssetDatapointResource;import org.openremote.model.datapoint.DatapointPeriod;import org.openremote.model.datapoint.ValueDatapoint;import org.openremote.model.http.RequestParams;+import org.openremote.model.security.ClientRole;import org.openremote.model.syslog.SyslogCategory;import jakarta.ws.rs.BadRequestException;@@ -43,6 +45,8 @@ import jakarta.ws.rs.container.AsyncResponse;import jakarta.ws.rs.container.ConnectionCallback;import jakarta.ws.rs.core.HttpHeaders;import jakarta.ws.rs.core.Response;+import org.openremote.model.value.MetaItemType;+import java.io.*;import java.util.concurrent.ScheduledFuture;import java.util.logging.Level;@@ -87,7 +91,18 @@ public class AssetDatapointResourceImpl extends ManagerWebResource implements Asthrow new WebApplicationException(Response.Status.NOT_FOUND);}- if (!isRealmActiveAndAccessible(asset.getRealm())) {+ // Realm should be accessible+ if(!isRealmActiveAndAccessible(asset.getRealm())) {+ throw new WebApplicationException(Response.Status.FORBIDDEN);+ }++ // If not logged in, asset should be PUBLIC READ+ if(!isAuthenticated() && !asset.isAccessPublicRead()) {+ throw new WebApplicationException(Response.Status.FORBIDDEN);+ }++ // If logged in, user should have READ ASSETS role+ if(isAuthenticated() && !hasResourceRole(ClientRole.READ_ASSETS.getValue(), Constants.KEYCLOAK_CLIENT_ID)) {LOG.info("Forbidden access for user '" + getUsername() + "': " + asset.getRealm());throw new WebApplicationException(Response.Status.FORBIDDEN);}@@ -96,6 +111,23 @@ public class AssetDatapointResourceImpl extends ManagerWebResource implements Asnew WebApplicationException(Response.Status.NOT_FOUND));+ // If restricted, the attribute should also be restricted+ if(isRestrictedUser()) {+ attribute.getMeta().getValue(MetaItemType.ACCESS_RESTRICTED_READ).ifPresentOrElse((v) -> {+ if(!v) { throw new WebApplicationException(Response.Status.FORBIDDEN); }+ }, () -> {+ throw new WebApplicationException(Response.Status.FORBIDDEN);+ });+ }++ // If not logged in, attribute should be PUBLIC READ+ if(!isAuthenticated()) {+ attribute.getMeta().getValue(MetaItemType.ACCESS_PUBLIC_READ).ifPresentOrElse((v) -> {+ if(!v) { throw new WebApplicationException(Response.Status.FORBIDDEN); }+ }, () -> {+ throw new WebApplicationException(Response.Status.FORBIDDEN);+ });+ }return assetDatapointService.queryDatapoints(assetId, attribute, query);} catch (IllegalStateException ex) {diff --git a/manager/src/main/java/org/openremote/manager/datapoint/AssetPredictedDatapointResourceImpl.java b/manager/src/main/java/org/openremote/manager/datapoint/AssetPredictedDatapointResourceImpl.javaindex 862f57c3d..c549fecff 100644--- a/manager/src/main/java/org/openremote/manager/datapoint/AssetPredictedDatapointResourceImpl.java+++ b/manager/src/main/java/org/openremote/manager/datapoint/AssetPredictedDatapointResourceImpl.java@@ -23,6 +23,7 @@ import org.openremote.container.timer.TimerService;import org.openremote.manager.asset.AssetStorageService;import org.openremote.manager.security.ManagerIdentityService;import org.openremote.manager.web.ManagerWebResource;+import org.openremote.model.Constants;import org.openremote.model.asset.Asset;import org.openremote.model.attribute.Attribute;import org.openremote.model.datapoint.query.AssetDatapointQuery;@@ -33,9 +34,9 @@ import org.openremote.model.http.RequestParams;import jakarta.ws.rs.BeanParam;import jakarta.ws.rs.WebApplicationException;import jakarta.ws.rs.core.Response;-import java.time.Instant;-import java.time.LocalDateTime;-import java.time.ZoneId;+import org.openremote.model.security.ClientRole;+import org.openremote.model.value.MetaItemType;+import java.util.logging.Logger;public class AssetPredictedDatapointResourceImpl extends ManagerWebResource implements AssetPredictedDatapointResource {@@ -71,7 +72,18 @@ public class AssetPredictedDatapointResourceImpl extends ManagerWebResource implthrow new WebApplicationException(Response.Status.NOT_FOUND);}- if (!isRealmActiveAndAccessible(asset.getRealm())) {+ // Realm should be accessible+ if(!isRealmActiveAndAccessible(asset.getRealm())) {+ throw new WebApplicationException(Response.Status.FORBIDDEN);+ }++ // If not logged in, asset should be PUBLIC READ+ if(!isAuthenticated() && !asset.isAccessPublicRead()) {+ throw new WebApplicationException(Response.Status.FORBIDDEN);+ }++ // If logged in, user should have READ ASSETS role+ if(isAuthenticated() && !hasResourceRole(ClientRole.READ_ASSETS.getValue(), Constants.KEYCLOAK_CLIENT_ID)) {LOG.info("Forbidden access for user '" + getUsername() + "': " + asset.getRealm());throw new WebApplicationException(Response.Status.FORBIDDEN);}@@ -80,7 +92,25 @@ public class AssetPredictedDatapointResourceImpl extends ManagerWebResource implnew WebApplicationException(Response.Status.NOT_FOUND));+ // If restricted, the attribute should also be restricted+ if(isRestrictedUser()) {+ attribute.getMeta().getValue(MetaItemType.ACCESS_RESTRICTED_READ).ifPresentOrElse((v) -> {+ if(!v) { throw new WebApplicationException(Response.Status.FORBIDDEN); }+ }, () -> {+ throw new WebApplicationException(Response.Status.FORBIDDEN);+ });+ }++ // If not logged in, attribute should be PUBLIC READ+ if(!isAuthenticated()) {+ attribute.getMeta().getValue(MetaItemType.ACCESS_PUBLIC_READ).ifPresentOrElse((v) -> {+ if(!v) { throw new WebApplicationException(Response.Status.FORBIDDEN); }+ }, () -> {+ throw new WebApplicationException(Response.Status.FORBIDDEN);+ });+ }return assetPredictedDatapointService.queryDatapoints(assetId, attribute, query);+} catch (IllegalStateException ex) {throw new WebApplicationException(ex, Response.Status.BAD_REQUEST);}diff --git a/manager/src/main/java/org/openremote/manager/web/ManagerWebResource.java b/manager/src/main/java/org/openremote/manager/web/ManagerWebResource.javaindex b78c04899..429f652c5 100644--- a/manager/src/main/java/org/openremote/manager/web/ManagerWebResource.java+++ b/manager/src/main/java/org/openremote/manager/web/ManagerWebResource.java@@ -47,11 +47,11 @@ public class ManagerWebResource extends WebResource {}public boolean isRealmActiveAndAccessible(String realm) {- return identityService.getIdentityProvider().isRealmActiveAndAccessible(this, realm);+ return identityService.getIdentityProvider().isRealmActiveAndAccessible(getAuthContext(), realm);}public boolean isRealmActiveAndAccessible(Realm realm) {- return identityService.getIdentityProvider().isRealmActiveAndAccessible(this, realm);+ return identityService.getIdentityProvider().isRealmActiveAndAccessible(getAuthContext(), realm);}}diff --git a/manager/src/web/shared/locales/en/or.json b/manager/src/web/shared/locales/en/or.jsonindex ab11d8364..013d1c83b 100644--- a/manager/src/web/shared/locales/en/or.json+++ b/manager/src/web/shared/locales/en/or.json@@ -274,6 +274,7 @@"custom": "Custom attribute","realm": "Realm","realm_plural": "Realms",+ "changeRealm": "Change realm","displayName":"Friendly name","loginTheme": "Login theme","emailTheme": "Email theme",@@ -582,6 +583,7 @@"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.",+ "dashboardNotFound": "This dashboard could not be found.","noDashboardWriteAccess": "You don't have access to edit this dashboard.","confirmContinueDashboardModified": "Dashboard has been edited, do you want to discard the changes?","dashboards": "Dashboards",diff --git a/manager/src/web/shared/locales/nl/or.json b/manager/src/web/shared/locales/nl/or.jsonindex 8c3743fe1..869941510 100644--- a/manager/src/web/shared/locales/nl/or.json+++ b/manager/src/web/shared/locales/nl/or.json@@ -274,6 +274,7 @@"custom": "Nieuw attribuut","realm": "Realm","realm_plural": "Realms",+ "changeRealm": "Verander realm","displayName":"Vriendelijke naam","loginTheme": "Login thema","emailTheme": "Email thema",@@ -582,6 +583,7 @@"noDashboardSelected": "Selecteer een dashboard aan de linkerkant","noDashboardSelected-mobile": "Selecteer een dashboard in het menu linksboven","noDashboardFound": "Geen dashboard gevonden.",+ "dashboardNotFound": "Het dashboard kon niet worden gevonden.","noDashboardWriteAccess": "U heeft geen rechten om dit dashboard aan te passen.","confirmContinueDashboardModified": "Dashboard is aangepast, wijzigingen negeren?","dashboards": "Dashboards",diff --git a/model/src/main/java/org/openremote/model/dashboard/Dashboard.java b/model/src/main/java/org/openremote/model/dashboard/Dashboard.javaindex 3dce1ec69..b16e1f426 100644--- a/model/src/main/java/org/openremote/model/dashboard/Dashboard.java+++ b/model/src/main/java/org/openremote/model/dashboard/Dashboard.java@@ -56,38 +56,94 @@ public class Dashboard {/* ----------------------------- */- public void setId(String id) {+ public Dashboard() {+ }++ public Dashboard(String realm, String displayName, DashboardScreenPreset[] screenPresets) {+ this.realm = realm;+ this.template = new DashboardTemplate(screenPresets);+ this.displayName = displayName;+ }++ public Dashboard setId(String id) {this.id = id;+ return this;}- public void setCreatedOn(Date createdOn) {++ public Dashboard setCreatedOn(Date createdOn) {this.createdOn = createdOn;+ return this;}- public void setRealm(String realm) {++ public Dashboard setRealm(String realm) {this.realm = realm;+ return this;}- public void setVersion(long version) {++ public Dashboard setVersion(long version) {this.version = version;+ return this;}- public void setOwnerId(String ownerId) {++ public Dashboard setOwnerId(String ownerId) {this.ownerId = ownerId;+ return this;+ }++ public Dashboard setViewAccess(DashboardAccess access) {+ this.viewAccess = access;+ return this;+ }++ public Dashboard setEditAccess(DashboardAccess access) {+ this.editAccess = access;+ return this;}- public void setViewAccess(DashboardAccess access) { this.viewAccess = access; }- public void setEditAccess(DashboardAccess access) { this.editAccess = access; }- public void setDisplayName(String displayName) {++ public Dashboard setDisplayName(String displayName) {this.displayName = displayName;+ return this;}- public void setTemplate(@Valid DashboardTemplate template) {++ public Dashboard setTemplate(@Valid DashboardTemplate template) {this.template = template;+ return this;}- public String getId() { return this.id; }- public Date getCreatedOn() { return this.createdOn; }- public String getRealm() { return this.realm; }- public long getVersion() { return this.version; }- public String getOwnerId() { return this.ownerId; }- public DashboardAccess getViewAccess() { return this.viewAccess; }- public DashboardAccess getEditAccess() { return this.editAccess; }- public String getDisplayName() { return this.displayName; }- public DashboardTemplate getTemplate() { return this.template; }+ public String getId() {+ return this.id;+ }++ public Date getCreatedOn() {+ return this.createdOn;+ }++ public String getRealm() {+ return this.realm;+ }++ public long getVersion() {+ return this.version;+ }++ public String getOwnerId() {+ return this.ownerId;+ }++ public DashboardAccess getViewAccess() {+ return this.viewAccess;+ }++ public DashboardAccess getEditAccess() {+ return this.editAccess;+ }++ public String getDisplayName() {+ return this.displayName;+ }++ public DashboardTemplate getTemplate() {+ return this.template;+ }}diff --git a/model/src/main/java/org/openremote/model/dashboard/DashboardResource.java b/model/src/main/java/org/openremote/model/dashboard/DashboardResource.javaindex 839837b37..8062297d6 100644--- a/model/src/main/java/org/openremote/model/dashboard/DashboardResource.java+++ b/model/src/main/java/org/openremote/model/dashboard/DashboardResource.java@@ -19,13 +19,11 @@ public interface DashboardResource {@GET@Path("all/{realm}")@Produces(APPLICATION_JSON)- @RolesAllowed({Constants.READ_INSIGHTS_ROLE})Dashboard[] getAllRealmDashboards(@BeanParam RequestParams requestParams, @PathParam("realm") String realm);@GET@Path("{dashboardId}")@Produces(APPLICATION_JSON)- @RolesAllowed({Constants.READ_INSIGHTS_ROLE})Dashboard get(@BeanParam RequestParams requestParams, @PathParam("dashboardId") String dashboardId);@POST@@ -38,10 +36,11 @@ public interface DashboardResource {@Consumes(APPLICATION_JSON)@Produces(APPLICATION_JSON)@RolesAllowed({Constants.WRITE_INSIGHTS_ROLE})- void update(@BeanParam RequestParams requestParams, @Valid Dashboard dashboard);+ Dashboard update(@BeanParam RequestParams requestParams, @Valid Dashboard dashboard);@DELETE+ @Path("{dashboardId}")@Produces(APPLICATION_JSON)@RolesAllowed({Constants.WRITE_INSIGHTS_ROLE})- void delete(@BeanParam RequestParams requestParams, @QueryParam("dashboardId") List<String> fields);+ void delete(@BeanParam RequestParams requestParams, @PathParam("dashboardId") String dashboardId);}diff --git a/model/src/main/java/org/openremote/model/dashboard/DashboardScreenPreset.java b/model/src/main/java/org/openremote/model/dashboard/DashboardScreenPreset.javaindex 198f5dc13..87fd99007 100644--- a/model/src/main/java/org/openremote/model/dashboard/DashboardScreenPreset.java+++ b/model/src/main/java/org/openremote/model/dashboard/DashboardScreenPreset.java@@ -27,6 +27,14 @@ public class DashboardScreenPreset {/* -------------------------------- */+ public DashboardScreenPreset() {+ }+ public DashboardScreenPreset(String displayName, DashboardScalingPreset scalingPreset) {+ this.displayName = displayName;+ this.breakpoint = 1;+ this.scalingPreset = scalingPreset;+ }+public void setId(@NotNull @NotEmpty String id) { this.id = id; }public void setDisplayName(@NotNull @NotEmpty String displayName) { this.displayName = displayName; }public void setBreakpoint(@NotNull int breakpoint) { this.breakpoint = breakpoint; }diff --git a/model/src/main/java/org/openremote/model/dashboard/DashboardTemplate.java b/model/src/main/java/org/openremote/model/dashboard/DashboardTemplate.javaindex e65adaca4..3cb4966b8 100644--- a/model/src/main/java/org/openremote/model/dashboard/DashboardTemplate.java+++ b/model/src/main/java/org/openremote/model/dashboard/DashboardTemplate.java@@ -26,6 +26,15 @@ public class DashboardTemplate {/* -------------------- */+ public DashboardTemplate() {++ }+ public DashboardTemplate(DashboardScreenPreset[] screenPresets) {+ this.columns = 1;+ this.maxScreenWidth = 1;+ 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; }diff --git a/model/src/main/java/org/openremote/model/datapoint/AssetDatapointResource.java b/model/src/main/java/org/openremote/model/datapoint/AssetDatapointResource.javaindex 74a22a97f..fbe8fd9b2 100644--- a/model/src/main/java/org/openremote/model/datapoint/AssetDatapointResource.java+++ b/model/src/main/java/org/openremote/model/datapoint/AssetDatapointResource.java@@ -45,7 +45,6 @@ public interface AssetDatapointResource {@Path("{assetId}/attribute/{attributeName}")@Consumes(APPLICATION_JSON)@Produces(APPLICATION_JSON)- @RolesAllowed({Constants.READ_ASSETS_ROLE})ValueDatapoint<?>[] getDatapoints(@BeanParam RequestParams requestParams,@PathParam("assetId") String assetId,@PathParam("attributeName") String attributeName,diff --git a/model/src/main/java/org/openremote/model/datapoint/AssetPredictedDatapointResource.java b/model/src/main/java/org/openremote/model/datapoint/AssetPredictedDatapointResource.javaindex 84266cec0..390cc0b95 100644--- a/model/src/main/java/org/openremote/model/datapoint/AssetPredictedDatapointResource.java+++ b/model/src/main/java/org/openremote/model/datapoint/AssetPredictedDatapointResource.java@@ -42,7 +42,6 @@ public interface AssetPredictedDatapointResource {@Path("{assetId}/attribute/{attributeName}")@Consumes(APPLICATION_JSON)@Produces(APPLICATION_JSON)- @RolesAllowed({Constants.READ_ASSETS_ROLE})ValueDatapoint<?>[] getPredictedDatapoints(@BeanParam RequestParams requestParams,@PathParam("assetId") String assetId,@PathParam("attributeName") String attributeName,diff --git a/test/src/test/groovy/org/openremote/test/dashboard/DashboardTest.groovy b/test/src/test/groovy/org/openremote/test/dashboard/DashboardTest.groovyindex 9b38b7a55..d37de593e 100644--- a/test/src/test/groovy/org/openremote/test/dashboard/DashboardTest.groovy+++ b/test/src/test/groovy/org/openremote/test/dashboard/DashboardTest.groovy@@ -1,12 +1,11 @@package org.openremote.test.dashboard+import jakarta.ws.rs.ForbiddenException+import jakarta.ws.rs.NotFoundExceptionimport org.openremote.manager.setup.SetupService-import org.openremote.model.dashboard.Dashboard-import org.openremote.model.dashboard.DashboardResource-import org.openremote.test.ManagerContainerTrait+import org.openremote.model.dashboard.*import org.openremote.setup.integration.KeycloakTestSetup-import org.openremote.setup.integration.ManagerTestSetup-import spock.lang.Ignore+import org.openremote.test.ManagerContainerTraitimport spock.lang.Specificationimport static org.openremote.container.security.IdentityProvider.OR_ADMIN_PASSWORD@@ -14,34 +13,119 @@ import static org.openremote.container.security.IdentityProvider.OR_ADMIN_PASSWOimport static org.openremote.container.util.MapAccess.getStringimport static org.openremote.model.Constants.*-@Ignoreclass DashboardTest extends Specification implements ManagerContainerTrait {- def "Test invalid input Dashboard"() {+ def "Test dashboard creation and access rights"() {+given: "the server container is started"def container = startContainer(defaultConfig(), defaultServices())- def managerTestSetup = container.getService(SetupService.class).getTaskOfType(ManagerTestSetup.class)def keycloakTestSetup = container.getService(SetupService.class).getTaskOfType(KeycloakTestSetup.class)- and: "an authenticated admin user"- def accessToken = authenticate(+ and: "all users are logged in"+ def adminUserAccessToken = authenticate(container,MASTER_REALM,KEYCLOAK_CLIENT_ID,MASTER_REALM_ADMIN_USER,getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)).token+ def privateUser1AccessToken = authenticate(+ container,+ MASTER_REALM,+ KEYCLOAK_CLIENT_ID,+ "testuser1",+ "testuser1"+ ).tokenand: "the dashboard resource"def serverUri = serverUri(serverPort)- def dashboardResource = getClientApiTarget(serverUri, MASTER_REALM, accessToken).proxy(DashboardResource.class)+ def adminUserDashboardResource = getClientApiTarget(serverUri, MASTER_REALM, adminUserAccessToken).proxy(DashboardResource.class)+ def privateUser1DashboardResource = getClientApiTarget(serverUri, MASTER_REALM, privateUser1AccessToken).proxy(DashboardResource.class)+ def publicUserDashboardResource = getClientApiTarget(serverUri, MASTER_REALM).proxy(DashboardResource.class)++ /* ----------------------- */++ // Test to verify dashboards can be CREATED and FETCHED by different users.when: "a dashboard is created in the authenticated realm"- Dashboard testDashboard = new Dashboard();- testDashboard = dashboardResource.create(null, testDashboard);+ DashboardScreenPreset[] screenPresets = Arrays.asList(new DashboardScreenPreset("preset1", DashboardScalingPreset.KEEP_LAYOUT)).toArray() as DashboardScreenPreset[]+ Dashboard temp1 = new Dashboard(MASTER_REALM, "dashboard1", screenPresets)+ adminUserDashboardResource.create(null, temp1)+ Dashboard temp2 = new Dashboard(MASTER_REALM, "dashboard2", screenPresets).setOwnerId(keycloakTestSetup.testuser1Id)+ privateUser1DashboardResource.create(null, temp2)++ then: "requesting the dashboard should return the same object"+ def adminDashboards = adminUserDashboardResource.getAllRealmDashboards(null, MASTER_REALM)+ def adminDashboard = adminDashboards[0]+ def privateUser1Dashboard = adminDashboards[1]+ assert adminDashboards.length == 2+ def userDashboards = privateUser1DashboardResource.getAllRealmDashboards(null, MASTER_REALM)+ assert userDashboards.length == 2+ assert adminDashboard.id == userDashboards[0].id+ assert privateUser1Dashboard.id == userDashboards[1].id++ /* ----------------------- */++ // Test to verify "EDIT ACCESS" logic++ when: "dashboard1 is made 'edit private' by its original owner"+ privateUser1Dashboard.setEditAccess(DashboardAccess.PRIVATE)+ assert privateUser1DashboardResource.update(null, privateUser1Dashboard) != null++ and: "dashboard1 is actually private"+ def dashboards = privateUser1DashboardResource.getAllRealmDashboards(null, MASTER_REALM)+ assert dashboards.length == 2+ assert dashboards.find((d) -> d.id == privateUser1Dashboard.id).editAccess == DashboardAccess.PRIVATE++ and: "the first dashboard cannot be edited by a different user, even if its admin user"+ privateUser1Dashboard.setDisplayName("another displayname")+ adminUserDashboardResource.update(null, privateUser1Dashboard)++ then: "it should throw exception"+ thrown NotFoundException++ /* ----------------------- */++ // Test to verify "DELETE" logic++ when: "admin user tries to delete a dashboard he doesn't own"+ adminUserDashboardResource.delete(null, privateUser1Dashboard.id)++ then: "it should throw exception"+ thrown NotFoundException++ /* ----------------------- */++ // Test to verify public/unauthenticated user cannot fetch dashboards by default++ when: "dashboards are requested by a public user"+ def publicDashboards1 = publicUserDashboardResource.getAllRealmDashboards(null, MASTER_REALM)++ then: "it should return an empty array"+ assert publicDashboards1.length == 0++ /* ----------------------- */++ // Test to verify public dashboards CAN be fetched by public/unauthenticated users++ when: "dashboard1 is made 'view public' by its original owner"+ privateUser1Dashboard.setViewAccess(DashboardAccess.PUBLIC)+ assert privateUser1DashboardResource.update(null, privateUser1Dashboard) != null++ then: "when a public user fetches all dashboards, it should only return that dashboard"+ def publicDashboards2 = publicUserDashboardResource.getAllRealmDashboards(null, MASTER_REALM)+ assert publicDashboards2.length == 1+ assert publicDashboards2[0].viewAccess == DashboardAccess.PUBLIC+ assert publicDashboards2[0].editAccess == DashboardAccess.PRIVATE++ /* ----------------------- */++ // Test to verify private dashboards cannot be fetched by public/unauthenticated users, even if ID is specified++ when: "when a public user specifically fetches a private dashboard"+ publicUserDashboardResource.get(null, adminDashboard.id);- then: "the dashboard should exist"- testDashboard.displayName == "Test Room"- testDashboard.template != null+ then: "it should throw exception"+ thrown ForbiddenException}}diff --git a/ui/app/insights/src/components/dashboard-menu.ts b/ui/app/insights/src/components/dashboard-menu.tsindex 578921e79..b01d9e270 100644--- a/ui/app/insights/src/components/dashboard-menu.ts+++ b/ui/app/insights/src/components/dashboard-menu.ts@@ -1,50 +1,62 @@-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 { html, css, LitElement, TemplateResult, unsafeCSS } from "lit";+import { customElement, property, query, state } from "lit/decorators.js";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 { Dashboard } from "@openremote/model";+import { i18next } from "@openremote/or-translate";+import { ListItem } from "@openremote/or-mwc-components/or-mwc-list";import { OrMwcDrawer } from "@openremote/or-mwc-components/or-mwc-drawer";-import {style} from "../style"+import {style} from "../style";+import { OrMwcDialog, showDialog } from "@openremote/or-mwc-components/or-mwc-dialog";+import {DefaultColor5} from "@openremote/core";-//language=css+// language=cssconst styling = css`#list-container {display: flex;flex-direction: column;gap: 16px;}+ #drawer-wrapper {+ height: 100%;+ display: flex;+ flex-direction: column;+ justify-content: space-between;+ }+ #drawer-actions-container {+ border-top: 1px solid var(--or-app-color5, ${unsafeCSS(DefaultColor5)});+ display: flex;+ flex-direction: column;+ gap: 8px;+ }`-export interface DrawerConfig {- enabled: boolean,- showHeader: boolean-}@customElement("dashboard-menu")export class DashboardMenu extends LitElement {- @property()- protected readonly dashboards!: Dashboard[];+ @property() // list of dashboards: if set to 'undefined', it will pull new dashboards automatically.+ protected readonly dashboards?: Dashboard[];++ @property() // Custom realm object that only requires name and displayName.+ protected readonly realms?: { name: string, displayName: string }[];@property() // id of the selected dashboardprotected readonly selectedId?: string;- @property()- protected readonly userId!: string;+ @property() // id of the current user+ protected readonly userId?: string;@property()- protected readonly realmName?: string;+ protected readonly realm?: string;@property()- protected readonly realmConfig?: RealmAppConfig;+ protected readonly loading: boolean = false;@property()- protected drawerConfig?: DrawerConfig;+ protected readonly logoMobileSrc?: string;- @property()- protected readonly loading: boolean = false;+ @state()+ protected selectedActions: string[] = [];@query("#drawer")protected drawer: OrMwcDrawer;@@ -56,16 +68,6 @@ export class DashboardMenu extends LitElement {return [style, styling];}- // Set defaults if not set yet- firstUpdated() {- if(!this.drawerConfig) {- this.drawerConfig = {- enabled: true,- showHeader: true- }- }- }-/* ------------------------------------------ */// PUBLIC METHODS FOR EXTERNAL CONTROL@@ -73,19 +75,19 @@ export class DashboardMenu extends LitElement {// For toggling drawer elsewhere, such as page-insights.ts// Returned value is the new status of the Drawerpublic async toggleDrawer(state?: boolean): Promise<boolean> {- if(state && state == this.drawer.open) {+ if(state != undefined && state == this.drawer.open) {return this.drawer.open;}- if(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.drawer?.toggle();}- this.requestUpdate(); // to reload the component, which removes the drawerScrim we added earlier from the DOM+ this.requestUpdate(); // to reload the component, since we need to remove the drawerScrim we added earlierthis.dispatchEvent(new CustomEvent('toggle', { detail: { value: this.drawer.open }}))- return this.drawer.open;+ return this.drawer?.open;}public isDrawerOpen(): boolean {@@ -93,35 +95,96 @@ export class DashboardMenu extends LitElement {}+ /* ---------------------------- */- /* -------------------------------------------------------- */+ // METHODS OF THE UI, THAT MOSTLY DISPATCH EVENTS TO PARENT COMPONENTSprotected selectDashboard(id: string) {- this.dispatchEvent(new CustomEvent('change', { detail: { value: id }}));+ const dashboard = this.dashboards.find((d) => d.id == id);+ this.dispatchEvent(new CustomEvent('change', { detail: { value: dashboard }}));}+ protected changeRealm(realm: string) {+ if(realm != this.realm) {+ this.dispatchEvent(new CustomEvent("realm", { detail: { value: realm }}));+ }+ }- 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>- `;+ protected logout() {+ this.dispatchEvent(new CustomEvent("logout"));+ }++ protected login() {+ this.dispatchEvent(new CustomEvent("login"))+ }++ protected promptRealmSwitch() {+ showDialog(new OrMwcDialog()+ .setHeading(i18next.t('changeRealm'))+ .setDismissAction(null)+ .setActions(Object.entries(this.realms).map(([key, value]) => ({+ content: html`<span>${value.displayName}</span>`,+ actionName: key,+ action: () => {+ this.changeRealm(value.name);+ }+ })))+ );+ }+++ /* ------------------------------------------- */++ protected render(): TemplateResult {+ const curRealm = this.realms?.find((r) => r.name == this.realm);+ const headerTemplate = html`+ <div style="display: flex; align-items: center; gap: 16px; padding: 13px 16px; border-bottom: 1px solid var(--or-app-color5, ${unsafeCSS(DefaultColor5)});">+ ${this.loading ? html`+ <div style="height: 34px;">+ <!-- Placeholder height to prevent changes during the realm fetch -->+ </div>+ ` : html`+ <img id="logo-mobile" width="34" height="34" alt="${curRealm.displayName} Logo" src="${this.logoMobileSrc}" />+ <span style="font-size: 18px; font-weight: bold;">${curRealm.displayName}</span>+ `}+ </div>+ `;+ const actionItems: ListItem[] = [];+ if(this.realms !== undefined && this.realms.length > 1) {+ actionItems.push({ icon: 'domain', text: i18next.t('changeRealm'), value: 'realm' })}+ if(this.userId !== undefined) {+ actionItems.push({ icon: 'logout', text: i18next.t('logout'), value: 'logout' });+ } else {+ actionItems.push({ icon: 'login', text: i18next.t('login'), value: 'login' })+ }+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)}+ <or-mwc-drawer id="drawer" .header="${headerTemplate}" .dismissible="${true}">+ <div id="drawer-wrapper">+ <div>+ ${getDashboardListTemplate(this.dashboards, this.selectedId, (id: string) => this.selectDashboard(id), this.userId, this.loading)}+ </div>+ <div id="drawer-actions-container">+ <or-mwc-list .listItems="${actionItems}" .values="${this.selectedActions}" @or-mwc-list-changed="${(ev: CustomEvent) => {+ switch (ev.detail[0].value) {+ case 'realm': {+ this.promptRealmSwitch(); break;+ } case 'logout': {+ this.logout(); break;+ } case 'login': {+ this.login(); break;+ }+ }+ // Hacky way to remove "select" status on or-mwc-list by updating selectedActions+ this.selectedActions = this.selectedActions == null ? [] : null;+ }}"+ ></or-mwc-list.>+ </div>+ </div>+ </or-mwc-drawer>+ ${when(this.isDrawerOpen(), () => html`+ <div id="drawer-custom-scrim" @click="${() => this.toggleDrawer(false)}"></div>`)}`}@@ -133,7 +196,7 @@ export class DashboardMenu extends LitElement {// 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 {+function getDashboardListTemplate(dashboards: Dashboard[], selectedId: string, onSelect: (id: string) => void, userId?: string, loading = false): TemplateResult {return html`${when(loading, () => html`<or-loading-indicator></or-loading-indicator>@@ -169,22 +232,20 @@ export function getDashboardListTemplate(dashboards: Dashboard[], selectedId: st`}-export function getDashboardMenuItems(dashboards: Dashboard[], userId: string): ListItem[][] {+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 })- })+ if(dashboards?.length > 0) {+ const myDashboards: Dashboard[] = [];+ const otherDashboards: Dashboard[] = [];+ dashboards?.forEach((d) => {+ (userId != null && 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.tsindex 0ed19d0e7..393583ae7 100644--- a/ui/app/insights/src/index.ts+++ b/ui/app/insights/src/index.ts@@ -1,7 +1,7 @@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 {pageViewProvider} from "./pages/page-view";import {ManagerAppConfig} from "@openremote/model";declare const CONFIG_URL_PREFIX: string;@@ -61,6 +61,10 @@ fetch(configURL).then(async (result) => {}}+ // Override specific for Insights app, since it doesn't require login.+ // Login and logout buttons can be found in the sidebar menu of the app.+ appConfig.manager.autoLogin = false;+orApp.managerConfig = appConfig.manager;orApp.appConfigProvider = (manager) => {@@ -112,7 +116,7 @@ fetch(configURL).then(async (result) => {}// Add insights page with correct parameters- orAppConfig.pages.push(pageInsightsProvider(store, orAppConfig.realms))+ orAppConfig.pages.push(pageViewProvider(store, orAppConfig.realms))return orAppConfig;}diff --git a/ui/app/insights/src/pages/page-insights.ts b/ui/app/insights/src/pages/page-insights.tsdeleted file mode 100644index 7f8f6a58b..000000000--- a/ui/app/insights/src/pages/page-insights.ts+++ /dev/null@@ -1,226 +0,0 @@-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/pages/page-view.ts b/ui/app/insights/src/pages/page-view.tsnew file mode 100644index 000000000..175912c52--- /dev/null+++ b/ui/app/insights/src/pages/page-view.ts@@ -0,0 +1,358 @@+import {html, TemplateResult} from "lit";+import {customElement, query, property, state} from "lit/decorators.js";+import {AppStateKeyed, DefaultMobileLogo, Page, PageProvider, RealmAppConfig, router, updateRealm} from "@openremote/or-app";+import {EnhancedStore} from "@reduxjs/toolkit";+import {when} from "lit/directives/when.js";+import {styleMap} from 'lit/directives/style-map.js';+import {guard} from "lit/directives/guard.js";+import {Dashboard, Realm} from "@openremote/model";+import {registerWidgetTypes} from "@openremote/or-dashboard-builder";+import manager from "@openremote/core";+import {DashboardMenu} from "../components/dashboard-menu";+import {InputType} from "@openremote/or-mwc-components/or-mwc-input";+import {i18next} from "@openremote/or-translate";+import {style} from "../style";+import {isAxiosError} from "@openremote/rest";+import "../components/dashboard-menu";+import "@openremote/or-chart";+import "@openremote/or-attribute-card";++export function pageViewProvider(store: EnhancedStore<AppStateKeyed>, realmConfigs: {[p: string]: RealmAppConfig}): PageProvider<AppStateKeyed> {+ return {+ name: "view",+ routes: [+ "view",+ "view/:id",+ "view/:id/:showMenu"+ ],+ pageCreator: () => {+ const page = new PageView(store);+ page.realmConfigs = realmConfigs;+ return page;+ }+ };+}++@customElement("page-view")+export class PageView extends Page<AppStateKeyed> {++ get name(): string {+ return "view"+ }++ @property() // configs of all available realms; contains details such as images+ public realmConfigs?: {[p: string]: RealmAppConfig};++ @property() // setting this to true removes the menu, and only fetches that specific dashboard to avoid clutter+ protected viewDashboardOnly: boolean = false;++ @state()+ protected _loadedDashboards?: Dashboard[];++ @state()+ protected _loadedRealms: Realm[] = [];++ @state() // ID of the selected dashboard+ protected _selectedId?: string;++ @state() // ID of the user. Will be undefined if not logged in.+ protected _userId?: string;++ @state()+ protected _realm: string = manager.displayRealm;++ @state() // list of active fetches, to make sure no duplicate fetch calls take place, and use for 'isLoading' checks+ protected _activePromises: Map<string, Promise<any>> = new Map<string, Promise<any>>();++ @state() // boolean that is put to true if a fresh render should take place. Similar to the one used in or-dashboard-builder.+ private rerenderPending: boolean = false;++ @query('#dashboard-menu')+ private dashboardMenu: DashboardMenu;++ static get styles() {+ return [style];+ }+++ /* -------------------- */++ constructor(props) {+ super(props);++ // Register user+ const userPromise = manager.rest.api.UserResource.getCurrent().then((response: any) => { this._userId = response.data.id; });+ this.registerPromise('user', userPromise, true, true);++ // Load available realms+ const realmPromise = manager.rest.api.RealmResource.getAccessible().then((response: any) => { this._loadedRealms = response.data; });+ this.registerPromise('realm', realmPromise, true, true);++ // Register dashboard related utils+ registerWidgetTypes();+ }+++ /* ------------------------ */++ // STATE RELATED FUNCTIONS++ // When state / url properties change+ stateChanged(state: AppStateKeyed): void {+ this._realm = state.app.realm;+ this.viewDashboardOnly = (state.app.params?.showMenu != undefined ? (state.app.params?.showMenu.toLowerCase() != 'true') : false);+ this.selectDashboard(state.app.params?.id, false);+ }++ // On every update, but before rendering anything+ willUpdate(changedProps: Map<string, any>) {++ // Update url if properties have changed that are present in the URL+ if(changedProps.has("_selectedId") || changedProps.has("viewDashboardOnly")) {+ this._updateRoute(this._selectedId, !this.viewDashboardOnly, false);+ }++ // Clear loadedDashboards when people switch between realms or viewing modes.+ // For example, if 'view this dashboard only' is active, we only fetch that specific dashboard.+ // When switched to 'view all dashboards', or the other way around, we should fetch all dashboard(s) of that realm again.+ if(changedProps.has("_realm") || changedProps.has("viewDashboardOnly")) {+ this._loadedDashboards = undefined;+ }++ // Fetch dashboard(s) if none exist, and no related fetch calls are active.+ if(this._loadedDashboards == undefined && !this.getPromise('dashboard/all') && !this.getPromise('dashboard/' + this._selectedId)) {++ // When visiting '/{id}/false', only fetch dashboard with that ID.+ if(this.viewDashboardOnly && this._selectedId) {+ this.fetchDashboard(this._selectedId).then((dashboard: Dashboard) => {+ this._loadedDashboards = (dashboard ? [dashboard] : undefined);+ })+ }+ // When visiting '/{id}/true', fetch dashboard with that ID first...+ else if(!this.viewDashboardOnly && this._selectedId) {+ this.fetchDashboard(this._selectedId).then((dashboard: Dashboard) => {+ this._loadedDashboards = dashboard ? [dashboard] : undefined;++ // If dashboard does not exist, but menu should be shown, then just deselect the dashboard.+ if(dashboard === undefined) {+ this._selectedId = undefined; // aka redirect to '/'+ }+ // If dashboard fetched with success, fetch all other dashboards of that realm as well.+ else {+ this.fetchAllDashboards().then((dashboards) => {+ this._loadedDashboards = dashboards;+ });+ }+ })+ }+ // When visiting '/'+ else {+ this.fetchAllDashboards().then((dashboards) => {+ if(!manager.authenticated && dashboards?.length === 0) {+ manager.login(); // if not logged in, auto login if no public dashboards are available+ } else {+ this._loadedDashboards = dashboards;+ if(dashboards.length === 1) {+ this._selectedId = this._loadedDashboards[0].id;+ }+ }+ })+ }+ }+ }+++ /* -------------------------------- */++ // FETCH RELATED FUNCTIONS++ protected async fetchAllDashboards(realmName?: string): Promise<Dashboard[]> {+ if(!realmName) {+ realmName = manager.displayRealm;+ }+ let promise = this.getPromise('dashboard/all');+ if(promise === undefined) {+ promise = this.registerPromise('dashboard/all', manager.rest.api.DashboardResource.getAllRealmDashboards(realmName), true, false);+ }+ try {+ const response = await promise;+ return response.data;+ } catch (ex) {+ console.error(ex);+ return [];+ }+ }++ protected async fetchDashboard(id: string, loginRedirect: boolean = true): Promise<Dashboard | undefined> {+ let promise = this.getPromise('dashboard/' + id);+ if(promise == undefined) {+ promise = this.registerPromise(('dashboard/' + id), manager.rest.api.DashboardResource.get(id), true, false);+ }+ try {+ const response = await promise;+ return response.data;+ } catch (ex) {+ if(isAxiosError(ex)) {+ if(ex.response.status === 404 && manager.isSuperUser()) {+ return undefined;+ }+ if(!manager.authenticated && ex.response.status === 403 && loginRedirect) {+ manager.login();+ }+ }+ return undefined;+ }+ }+++ /* ---------------------------- */++ protected render(): TemplateResult {+ const realmConfig = this.realmConfigs ? this.realmConfigs[this._realm] : undefined;+ const selected: Dashboard | undefined = this._loadedDashboards?.find((d) => d.id === this._selectedId);+ let logoMobile = realmConfig?.logoMobile;+ if(logoMobile == undefined) {+ logoMobile = DefaultMobileLogo;+ }+ const pageStyles = {+ display: 'flex',+ flexDirection: 'column',+ pointerEvents: this.dashboardMenu?.isDrawerOpen() ? 'none' : 'auto'+ }+ return html`+ ${when(!this.viewDashboardOnly, () => {+ const realms = this._loadedRealms?.map((r) => ({ name: r.name, displayName: r.displayName }));+ return html`+ <dashboard-menu id="dashboard-menu" .dashboards="${this._loadedDashboards}" .realms="${realms}" .realm="${this._realm}"+ .selectedId="${this._selectedId}" .userId="${this._userId}" .loading="${this.isLoading()}" .logoMobileSrc="${logoMobile}"+ @realm="${(ev: CustomEvent) => this.changeRealm(ev.detail.value)}"+ @change="${(ev: CustomEvent) => this.selectDashboard((ev.detail.value as Dashboard).id, true)}"+ @login="${() => { manager.login(); }}"+ @logout="${() => { this._updateRoute(); manager.logout(); }}"+ ></dashboard-menu>+ `+ })}+ <div style="flex: 1; ${styleMap(pageStyles)}">+ ${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`+ <or-dashboard-preview style="background: transparent;" .rerenderPending="${this.rerenderPending}"+ .realm="${manager.displayRealm}" .template="${selected?.template}" .editMode="${false}"+ .fullscreen="${true}" .readonly="${true}"+ @rerenderfinished="${() => this.rerenderPending = false}"+ ></or-dashboard-preview>+ `, () => html`+ <div id="dashboard-error-text">+ <span>${this.getErrorMsg(true)}</span>+ </div>+ `)}+ `)}+ </div>+ </div>+ `+ }++ getErrorMsg(translate: boolean = true): string {+ if(this.viewDashboardOnly && this._loadedDashboards?.length === 0) {+ return (translate ? i18next.t('dashboardNotFound') : 'dashboardNotFound');+ } else if(!this.viewDashboardOnly) {+ return (translate ? i18next.t('noDashboardSelected-mobile') : 'noDashboardSelected-mobile')+ }+ return (translate ? i18next.t('errorOccured') : 'errorOccured')+ }++ selectDashboard(id: string, closeDrawer: boolean = true) {+ if (id) {+ if (this.dashboardMenu && closeDrawer) {+ this.dashboardMenu.toggleDrawer(false).then(() => {+ this._selectedId = id;+ });+ } else {+ this._selectedId = id;+ }+ }+ }++ // Method to switch realms.+ // If dashboardId is not set, it will navigate to '/' since the current selectedId is not present in the new realm.+ changeRealm(realm: string, dashboardId?: string) {+ this._selectedId = dashboardId;+ this.updateComplete.then(() => {+ this._store.dispatch(updateRealm(realm));+ })+ }+++++ /* ---------------------------- */++ // PROMISE HANDLING UTILITY FUNCTIONS++ // It uses _activePromises to keep track of active processes / fetches.+ // This list is used for checking 'loading' state, or do an "await Promise.all()" to wait until everything is loaded.++ isLoading(): boolean {+ return (this._activePromises.size > 0);+ }++ getPromise(topic: string) {+ return this._activePromises.get(topic);+ }++ registerPromise(topic: string, promise: Promise<any>, doUpdate: boolean = true, updateOnComplete: boolean = true): Promise<any> {+ if(this._activePromises.has(topic)) {+ promise = this._activePromises.get(topic);+ } else {+ this._activePromises.set(topic, promise);+ }+ promise.finally(() => { this.completePromise(topic, updateOnComplete); });+ if(doUpdate) { this.requestUpdate("_activePromises"); }+ return promise;+ }++ completePromise(topic: string, doUpdate: boolean = true) {+ this._activePromises.delete(topic);+ if(doUpdate) { this.requestUpdate("_activePromises"); }+ }+++ // Util method for updating URL+ protected _updateRoute(id?: string, showMenu?: boolean, silent: boolean = true) {+ let path = "view";+ if(id) {+ path += "/" + id + (showMenu != undefined ? ('/' + showMenu) : undefined)+ }+ router.navigate(path, {+ callHooks: !silent,+ callHandler: !silent+ });+ }+++}++function getDashboardHeaderTemplate(showMenu = true, selected?: Dashboard, onopen?: (ev: Event) => void, onrefresh?: (ev: Event) => void): TemplateResult {+ return html`+ <div id="fullscreen-header">+ <div id="fullscreen-header-wrapper">+ <div>+ ${when(showMenu, () => html`+ <or-mwc-input type="${InputType.BUTTON}" icon="menu" @or-mwc-input-changed="${onopen}"></or-mwc-input>+ `)}+ </div>+ <div id="fullscreen-header-title">+ <span>${selected?.displayName}</span>+ </div>+ <div>+ <div>+ <or-mwc-input id="refresh-btn" class="small-btn" .disabled="${(selected == null)}" type="${InputType.BUTTON}" icon="refresh"+ @or-mwc-input-changed="${onrefresh}"+ ></or-mwc-input>+ </div>+ </div>+ </div>+ </div>+ `+}diff --git a/ui/component/or-app/src/index.ts b/ui/component/or-app/src/index.tsindex f8a691f51..de21b823a 100644--- a/ui/component/or-app/src/index.ts+++ b/ui/component/or-app/src/index.ts@@ -25,9 +25,9 @@ import { InputType, OrInputChangedEvent } from "@openremote/or-mwc-components/orimport { ORError } from "@openremote/core";import { Auth, ManagerConfig, Realm } from "@openremote/model";-const DefaultLogo = require("../images/logo.svg");-const DefaultMobileLogo = require("../images/logo-mobile.svg");-const DefaultFavIcon = require("../images/favicon.ico");+export const DefaultLogo = require("../images/logo.svg");+export const DefaultMobileLogo = require("../images/logo-mobile.svg");+export const DefaultFavIcon = require("../images/favicon.ico");export {AnyAction};export * from "./app";diff --git a/ui/component/or-chart/src/index.ts b/ui/component/or-chart/src/index.tsindex 4e306c270..48173bdba 100644--- a/ui/component/or-chart/src/index.ts+++ b/ui/component/or-chart/src/index.ts@@ -377,7 +377,7 @@ export class OrChart extends translate(i18next)(LitElement) {public colors: string[] = ["#3869B1", "#DA7E30", "#3F9852", "#CC2428", "#6B4C9A", "#922427", "#958C3D", "#535055"];@property({type: Object})- public datapointQuery!: AssetDatapointQueryUnion;+ public readonly datapointQuery!: AssetDatapointQueryUnion;@property({type: Object})public config?: OrChartConfig;@@ -1064,7 +1064,7 @@ export class OrChart extends translate(i18next)(LitElement) {if (asset.id && attribute.name && this.datapointQuery) {let response: GenericAxiosResponse<ValueDatapoint<any>[]>;- const query = this.datapointQuery;+ const query = JSON.parse(JSON.stringify(this.datapointQuery)); // recreating object, since the changes shouldn't apply to parent components; only or-chart itself.query.fromTimestamp = this._startOfPeriod;query.toTimestamp = this._endOfPeriod;diff --git a/ui/component/or-dashboard-builder/src/index.ts b/ui/component/or-dashboard-builder/src/index.tsindex b3fe3e0b5..58f0674d8 100644--- a/ui/component/or-dashboard-builder/src/index.ts+++ b/ui/component/or-dashboard-builder/src/index.ts@@ -21,7 +21,7 @@ import {DashboardTemplate,DashboardWidget} from "@openremote/model";-import manager, {DefaultColor1, DefaultColor3, DefaultColor5} from "@openremote/core";+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";@@ -325,7 +325,7 @@ export class OrDashboardBuilder extends LitElement {// Setting dashboard if selectedId is given by parent componentif(this.selectedId != undefined) {- this.selectedDashboard = Object.assign({}, this.dashboards?.find(x => { return x.id == this.selectedId; }));+ this.selectedDashboard = this.dashboards?.find(x => { return x.id == this.selectedId; });}}@@ -339,7 +339,9 @@ export class OrDashboardBuilder extends LitElement {// On any update (except widget selection), check whether hasChanged should be updated.if(!(changedProperties.size == 1 && changedProperties.has('selectedWidget'))) {- this.hasChanged = (JSON.stringify(this.selectedDashboard) != this.initialDashboardJSON || JSON.stringify(this.currentTemplate) != this.initialTemplateJSON);+ 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@@ -442,6 +444,13 @@ export class OrDashboardBuilder extends LitElement {}}+ openDashboardInInsights() {+ if(this.selectedDashboard != null) {+ const insightsUrl: string = (window.location.origin + "/insights/?realm=" + manager.displayRealm + "#/view/" + this.selectedDashboard.id + "/true/"); // Just using relative URL to origin, as its enough for now.+ window.open(insightsUrl)?.focus();+ }+ }+shareUrl(method: string) {let url = window.location.href.replace("true", "false");if(method == 'copy') {@@ -546,6 +555,9 @@ export class OrDashboardBuilder extends LitElement {<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>@@ -566,7 +578,12 @@ 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="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></div>diff --git a/ui/component/or-dashboard-builder/src/or-dashboard-boardsettings.ts b/ui/component/or-dashboard-builder/src/or-dashboard-boardsettings.tsindex 0e7e1db32..3193848ef 100644--- a/ui/component/or-dashboard-builder/src/or-dashboard-boardsettings.ts+++ b/ui/component/or-dashboard-builder/src/or-dashboard-boardsettings.ts@@ -71,9 +71,7 @@ export class OrDashboardBoardsettings extends LitElement {private setViewAccess(access: DashboardAccess) {this.dashboard.viewAccess = access;if(access == DashboardAccess.PRIVATE) {- this.dashboard.editAccess = DashboardAccess.PRIVATE;- } else if(this.dashboard.editAccess == DashboardAccess.PRIVATE) {- this.dashboard.editAccess = access;+ this.dashboard.editAccess = DashboardAccess.PRIVATE; // if viewAccess changed to PRIVATE, make editAccess private as well.}this.requestUpdate();this.forceParentUpdate(false);@@ -92,10 +90,8 @@ export class OrDashboardBoardsettings extends LitElement {protected render() {if(this.dashboard.template?.screenPresets != null) {const screenPresets = sortScreenPresets(this.dashboard.template.screenPresets, true);- const accessOptions: {key: DashboardAccess, value: string}[] = [];- [DashboardAccess.PRIVATE, DashboardAccess.SHARED, /*DashboardAccess.PUBLIC*/].forEach((access) => {- accessOptions.push({key: access, value: dashboardAccessToString(access)})- })+ 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}[] = [];[DashboardScalingPreset.KEEP_LAYOUT, DashboardScalingPreset.WRAP_TO_SINGLE_COLUMN, /*DashboardScalingPreset.REDIRECT,*/ DashboardScalingPreset.BLOCK_DEVICE].forEach((preset: DashboardScalingPreset) => {scalingPresets.push({key: preset, value: scalingPresetToString(preset) });@@ -111,9 +107,9 @@ export class OrDashboardBoardsettings extends LitElement {${html`<span>${unsafeHTML(i18next.t('dashboard.whoCanView').toString())}</span>`}</div><or-mwc-input class="permissionInput" comfortable type="${InputType.SELECT}" style="width: 250px;"- .options="${accessOptions.map((access) => access.value)}"+ .options="${viewAccessOptions.map((access) => access.value)}".value="${dashboardAccessToString(this.dashboard.viewAccess!)}"- @or-mwc-input-changed="${(event: OrInputChangedEvent) => { this.setViewAccess(accessOptions.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;">@@ -122,9 +118,9 @@ export class OrDashboardBoardsettings extends LitElement {</div><or-mwc-input class="permissionInput" comfortable type="${InputType.SELECT}" style="width: 250px;".disabled="${(this.dashboard.viewAccess == DashboardAccess.PRIVATE)}"- .options="${accessOptions.map((access) => access.value)}"+ .options="${editAccessOptions.map((access) => access.value)}".value="${dashboardAccessToString(this.dashboard.editAccess!)}"- @or-mwc-input-changed="${(event: OrInputChangedEvent) => { this.setEditAccess(accessOptions.find((access) => access.value == event.detail.value)?.key!); }}"+ @or-mwc-input-changed="${(event: OrInputChangedEvent) => { this.setEditAccess(editAccessOptions.find((access) => access.value == event.detail.value)?.key!); }}"></or-mwc-input></div></div>diff --git a/ui/component/or-dashboard-builder/src/or-dashboard-settingspanel.ts b/ui/component/or-dashboard-builder/src/or-dashboard-settingspanel.tsindex e799868f6..cfbc36d62 100644--- a/ui/component/or-dashboard-builder/src/or-dashboard-settingspanel.ts+++ b/ui/component/or-dashboard-builder/src/or-dashboard-settingspanel.ts@@ -1,8 +1,6 @@import manager, {DefaultColor5, Util} from "@openremote/core";import {- Asset, AssetModelUtil, AttributeRef, AssetQuery, WellknownAssets,- AssetDescriptor, WellknownMetaItems, GeoJSONPoint, WellknownAttributes,- Attribute, AssetQueryOrderBy$Property, AssetTypeInfo,+ Asset, AssetModelUtil, AttributeRef, AssetDescriptor, AssetTypeInfo,} from "@openremote/model";import {OrAttributePicker, OrAttributePickerPickedEvent} from "@openremote/or-attribute-picker";import {getAssetDescriptorIconTemplate} from "@openremote/or-icon";@@ -136,7 +134,7 @@ export class OrDashboardSettingsPanel extends LitElement {// and fetching assets if any of the AttributeRefs are not pulled yet.willUpdate(changedProperties: Map<string, any>) {if (changedProperties.has("widgetConfig")) {- if (!this._config || (changedProperties.get("widgetConfig") != this._config) && this.widgetConfig.attributeRefs) {+ if (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 => {@@ -448,32 +446,22 @@ export class OrDashboardSettingsPanel extends LitElement {/* ---------------------------------------------------- */- async getAssetTypes(config: OrWidgetConfig | any) {- const response = await manager.rest.api.AssetResource.queryAssets({- realm: {- name: manager.displayRealm- },- select: {- attributes: []- },- });- if (response && response.data) {- const types: string[] = response.data.map(asset => asset.type!).filter((type, index, asset) => asset.indexOf(type) === index).sort();- return types.map((type) => AssetModelUtil.getAssetDescriptor(type)!).filter((t) => t.descriptorType === "asset");- }+ async getAssetTypes() {+ return AssetModelUtil.getAssetDescriptors().filter((t) => t.descriptorType == "asset");}getAttributesByType(type: string) {const descriptor: AssetDescriptor = (AssetModelUtil.getAssetDescriptor(type) as AssetDescriptor);- const typeInfo: AssetTypeInfo = (AssetModelUtil.getAssetTypeInfo(descriptor) as AssetTypeInfo);-- if (typeInfo.attributeDescriptors) {- return typeInfo.attributeDescriptors.filter((ad) => {- return this._allowedValueTypes.indexOf(ad.type!) > -1;- }).map((ad) => {- const label = Util.getAttributeLabel(ad, undefined, type, false);- return [ad.name!, label];- }).sort(Util.sortByString((attr) => attr[1]));+ 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]));+ }}}@@ -528,7 +516,7 @@ export class OrDashboardSettingsPanel extends LitElement {protected handleTypeSelect(value: string) {if (this._config.assetType !== value) {this._config.attributeName = undefined;- this._config.assets = [];+ this._config.assetIds = [];this._config.showLabels = false;this._config.showUnits = false;this._config.boolColors = {type: 'boolean', 'false': '#ef5350', 'true': '#4caf50'};@@ -551,8 +539,8 @@ export class OrDashboardSettingsPanel extends LitElement {},types: [this._config.assetType],}).then(response => {- this._config.assets = response.data;- this._config.valueType = response.data[0].attributes![value].type;+ 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'));@@ -562,67 +550,61 @@ export class OrDashboardSettingsPanel extends LitElement {}async getAssettypesHTML(config: OrWidgetConfig | any) {- if (config.assetTypes) {- if (this._loadedAssetTypes.length === 0) {- this._loadedAssetTypes = await this.getAssetTypes(config) as AssetDescriptor[]- }- return html`- <div style="padding: 12px 24px 24px 24px; display: flex; flex-direction: column; gap: 16px;">- ${(config.assetType) ? html`- ${this._loadedAssetTypes.length > 0 ? getContentWithMenuTemplate(- this.assetTypeSelect(),- this.mapDescriptors(this._loadedAssetTypes, {- text: i18next.t("filter.assetTypeMenuNone"),- value: "",- icon: "selection-ellipse"- }) as ListItem[],- undefined,- (v: string[] | string) => {- this.handleTypeSelect(v as string);- },- undefined,- false,- true,- true) : html``- }-- <div>- <or-mwc-input .type="${InputType.SELECT}" style="width: 100%;"- .options="${this._config.attributes}"- .value="${config.attributeName}" label="${i18next.t('filter.attributeLabel')}"- @or-mwc-input-changed="${(event: CustomEvent) => {- this.handleAttributeSelect(event.detail.value);- }}"- ></or-mwc-input>- </div>- <div style="padding: 0 10px 12px 10px;">- <div class="switchMwcInputContainer">- <span>${i18next.t('dashboard.showLabels')}</span>- <or-mwc-input .type="${InputType.SWITCH}" style="width: 70px;"- .value="${config.showLabels}"- @or-mwc-input-changed="${(event: CustomEvent) => {- this._config.showLabels = event.detail.value;- this.updateParent(new Map<string, any>([["config", this._config]]));- }}"- ></or-mwc-input>- </div>- <div class="switchMwcInputContainer">- <span>${i18next.t('dashboard.showUnits')}</span>- <or-mwc-input .type="${InputType.SWITCH}" style="width: 70px;"- .value="${config.showUnits}"- .disabled="${!config.showLabels}"- @or-mwc-input-changed="${(event: CustomEvent) => {- this._config.showUnits = event.detail.value;- this.updateParent(new Map<string, any>([["config", this._config]]));- }}"- ></or-mwc-input>- </div>-- </div>+ if (this._loadedAssetTypes.length === 0) {+ this._loadedAssetTypes = await this.getAssetTypes() as AssetDescriptor[]+ }+ return html`+ <div style="padding: 12px 24px 24px 24px; display: flex; flex-direction: column; gap: 16px;">+ ${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 style="padding: 0 10px 12px 10px;">+ <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>- ` : undefined}</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.tsindex 211cdbf2c..388e393cb 100644--- a/ui/component/or-dashboard-builder/src/or-dashboard-tree.ts+++ b/ui/component/or-dashboard-builder/src/or-dashboard-tree.ts@@ -142,7 +142,7 @@ export class OrDashboardTree extends LitElement {private deleteDashboard(dashboard: Dashboard) {if(dashboard.id != null) {- manager.rest.api.DashboardResource.delete({dashboardId: [dashboard.id]})+ manager.rest.api.DashboardResource.delete(dashboard.id).then((response) => {if(response.status == 204) {this.getAllDashboards();@@ -210,7 +210,7 @@ export class OrDashboardTree extends LitElement {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>- <div id="list-container">+ <div id="list-container" style="overflow: hidden;"><ol id="list">${items.map((listItem: ListItem) => {return html`diff --git a/ui/component/or-dashboard-builder/src/or-dashboard-widget.ts b/ui/component/or-dashboard-builder/src/or-dashboard-widget.tsindex 79f416a42..a11cf1dba 100644--- a/ui/component/or-dashboard-builder/src/or-dashboard-widget.ts+++ b/ui/component/or-dashboard-builder/src/or-dashboard-widget.ts@@ -104,12 +104,9 @@ export class OrDashboardWidget extends LitElement {}getWidgetContent(widget: DashboardWidget): TemplateResult {- const _widget = Object.assign({}, widget);- if(_widget.gridItem) {-+ if(widget.gridItem) {const widgetEntity = widgetTypes.get(widget.widgetTypeId!);- return widgetEntity!.getWidgetHTML(this.widget!, this.editMode!, this.realm!);-+ return widgetEntity!.getWidgetHTML(widget, this.editMode!, this.realm!);}return html`<span>${i18next.t('error')}!</span>`;}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.tsindex 2e72a5395..2b7ee8d69 100644--- a/ui/component/or-dashboard-builder/src/widgets/or-map-widget.ts+++ b/ui/component/or-dashboard-builder/src/widgets/or-map-widget.ts@@ -53,7 +53,7 @@ export interface MapWidgetConfig extends OrWidgetConfig {valueType?: string,attributeName?: string,assetTypes: AssetDescriptor[],- assets: Asset[],+ assetIds: string[],attributes: string[],}@@ -78,8 +78,8 @@ export class OrMapWidget implements OrWidgetEntity {textColors: [['example', '4caf50'], ['example2', 'ef5350']],thresholds: [[0, "#4caf50"], [75, "#ff9800"], [90, "#ef5350"]],assetTypes: [],- assetType: " ",- assets: [],+ assetType: undefined,+ assetIds: [],attributes: [],} as MapWidgetConfig;}@@ -115,7 +115,7 @@ export class OrMapWidgetContent extends LitElement {public realm?: string;@state()- private assets: Asset[] = [];+ private assets?: Asset[] = [];@query("#miniMap")protected _map?: OrMap;@@ -138,7 +138,7 @@ export class OrMapWidgetContent extends LitElement {return false;}const attr = asset.attributes[WellknownAttributes.LOCATION] as Attribute<GeoJSONPoint>;- return !attr.meta || !attr.meta.hasOwnProperty(WellknownMetaItems.SHOWONDASHBOARD) || !!Util.getMetaValue(WellknownMetaItems.SHOWONDASHBOARD, attr);+ return !attr || !attr.meta || !attr.meta.hasOwnProperty(WellknownMetaItems.SHOWONDASHBOARD) || !!Util.getMetaValue(WellknownMetaItems.SHOWONDASHBOARD, attr);}).map(asset => {if (this.markers) {// Configure map marker asset settings@@ -184,7 +184,8 @@ export class OrMapWidgetContent extends LitElement {updated(changedProperties: Map<string, any>) {if (changedProperties.has("widget") || changedProperties.has("editMode")) {- if (this.assets !== this.widget!.widgetConfig.assets || this.assets.length === 0) {+ 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!;});@@ -299,7 +300,7 @@ class OrMapWidgetSettings extends LitElement {</or-dashboard-settingspanel>` : null}</div>- ${this.widget?.widgetConfig.assets.length > 0 ? html`+ ${this.widget?.widgetConfig?.assetIds?.length > 0 ? html`<div>${this.generateExpandableHeader(i18next.t('thresholds'))}</div>diff --git a/ui/component/or-mwc-components/src/or-mwc-menu.ts b/ui/component/or-mwc-components/src/or-mwc-menu.tsindex 63d79bb22..b760806ad 100644--- a/ui/component/or-mwc-components/src/or-mwc-menu.ts+++ b/ui/component/or-mwc-components/src/or-mwc-menu.ts@@ -7,6 +7,7 @@ import {unsafeCSS} from "lit";import {customElement, property, query} from "lit/decorators.js";+import {classMap} from 'lit/directives/class-map.js';import {MDCMenu} from "@material/menu";import {DefaultColor4, DefaultColor8} from "@openremote/core";@@ -50,7 +51,7 @@ declare global {}}-export function getContentWithMenuTemplate(content: TemplateResult, menuItems: (ListItem | ListItem[] | null)[], selectedValues: string[] | string | undefined, valueChangedCallback: (values: string[] | string) => void, closedCallback?: () => void, multiSelect = false, translateValues = true, midHeight = false): TemplateResult {+export function getContentWithMenuTemplate(content: TemplateResult, menuItems: (ListItem | ListItem[] | null)[], selectedValues: string[] | string | undefined, valueChangedCallback: (values: string[] | string) => void, closedCallback?: () => void, multiSelect = false, translateValues = true, midHeight = false, fullWidth = false): TemplateResult {const openMenu = (evt: Event) => {if (!menuItems) {@@ -63,7 +64,7 @@ export function getContentWithMenuTemplate(content: TemplateResult, menuItems: (return html`<span><span @click="${openMenu}">${content}</span>- ${menuItems ? html`<or-mwc-menu ?multiselect="${multiSelect}" @or-mwc-menu-closed="${() => {if (closedCallback) { closedCallback(); }} }" @or-mwc-menu-changed="${(evt: OrMwcMenuChangedEvent) => {if (valueChangedCallback) { valueChangedCallback(evt.detail); }} }" .translateValues="${translateValues}" .values="${selectedValues}" .menuItems="${menuItems}" .midHeight="${midHeight}" id="menu"></or-mwc-menu>` : ``}+ ${menuItems ? html`<or-mwc-menu ?multiselect="${multiSelect}" @or-mwc-menu-closed="${() => {if (closedCallback) { closedCallback(); }} }" @or-mwc-menu-changed="${(evt: OrMwcMenuChangedEvent) => {if (valueChangedCallback) { valueChangedCallback(evt.detail); }} }" .translateValues="${translateValues}" .values="${selectedValues}" .menuItems="${menuItems}" .midHeight="${midHeight}" .fullWidth="${fullWidth}" id="menu"></or-mwc-menu>` : ``}</span>`;}@@ -90,7 +91,10 @@ const style = css`}.mdc-menu-surface-mid-height {- max-height: calc(50vh - 32px) !important;+ max-height: calc(45vh - 32px) !important;+ }+ .mdc-menu-surface-full-width {+ width: 100%;}`;@@ -124,6 +128,9 @@ export class OrMwcMenu extends LitElement {@property({type: Boolean, attribute: false})public midHeight?: boolean;+ @property({type: Boolean, attribute: false})+ public fullWidth?: boolean;+@query("#wrapper")protected _wrapperElem!: HTMLElement;@@ -153,9 +160,13 @@ export class OrMwcMenu extends LitElement {const content = this.getItemsTemplate(this.menuItems, this.translateValues);const isTwoLine = this.menuItems && this.menuItems.some((item) => item && !Array.isArray(item) && !!item.secondaryText);+ const classes = {+ 'mdc-menu-surface-mid-height': (this.midHeight ? 1 : 0),+ 'mdc-menu-surface-full-width': (this.fullWidth ? 1 : 0)+ }return html`<div id="wrapper" class="mdc-menu-surface--anchor">- <div class="mdc-menu mdc-menu-surface ${this.midHeight ? "mdc-menu-surface-mid-height" : ""}" id="menu" @MDCMenuSurface:closed="${this._onMenuClosed}">+ <div class="mdc-menu mdc-menu-surface ${classMap(classes)}" id="menu" @MDCMenuSurface:closed="${this._onMenuClosed}">${getListTemplate(ListType.MULTI_TICK, content, isTwoLine, "menu")}</div></div>