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
First integration of insights dashboard (#742)
Martin Peetersd0ac14c6f8ad
diff --git a/container/src/main/java/org/openremote/container/persistence/PersistenceService.java b/container/src/main/java/org/openremote/container/persistence/PersistenceService.javaindex 9b249a35d..c4c35109e 100644--- a/container/src/main/java/org/openremote/container/persistence/PersistenceService.java+++ b/container/src/main/java/org/openremote/container/persistence/PersistenceService.java@@ -37,6 +37,7 @@ import org.openremote.model.apps.ConsoleAppConfig;import org.openremote.model.asset.Asset;import org.openremote.model.asset.AssetDescriptor;import org.openremote.model.asset.UserAssetLink;+import org.openremote.model.dashboard.Dashboard;import org.openremote.model.datapoint.AssetDatapoint;import org.openremote.model.gateway.GatewayConnection;import org.openremote.model.notification.SentNotification;@@ -307,6 +308,7 @@ public class PersistenceService implements ContainerService, Consumer<PersistencentityClasses.add(SyslogEvent.class.getName());entityClasses.add(GatewayConnection.class.getName());entityClasses.add(ConsoleAppConfig.class.getName());+ entityClasses.add(Dashboard.class.getName());entityClasses.add(ProvisioningConfig.class.getName());entityClasses.add(X509ProvisioningConfig.class.getName());diff --git a/manager/src/main/java/org/openremote/manager/dashboard/DashboardResourceImpl.java b/manager/src/main/java/org/openremote/manager/dashboard/DashboardResourceImpl.javanew file mode 100644index 000000000..36149e4b5--- /dev/null+++ b/manager/src/main/java/org/openremote/manager/dashboard/DashboardResourceImpl.java@@ -0,0 +1,94 @@+package org.openremote.manager.dashboard;++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.dashboard.Dashboard;+import org.openremote.model.dashboard.DashboardResource;+import org.openremote.model.dashboard.DashboardAccess;+import org.openremote.model.http.RequestParams;+import org.openremote.model.util.ValueUtil;++import javax.ws.rs.WebApplicationException;++import java.util.List;++import static javax.ws.rs.core.Response.Status.*;++public class DashboardResourceImpl extends ManagerWebResource implements DashboardResource {++ protected final DashboardStorageService dashboardStorageService;+ protected final MessageBrokerService messageBrokerService;++ public DashboardResourceImpl(TimerService timerService, ManagerIdentityService identityService, DashboardStorageService dashboardStorageService, MessageBrokerService messageBrokerService) {+ super(timerService, identityService);+ this.dashboardStorageService = dashboardStorageService;+ this.messageBrokerService = messageBrokerService;+ }+++ @Override+ public Dashboard[] getAllRealmDashboards(RequestParams requestParams, String realm) {++ try {+ if(!isRealmActiveAndAccessible(realm)) {+ throw new WebApplicationException(FORBIDDEN);+ }+ return this.dashboardStorageService.findAllOfRealm(realm, getUserId());++ } catch (IllegalStateException ex) {+ throw new WebApplicationException(ex, BAD_REQUEST);+ }+ }++ @Override+ public Dashboard get(RequestParams requestParams, String dashboardId) {+ return this.dashboardStorageService.get(dashboardId);+ }++ @Override+ public Dashboard create(RequestParams requestParams, Dashboard dashboard) {+ 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);++ return this.dashboardStorageService.createNew(ValueUtil.clone(dashboard));++ } catch (IllegalStateException ex) {+ ex.printStackTrace();+ throw new WebApplicationException(ex, INTERNAL_SERVER_ERROR);+ }+ }++ @Override+ public void update(RequestParams requestParams, Dashboard dashboard) {+ try {++ // Check if access to realm+ if(!isRealmActiveAndAccessible(dashboard.getRealm())) {+ throw new WebApplicationException(FORBIDDEN);+ }+ this.dashboardStorageService.update(ValueUtil.clone(dashboard), getUserId());+ } catch (IllegalStateException ex) {+ ex.printStackTrace();+ throw new WebApplicationException(ex, INTERNAL_SERVER_ERROR);+ }+ }++ @Override+ public void delete(RequestParams requestParams, List<String> fields) {+ try {+ this.dashboardStorageService.delete(fields, getUserId());+ } 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.javanew file mode 100644index 000000000..7521e83ce--- /dev/null+++ b/manager/src/main/java/org/openremote/manager/dashboard/DashboardStorageService.java@@ -0,0 +1,168 @@+package org.openremote.manager.dashboard;++import org.apache.camel.builder.RouteBuilder;+import org.openremote.container.message.MessageBrokerService;+import org.openremote.container.persistence.PersistenceService;+import org.openremote.container.timer.TimerService;+import org.openremote.manager.security.ManagerIdentityService;+import org.openremote.manager.web.ManagerWebService;+import org.openremote.model.Container;+import org.openremote.model.ContainerService;+import org.openremote.model.dashboard.Dashboard;+import org.openremote.model.dashboard.DashboardAccess;++import javax.persistence.Query;+import javax.persistence.TypedQuery;+import javax.persistence.criteria.CriteriaBuilder;+import javax.persistence.criteria.CriteriaQuery;+import javax.persistence.criteria.Predicate;+import javax.persistence.criteria.Root;+import javax.ws.rs.WebApplicationException;+import java.util.ArrayList;+import java.util.Collection;+import java.util.List;++import static javax.ws.rs.core.Response.Status.FORBIDDEN;+import static javax.ws.rs.core.Response.Status.NOT_FOUND;++public class DashboardStorageService extends RouteBuilder implements ContainerService {++ protected ManagerIdentityService identityService;+ protected PersistenceService persistenceService;++ @Override+ public int getPriority() {+ return ContainerService.DEFAULT_PRIORITY;+ }++ @Override+ public void configure() throws Exception {+ /* code not overridden yet */+ }++ @Override+ public void init(Container container) throws Exception {+ identityService = container.getService(ManagerIdentityService.class);+ persistenceService = container.getService(PersistenceService.class);+ container.getService(ManagerWebService.class).addApiSingleton(+ new DashboardResourceImpl(+ container.getService(TimerService.class),+ identityService,+ this,+ container.getService(MessageBrokerService.class)+ )+ );+ }++ @Override+ public void start(Container container) throws Exception {+ /* code not overridden yet */+ }++ @Override+ public void stop(Container container) throws Exception {+ /* code not overridden yet */++ }+++ /* -------------------------- */++ // 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) {+ 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));+ }+ 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))+ ));+ } else {+ predicates.add(cb.or(+ root.get("viewAccess").in(DashboardAccess.PUBLIC, DashboardAccess.SHARED),+ 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]);++ } catch (Exception e) {+ e.printStackTrace();+ }+ return new Dashboard[0]; // Empty array if nothing found.+ });+ }++ @SuppressWarnings("java:S2326")+ protected <T extends Dashboard> Dashboard get(String id) {+ return persistenceService.doReturningTransaction(em -> em.find(Dashboard.class, id));+ }+++ // Creation of initial dashboard (so no updating!)+ protected <T extends Dashboard> T createNew(T dashboard) {+ 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+ if(d != null) {+ throw new IllegalArgumentException("This dashboard has already been created.");+ }+ }+ return em.merge(dashboard);+ });+ }++ // 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.+ return em.merge(dashboard);+ } else {+ throw new WebApplicationException("This dashboard does not exist!", NOT_FOUND);+ }+ });+ }++ protected boolean delete(List<String> dashboardIds, String userId) {+ 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;+ }+ });+ }+}diff --git a/manager/src/main/java/org/openremote/manager/setup/AbstractKeycloakSetup.java b/manager/src/main/java/org/openremote/manager/setup/AbstractKeycloakSetup.javaindex 814e69e5c..11dda0e9c 100644--- a/manager/src/main/java/org/openremote/manager/setup/AbstractKeycloakSetup.java+++ b/manager/src/main/java/org/openremote/manager/setup/AbstractKeycloakSetup.java@@ -41,7 +41,8 @@ public abstract class AbstractKeycloakSetup implements Setup {public static final ClientRole[] PUBLIC_USER_ROLES = new ClientRole[] {ClientRole.READ_ASSETS,- ClientRole.READ_MAP+ ClientRole.READ_MAP,+ ClientRole.READ_INSIGHTS};public static final ClientRole[] REGULAR_USER_ROLES = new ClientRole[] {ClientRole.WRITE_USER,@@ -49,9 +50,11 @@ public abstract class AbstractKeycloakSetup implements Setup {ClientRole.READ_ASSETS,ClientRole.READ_USERS,ClientRole.READ_RULES,+ ClientRole.READ_INSIGHTS,ClientRole.WRITE_ASSETS,ClientRole.WRITE_ATTRIBUTES,- ClientRole.WRITE_RULES+ ClientRole.WRITE_RULES,+ ClientRole.WRITE_INSIGHTS};final protected Container container;diff --git a/manager/src/main/resources/META-INF/services/org.openremote.model.ContainerService b/manager/src/main/resources/META-INF/services/org.openremote.model.ContainerServiceindex e6c4d6af8..a6f61da7c 100644--- a/manager/src/main/resources/META-INF/services/org.openremote.model.ContainerService+++ b/manager/src/main/resources/META-INF/services/org.openremote.model.ContainerService@@ -29,4 +29,5 @@ org.openremote.manager.energy.EnergyOptimisationServiceorg.openremote.manager.energy.ForecastWindServiceorg.openremote.manager.energy.ForecastSolarServiceorg.openremote.manager.provisioning.ProvisioningService+org.openremote.manager.dashboard.DashboardStorageServiceorg.openremote.manager.security.AuthorisationServicediff --git a/manager/src/main/resources/org/openremote/manager/setup/database/V20220705_01__Schema.sql b/manager/src/main/resources/org/openremote/manager/setup/database/V20220705_01__Schema.sqlnew file mode 100644index 000000000..e21d69576--- /dev/null+++ b/manager/src/main/resources/org/openremote/manager/setup/database/V20220705_01__Schema.sql@@ -0,0 +1,12 @@+create table DASHBOARD (+ ID varchar(22) not null,+ CREATED_ON timestamp with time zone not null,+ REALM varchar(255) not null,+ VERSION int8 not null,+ OWNER_ID varchar(255) not null,+ VIEW_ACCESS int8 not null,+ EDIT_ACCESS int8 not null,+ DISPLAY_NAME varchar(255) not null,+ TEMPLATE jsonb not null,+ primary key (ID)+);diff --git a/manager/src/web/shared/locales/en/or.json b/manager/src/web/shared/locales/en/or.jsonindex 671b6d710..147c332b7 100644--- a/manager/src/web/shared/locales/en/or.json+++ b/manager/src/web/shared/locales/en/or.json@@ -165,6 +165,7 @@"noRuleStateAttributes": "No attributes with 'rule state' or 'agent link' configuration item found","noDatapointsAttributes": "No attributes with 'store data points' or 'agent link' configuration item found","noAttributesToShow": "No attributes found",+ "noAttributesConnected": "No attributes connected.","noDatapointsOrRuleStateAttributes": "No attributes with 'rule state', 'store data points', or 'agent link' configuration item found","copy": "Copy","paste": "Paste",@@ -204,6 +205,7 @@"notSupported": "Not supported","ruleName": "Rule name","value": "Value",+ "values": "Values","and": "and","number": "Number","string": "Text",@@ -323,6 +325,8 @@"closed": "Closed","on": "On","off": "Off",+ "min": "Min",+ "max": "Max","units": {"per": "/","squared": "²",@@ -504,5 +508,61 @@"assetTypeDoesNotExist": "Filter : Asset type does not exist"},"realmDeleteConfirm": "Warning! this will delete everything in this realm, type the realm name '{{realmName}}' to confirm.",- "realmDeleteFailed": "Failed to delete realm"+ "realmDeleteFailed": "Failed to delete realm",+ "public": "Public",+ "shared": "Shared",+ "private": "Private",+ "width": "Width",+ "height": "Height",+ "layout": "Layout",+ "display": "Display",+ "screen": "Screen",+ "thresholds": "Thresholds",+ "noDashboardSelected": "Please select a dashboard on the left",+ "noDashboardFound": "No dashboard could be found.",+ "noDashboardWriteAccess": "You don't have access to edit this dashboard.",+ "confirmContinueDashboardModified": "Dashboard has been edited, do you want to discard the changes?",+ "dashboards": "Dashboards",+ "dashboard": {+ "widget": "Widget",+ "widgets": "Widgets",+ "widget-kpi": "KPI",+ "widget-linechart": "Line Chart",+ "presets.wrap_to_single_column": "Wrap to single column",+ "presets.keep_layout": "Keep layout",+ "presets.block_device": "Block this device",+ "presets.redirect": "Redirect to a different dashboard..",+ "size.fullscreen": "Fullscreen",+ "size.large": "Large",+ "size.desktop": "Desktop",+ "size.medium": "Medium",+ "size.small": "Small",+ "size.mobile": "Mobile",+ "size.custom": "Custom size",+ "access.public": "Public",+ "access.shared": "Realm Users",+ "access.private": "Only me",+ "saveSuccessful": "Saved dashboard successfully!",+ "initialName": "New Dashboard",+ "openInNewTab": "Open in new tab",+ "whoCanView": "Who can <b>view</b> the dashboard?",+ "whoCanEdit": "Who can <b>edit</b> the dashboard?",+ "numberOfColumns": "Number of columns",+ "maxScreenWidth": "Max screen width",+ "onScreenMyBoardShould": "On a {{size}} screen my board should:",+ "setToMobilePreset": "Set Mobile Preset",+ "zoomPercent": "Zoom %",+ "presetSize": "Preview size",+ "renderingGrid": "Rendering grid...",+ "deviceNotSupported": "This dashboard does not support your device.",+ "deletePermanentWarning": "This will delete {{dashboard}} permanently.",+ "deleteWidgetWarning": "This will remove the widget from your board, and be permanently deleted after saving.",+ "widgetTooSmall": "Widget is too small.",+ "showTimestampControls": "Show timestamp controls",+ "showLegend": "Show legend",+ "showValueAs": "Show value as",+ "deleteWidget": "Delete widget",+ "myDashboards": "My dashboards",+ "createdByOthers": "Created by others"+ }}diff --git a/manager/src/web/shared/locales/nl/or.json b/manager/src/web/shared/locales/nl/or.jsonindex 3be62a456..e48c3d3c7 100644--- a/manager/src/web/shared/locales/nl/or.json+++ b/manager/src/web/shared/locales/nl/or.json@@ -203,6 +203,7 @@"notSupported": "Niet ondersteund","ruleName": "Regel naam","value": "Waarde",+ "values": "Waardes","and": "en","number": "Nummer","string": "Tekst",@@ -322,6 +323,8 @@"closed": "Gesloten","on": "Aan","off": "Uit",+ "min": "Min",+ "max": "Max","units": {"per": "/","squared": "²",@@ -497,5 +500,61 @@"attributeLabel": "Attribuut","attributeValueLabel": "Attribuutwaarde","assetTypeDoesNotExist": "Filter: Asset type bestaat niet"+ },+ "public": "Openbaar",+ "shared": "Gedeeld",+ "private": "Prive",+ "width": "Breedte",+ "height": "Hoogte",+ "layout": "Indeling",+ "display": "Weergave",+ "screen": "Scherm",+ "thresholds": "Drempelwaardes",+ "noDashboardSelected": "Selecteer een dashboard aan de linkerkant",+ "noDashboardFound": "Geen dashboard gevonden.",+ "noDashboardWriteAccess": "U heeft geen rechten om dit dashboard aan te passen.",+ "confirmContinueDashboardModified": "Dashboard is aangepast, wijzigingen negeren?",+ "dashboards": "Dashboards",+ "dashboard": {+ "widget": "Widget",+ "widgets": "Widgets",+ "widget-kpi": "KPI",+ "widget-linechart": "Lijngrafiek",+ "presets.wrap_to_single_column": "Widgets onder elkaar zetten",+ "presets.keep_layout": "Behoud indeling",+ "presets.block_device": "Blokkeer dit apparaat",+ "presets.redirect": "Open een ander dashboard..",+ "size.fullscreen": "Volledig scherm",+ "size.large": "Groot",+ "size.desktop": "Desktop",+ "size.medium": "Medium",+ "size.small": "Klein",+ "size.mobile": "Mobiel",+ "size.custom": "Specifieke grootte",+ "access.public": "Openbaar",+ "access.shared": "Realm gebruikers",+ "access.private": "Alleen ik",+ "saveSuccessful": "Dashboard succesvol opgeslagen!",+ "initialName": "Nieuw dashboard",+ "openInNewTab": "Openen in een nieuw tabblad",+ "whoCanView": "Wie kan het dashboard <b>bekijken</b>?",+ "whoCanEdit": "Wie kan het dashboard <b>bewerken</b>?",+ "numberOfColumns": "Aantal kolommen",+ "maxScreenWidth": "Max schermbreedte",+ "onScreenMyBoardShould": "Op een {{size}} scherm moet het bord:",+ "setToMobilePreset": "Stel mobiel preset in",+ "zoomPercent": "Zoom %",+ "presetSize": "Voorbeeld grootte",+ "renderingGrid": "Grid aan het renderen...",+ "deviceNotSupported": "Dit dashboard wordt niet ondersteund op dit apparaat.",+ "deletePermanentWarning": "Dit zal {{dashboard}} permanent verwijderen.",+ "deleteWidgetWarning": "De widget zal worden weggehaald van het bord, en zal permanent worden verwijderd als u opslaat.",+ "widgetTooSmall": "Widget is te klein.",+ "showTimestampControls": "Toon tijdsopties",+ "showLegend": "Toon legenda",+ "showValueAs": "Laat waarde zien als",+ "deleteWidget": "Verwijder widget",+ "myDashboards": "Mijn dashboards",+ "createdByOthers": "Gemaakt door anderen"}}diff --git a/model/src/main/java/org/openremote/model/Constants.java b/model/src/main/java/org/openremote/model/Constants.javaindex 7871a0802..0371fc8ef 100644--- a/model/src/main/java/org/openremote/model/Constants.java+++ b/model/src/main/java/org/openremote/model/Constants.java@@ -34,12 +34,14 @@ public interface Constants {String READ_MAP_ROLE = "read:map";String READ_ASSETS_ROLE = "read:assets";String READ_RULES_ROLE = "read:rules";+ String READ_INSIGHTS_ROLE = "read:insights";String WRITE_USER_ROLE = "write:user";String WRITE_ADMIN_ROLE = "write:admin";String WRITE_LOGS_ROLE = "write:logs";String WRITE_ASSETS_ROLE = "write:assets";String WRITE_ATTRIBUTES_ROLE = "write:attributes";String WRITE_RULES_ROLE = "write:rules";+ String WRITE_INSIGHTS_ROLE = "write:insights";String RESTRICTED_USER_REALM_ROLE = "restricted_user";String AUTH_CONTEXT = "AUTH_CONTEXT";int ACCESS_TOKEN_LIFESPAN_SECONDS = 60; // 1 minutediff --git a/model/src/main/java/org/openremote/model/dashboard/Dashboard.java b/model/src/main/java/org/openremote/model/dashboard/Dashboard.javanew file mode 100644index 000000000..81e64c803--- /dev/null+++ b/model/src/main/java/org/openremote/model/dashboard/Dashboard.java@@ -0,0 +1,92 @@+package org.openremote.model.dashboard;++import javax.persistence.*;+import javax.validation.Valid;+import javax.validation.constraints.NotBlank;+import javax.validation.constraints.NotNull;+import javax.validation.constraints.Size;+import java.util.Date;++import static org.openremote.model.Constants.PERSISTENCE_JSON_VALUE_TYPE;+import static org.openremote.model.Constants.PERSISTENCE_UNIQUE_ID_GENERATOR;++@Entity+@Table(name = "DASHBOARD")+public class Dashboard {++ @Id+ @Column(name = "ID", length = 22, columnDefinition = "char(22)")+ @GeneratedValue(generator = PERSISTENCE_UNIQUE_ID_GENERATOR)+ protected String id;++ @Temporal(TemporalType.TIMESTAMP)+ @Column(name = "CREATED_ON", updatable = false, nullable = false, columnDefinition = "TIMESTAMP WITH TIME ZONE")+ @org.hibernate.annotations.CreationTimestamp+ protected Date createdOn;++ @NotBlank(message = "{Dashboard.realm.NotBlank}")+ @Size(min = 1, max = 255, message = "{Asset.realm.Size}")+ @Column(name = "REALM", nullable = false, updatable = false)+ protected String realm;++ @Version+ @Column(name = "VERSION", nullable = false)+ protected long version;++ @Column(name = "OWNER_ID", nullable = false)+ protected String ownerId;++ @Column(name = "VIEW_ACCESS", nullable = false)+ protected DashboardAccess viewAccess;++ @Column(name = "EDIT_ACCESS", nullable = false)+ protected DashboardAccess editAccess;++ @NotBlank(message = "{Dashboard.displayName.NotBlank}")+ @Column(name = "DISPLAY_NAME", nullable = false)+ protected String displayName;++ @NotNull(message = "{Dashboard.template.NotNull}")+ @Column(name = "TEMPLATE", columnDefinition = PERSISTENCE_JSON_VALUE_TYPE, nullable = false)+ @org.hibernate.annotations.Type(type = PERSISTENCE_JSON_VALUE_TYPE)+ @Valid+ protected DashboardTemplate template;+++ /* ----------------------------- */++ public void setId(String id) {+ this.id = id;+ }+ public void setCreatedOn(Date createdOn) {+ this.createdOn = createdOn;+ }+ public void setRealm(String realm) {+ this.realm = realm;+ }+ public void setVersion(long version) {+ this.version = version;+ }+ public void setOwnerId(String ownerId) {+ this.ownerId = ownerId;+ }+ public void setViewAccess(DashboardAccess access) { this.viewAccess = access; }+ public void setEditAccess(DashboardAccess access) { this.editAccess = access; }+ public void setDisplayName(String displayName) {+ this.displayName = displayName;+ }+ public void setTemplate(@Valid DashboardTemplate template) {+ this.template = 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/DashboardAccess.java b/model/src/main/java/org/openremote/model/dashboard/DashboardAccess.javanew file mode 100644index 000000000..9a2a3625c--- /dev/null+++ b/model/src/main/java/org/openremote/model/dashboard/DashboardAccess.java@@ -0,0 +1,5 @@+package org.openremote.model.dashboard;++public enum DashboardAccess {+ PUBLIC, SHARED, PRIVATE+}diff --git a/model/src/main/java/org/openremote/model/dashboard/DashboardGridItem.java b/model/src/main/java/org/openremote/model/dashboard/DashboardGridItem.javanew file mode 100644index 000000000..7572dfbcd--- /dev/null+++ b/model/src/main/java/org/openremote/model/dashboard/DashboardGridItem.java@@ -0,0 +1,25 @@+package org.openremote.model.dashboard;++import javax.validation.constraints.Min;++public class DashboardGridItem {++ // Fields+ protected String id;+ protected int x;+ protected int y;++ @Min(value = 1, message = "{Dashboard.gridItem.w.Min}")+ protected int w;++ @Min(value = 1, message = "{Dashboard.gridItem.h.Min}")+ protected int h;++ protected int minH;+ protected int minW;+ protected int minPixelH;+ protected int minPixelW;+ protected boolean noResize;+ protected boolean noMove;+ protected boolean locked;+}diff --git a/model/src/main/java/org/openremote/model/dashboard/DashboardResource.java b/model/src/main/java/org/openremote/model/dashboard/DashboardResource.javanew file mode 100644index 000000000..558d5395b--- /dev/null+++ b/model/src/main/java/org/openremote/model/dashboard/DashboardResource.java@@ -0,0 +1,47 @@+package org.openremote.model.dashboard;++import io.swagger.v3.oas.annotations.tags.Tag;+import org.openremote.model.Constants;+import org.openremote.model.http.RequestParams;++import javax.annotation.security.RolesAllowed;+import javax.validation.Valid;+import javax.ws.rs.*;++import java.util.List;++import static javax.ws.rs.core.MediaType.APPLICATION_JSON;++@Tag(name = "Dashboard")+@Path("dashboard")+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+ @Consumes(APPLICATION_JSON)+ @Produces(APPLICATION_JSON)+ @RolesAllowed({Constants.WRITE_INSIGHTS_ROLE})+ Dashboard create(@BeanParam RequestParams requestParams, @Valid Dashboard dashboard);++ @PUT+ @Consumes(APPLICATION_JSON)+ @Produces(APPLICATION_JSON)+ @RolesAllowed({Constants.WRITE_INSIGHTS_ROLE})+ void update(@BeanParam RequestParams requestParams, @Valid Dashboard dashboard);++ @DELETE+ @Produces(APPLICATION_JSON)+ @RolesAllowed({Constants.WRITE_INSIGHTS_ROLE})+ void delete(@BeanParam RequestParams requestParams, @QueryParam("dashboardId") List<String> fields);+}diff --git a/model/src/main/java/org/openremote/model/dashboard/DashboardScalingPreset.java b/model/src/main/java/org/openremote/model/dashboard/DashboardScalingPreset.javanew file mode 100644index 000000000..d46f7d4ed--- /dev/null+++ b/model/src/main/java/org/openremote/model/dashboard/DashboardScalingPreset.java@@ -0,0 +1,5 @@+package org.openremote.model.dashboard;++public enum DashboardScalingPreset {+ WRAP_TO_SINGLE_COLUMN, KEEP_LAYOUT, REDIRECT, BLOCK_DEVICE+}diff --git a/model/src/main/java/org/openremote/model/dashboard/DashboardScreenPreset.java b/model/src/main/java/org/openremote/model/dashboard/DashboardScreenPreset.javanew file mode 100644index 000000000..af656e706--- /dev/null+++ b/model/src/main/java/org/openremote/model/dashboard/DashboardScreenPreset.java@@ -0,0 +1,46 @@+package org.openremote.model.dashboard;++import javax.validation.constraints.Min;+import javax.validation.constraints.NotBlank;+import javax.validation.constraints.NotEmpty;+import javax.validation.constraints.NotNull;+import javax.ws.rs.WebApplicationException;++import static javax.ws.rs.core.Response.Status.BAD_REQUEST;++public class DashboardScreenPreset {++ // Fields+ protected String id;++ @NotBlank(message = "{Dashboard.screenPreset.displayName.NotBlank}")+ protected String displayName;++ @Min(value = 1, message = "{Dashboard.screenPreset.breakpoint.Min}")+ protected int breakpoint;++ @NotNull(message = "{Dashboard.screenPreset.scalingPreset.NotNull}")+ protected DashboardScalingPreset scalingPreset;++ protected String redirectDashboardId; // nullable+++ /* -------------------------------- */++ 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; }+ public void setScalingPreset(@NotNull DashboardScalingPreset scalingPreset) { this.scalingPreset = scalingPreset; }+ public void setRedirectDashboardId(String redirectDashboardId) {+ if((redirectDashboardId == null || redirectDashboardId.isEmpty()) && this.scalingPreset == DashboardScalingPreset.REDIRECT) {+ throw new WebApplicationException(BAD_REQUEST);+ }+ this.redirectDashboardId = redirectDashboardId;+ }++ public String getId() { return id; }+ public String getDisplayName() { return displayName; }+ public int getBreakpoint() { return breakpoint; }+ public DashboardScalingPreset getScalingPreset() { return scalingPreset; }+ public String getRedirectDashboardId() { return redirectDashboardId; }+}diff --git a/model/src/main/java/org/openremote/model/dashboard/DashboardTemplate.java b/model/src/main/java/org/openremote/model/dashboard/DashboardTemplate.javanew file mode 100644index 000000000..6e7eed58d--- /dev/null+++ b/model/src/main/java/org/openremote/model/dashboard/DashboardTemplate.java@@ -0,0 +1,40 @@+package org.openremote.model.dashboard;++import javax.validation.Valid;+import javax.validation.constraints.Min;+import javax.validation.constraints.NotNull;++public class DashboardTemplate {++ // Fields+ protected String id;++ @Min(value = 1, message = "${Dashboard.template.columns.Min}")+ protected int columns;++ @Min(value = 1, message = "${Dashboard.template.maxScreenWidth.Min}")+ protected int maxScreenWidth;++ @NotNull(message = "{Dashboard.template.screenPresets.NotNull}")+ @Valid+ protected DashboardScreenPreset[] screenPresets;++ @Valid+ protected DashboardWidget[] widgets;++++ /* -------------------- */++ public void setId(String id) { this.id = id; }+ public void setColumns(int columns) { this.columns = columns; }+ public void setMaxScreenWidth(int maxScreenWidth) { this.maxScreenWidth = maxScreenWidth; }+ public void setScreenPresets(DashboardScreenPreset[] screenPresets) { this.screenPresets = screenPresets; }+ public void setWidgets(DashboardWidget[] widgets) { this.widgets = widgets; }++ public String getId() { return id; }+ public int getColumns() { return columns; }+ public int getMaxScreenWidth() { return maxScreenWidth; }+ public DashboardScreenPreset[] getScreenPresets() { return screenPresets; }+ public DashboardWidget[] getWidgets() { return widgets; }+}diff --git a/model/src/main/java/org/openremote/model/dashboard/DashboardWidget.java b/model/src/main/java/org/openremote/model/dashboard/DashboardWidget.javanew file mode 100644index 000000000..e472de129--- /dev/null+++ b/model/src/main/java/org/openremote/model/dashboard/DashboardWidget.java@@ -0,0 +1,39 @@+package org.openremote.model.dashboard;++import javax.validation.Valid;+import javax.validation.constraints.NotBlank;+import javax.validation.constraints.NotEmpty;+import javax.validation.constraints.NotNull;++public class DashboardWidget {++ // Fields+ protected String id;++ @NotBlank(message = "{Dashboard.widget.displayName.NotBlank}")+ protected String displayName;++ @NotNull(message = "{Dashboard.widget.gridItem.NotNull}")+ @Valid+ protected DashboardGridItem gridItem;++ @NotNull(message = "{Dashboard.widget.widgetTypeId.NotNull}")+ protected String widgetTypeId;++ protected Object widgetConfig;+++ /* ------------------------------ */++ public void setId(@NotNull @NotEmpty String id) { this.id = id; }+ public void setDisplayName(@NotNull @NotEmpty String displayName) { this.displayName = displayName; }+ public void setGridItem(@NotNull DashboardGridItem gridItem) { this.gridItem = gridItem; }+ public void setWidgetTypeId(@NotNull String widgetTypeId) { this.widgetTypeId = widgetTypeId; }+ public void setWidgetConfig(Object widgetConfig) { this.widgetConfig = widgetConfig; }++ public String getId() { return id; }+ public String getDisplayName() { return displayName; }+ public DashboardGridItem getGridItem() { return gridItem; }+ public String getWidgetTypeId() { return widgetTypeId; }+ public Object getWidgetConfig() { return widgetConfig; }+}diff --git a/model/src/main/java/org/openremote/model/security/ClientRole.java b/model/src/main/java/org/openremote/model/security/ClientRole.javaindex 42a4ffd9c..395b7734f 100644--- a/model/src/main/java/org/openremote/model/security/ClientRole.java+++ b/model/src/main/java/org/openremote/model/security/ClientRole.java@@ -39,6 +39,7 @@ public enum ClientRole {READ_MAP(Constants.READ_MAP_ROLE, "View map"),READ_ASSETS(Constants.READ_ASSETS_ROLE, "Read asset data"),READ_RULES(Constants.READ_RULES_ROLE, "Read rulesets"),+ READ_INSIGHTS(Constants.READ_INSIGHTS_ROLE, "Read dashboards"),WRITE_USER(Constants.WRITE_USER_ROLE, "Write data of the authenticated user"),WRITE_ADMIN(Constants.WRITE_ADMIN_ROLE, "Write system settings, realms, and users"),@@ -46,6 +47,7 @@ public enum ClientRole {WRITE_ASSETS(Constants.WRITE_ASSETS_ROLE, "Write asset data"),WRITE_ATTRIBUTES(Constants.WRITE_ATTRIBUTES_ROLE, "Write attribute data"),WRITE_RULES(Constants.WRITE_RULES_ROLE, "Write rulesets (NOTE: effectively super-user access!)"),+ WRITE_INSIGHTS(Constants.WRITE_INSIGHTS_ROLE, "Write dashboard data"),READ("read", "Read all data", new ClientRole[]{READ_ADMIN,@@ -53,7 +55,8 @@ public enum ClientRole {READ_USERS,READ_MAP,READ_ASSETS,- READ_RULES+ READ_RULES,+ READ_INSIGHTS}),WRITE("write", "Write all data", new ClientRole[]{@@ -63,12 +66,14 @@ public enum ClientRole {READ_MAP,READ_ASSETS,READ_RULES,+ READ_INSIGHTS,WRITE_USER,WRITE_ADMIN,WRITE_LOGS,WRITE_ASSETS,WRITE_ATTRIBUTES,- WRITE_RULES+ WRITE_RULES,+ WRITE_INSIGHTS});// Only individual roles, not compositesdiff --git a/model/src/main/resources/ValidationMessages.properties b/model/src/main/resources/ValidationMessages.propertiesindex 07a1ed79f..977d88faa 100644--- a/model/src/main/resources/ValidationMessages.properties+++ b/model/src/main/resources/ValidationMessages.properties@@ -33,6 +33,22 @@ Asset.attribute.Missing = Asset required attribute is missing.Asset.attribute.type.Mismatch = Asset attribute value type does not match the attribute descriptor.Asset.valueHolder.name.NotBlank = Asset attribute and meta item names can not be empty.+Dashboard.realm.NotBlank = Dashboard realm cannot be empty.+Dashboard.ownerId.NotBlank = Dashboard ownerId cannot be empty.+Dashboard.displayName.NotBlank = Dashboard displayName cannot be empty.+Dashboard.template.NotNull = Dashboard template cannot be null.+Dashboard.template.columns.Min = Template columns cannot empty nor set to 0.+Dashboard.template.maxScreenWidth.Min = Template maxScreenWidth cannot be empty nor set to 0.+Dashboard.template.screenPresets.Null = Template screenPresets cannot be null.+Dashboard.screenPreset.displayName.NotBlank = ScreenPreset displayName cannot be empty.+Dashboard.screenPreset.breakpoint.Min = ScreenPreset breakpoint cannot be empty nor set to 0.+Dashboard.screenPreset.scalingPreset.NotNull = ScreenPreset scalingPreset cannot be null.+Dashboard.widget.displayName.NotBlank = Widget displayName cannot be empty.+Dashboard.widget.gridItem.NotNull = Widget gridItem cannot be null.+Dashboard.widget.widgetTypeId.NotNull = Widget widgetTypeId cannot be null.+Dashboard.gridItem.w.Min = GridItem w (width) cannot be empty nor set to 0.+Dashboard.gridItem.h.Min = GridItem h (height) cannot be empty nor set to 0.+GatewayConnection.host.NotNull = Gateway connection host can not be empty.GatewayConnection.host.Size = Gateway connection host must be at least {min} and not more than {max} characters long.GatewayConnection.port.Range = Gateway connection port must be between {min} and {max}.diff --git a/test/src/test/groovy/org/openremote/test/dashboard/DashboardTest.groovy b/test/src/test/groovy/org/openremote/test/dashboard/DashboardTest.groovynew file mode 100644index 000000000..da5c6bdc8--- /dev/null+++ b/test/src/test/groovy/org/openremote/test/dashboard/DashboardTest.groovy@@ -0,0 +1,47 @@+package org.openremote.test.dashboard++import 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.test.setup.KeycloakTestSetup+import org.openremote.test.setup.ManagerTestSetup+import spock.lang.Ignore+import spock.lang.Specification++import static org.openremote.container.security.IdentityProvider.OR_ADMIN_PASSWORD+import static org.openremote.container.security.IdentityProvider.OR_ADMIN_PASSWORD_DEFAULT+import static org.openremote.container.util.MapAccess.getString+import static org.openremote.model.Constants.*++@Ignore+class DashboardTest extends Specification implements ManagerContainerTrait {++ def "Test invalid input Dashboard"() {+ 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(+ container,+ MASTER_REALM,+ KEYCLOAK_CLIENT_ID,+ MASTER_REALM_ADMIN_USER,+ getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)+ ).token++ and: "the dashboard resource"+ def serverUri = serverUri(serverPort)+ def dashboardResource = getClientApiTarget(serverUri, MASTER_REALM, accessToken).proxy(DashboardResource.class)++ when: "a dashboard is created in the authenticated realm"+ Dashboard testDashboard = new Dashboard();+ testDashboard = dashboardResource.create(null, testDashboard);++ then: "the dashboard should exist"+ testDashboard.displayName == "Test Room"+ testDashboard.template != null+ }+}diff --git a/ui/app/dashboard/.babelrc b/ui/app/dashboard/.babelrcnew file mode 100644index 000000000..1320b9a32--- /dev/null+++ b/ui/app/dashboard/.babelrc@@ -0,0 +1,3 @@+{+ "presets": ["@babel/preset-env"]+}diff --git a/ui/app/dashboard/.gitignore b/ui/app/dashboard/.gitignorenew file mode 100644index 000000000..860bc87e6--- /dev/null+++ b/ui/app/dashboard/.gitignore@@ -0,0 +1,5 @@+build/+node_modules/+src/**/*.d.ts+src/**/*.js+src/**/*.js.mapdiff --git a/ui/app/dashboard/babel.config.js b/ui/app/dashboard/babel.config.jsnew file mode 100644index 000000000..6ab6c73a6--- /dev/null+++ b/ui/app/dashboard/babel.config.js@@ -0,0 +1,38 @@+module.exports = api => {++ api.cache(false);+ return {+ presets: [+ [+ "@babel/preset-env",+ {+ modules: false,+ exclude: ['transform-async-to-generator'],+ targets: [+ "last 2 versions",+ "IE 11"+ ]+ }+ ]+ ],+ plugins: [+ [+ "@babel/transform-runtime",+ {+ "corejs": false,+ "helpers": true,+ "regenerator": true,+ "useESModules": false+ }+ ],+ "@babel/syntax-dynamic-import",+ "@babel/syntax-object-rest-spread",+ [+ 'module:fast-async',+ {+ spec: true+ }+ ]+ ]+ };+};diff --git a/ui/app/dashboard/build.gradle b/ui/app/dashboard/build.gradlenew file mode 100644index 000000000..9696ff827--- /dev/null+++ b/ui/app/dashboard/build.gradle@@ -0,0 +1,12 @@+buildDir = "dist"++task clean {+ dependsOn npmClean+}++task installDist(type: Copy) {+ dependsOn npmBuild+ mustRunAfter(resolveTask(":manager:installDist"))+ from project.buildDir+ into "${resolveProject(':manager').buildDir}/install/manager/web/${projectDir.name}"+}diff --git a/ui/app/dashboard/index.html b/ui/app/dashboard/index.htmlnew file mode 100644index 000000000..67304b598--- /dev/null+++ b/ui/app/dashboard/index.html@@ -0,0 +1,89 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <meta name="viewport" content="width=device-width, minimum-scale=1, initial-scale=1, user-scalable=yes, viewport-fit=cover">++ <title>OpenRemote Demo</title>+ <meta name="application-name" content="OpenRemote Demo">+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">+ <meta name="apple-mobile-web-app-title" content="OpenRemote Demo">++ <meta name="msapplication-TileImage" content="images/Icon-144.png">+ <meta name="msapplication-TileColor" content="#ffffff">+ <meta name="msapplication-tap-highlight" content="no">++ <link rel="icon" href="images/favicon.ico">+ <meta name="theme-color" content="#ffffff">++ <!-- Add to homescreen for Chrome on Android. Fallback for manifest.json -->+ <meta name="mobile-web-app-capable" content="yes">++ <!-- Add to homescreen for Safari on iOS -->+ <meta name="apple-mobile-web-app-capable" content="yes">++ <!-- Homescreen icons -->+ <link rel="apple-touch-icon" href="images/Icon-48.png">+ <link rel="apple-touch-icon" sizes="72x72" href="images/Icon-72.png">+ <link rel="apple-touch-icon" sizes="144x144" href="images/Icon-144.png">+ <link rel="apple-touch-icon" sizes="192x192" href="images/Icon-196.png">++ <!-- Tile icon for Windows 8 (144x144 + tile color) -->+ <meta name="msapplication-TileImage" content="images/Icon-144.png">+ <meta name="msapplication-TileColor" content="#ffffff">+ <meta name="msapplication-tap-highlight" content="no">++ <!-- Default twitter cards -->+ <meta name="twitter:card" content="summary">+ <meta name="twitter:site" content="@username">+ <meta property="og:type" content="website">+ <meta property="og:site_name" content="my-app">+ <meta property="og:image" content="images/Icon-144.png" />++ <!--+ Feature detect Custom Elements support. If the browser DOES support Custom+ Elements then we need to load the custom-elements-es5-adapter because+ our project code has been transpiled from ES2015 to ES5 and native Custom+ Elements expect elements will be registered as classes.+ -->+ <script>if (!window.customElements) { document.write('<!--'); }</script>+ <script src="./modules/@webcomponents/webcomponentsjs/custom-elements-es5-adapter.js"></script>+ <!--! DO NOT REMOVE THIS COMMENT, WE NEED ITS CLOSING MARKER -->++ <style>+ html {+ height: 100%;+ }+ body {+ margin: 0;+ font-family: "Segoe UI", Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol";+ line-height: 1.5;+ height: 100%;+ -webkit-font-smoothing: antialiased;+ overflow: hidden;+ }+ </style>+++</head>+<body>+<!--+Use the webcomponents-loader script which will feature detect which Web+Components features are missing and lazy load the appropriate polyfills.+When we hear the 'WebComponentsReady' event from the polyfill bundle we can+insert our 'bundle.js'.+-->+<script>+ (function () {+ document.addEventListener('WebComponentsReady', function componentsReady() {+ document.removeEventListener('WebComponentsReady', componentsReady, false);+ var script = document.createElement('script');+ script.src = '<%= htmlWebpackPlugin.files.js[0] %>';+ var refScript = document.getElementsByTagName('script')[0];+ refScript.parentNode.insertBefore(script, refScript);+ }, false);+ })();+</script>+<script src="modules/@webcomponents/webcomponentsjs/webcomponents-loader.js"></script>+</body>+</html>diff --git a/ui/app/dashboard/package.json b/ui/app/dashboard/package.jsonnew file mode 100644index 000000000..91ccd26db--- /dev/null+++ b/ui/app/dashboard/package.json@@ -0,0 +1,33 @@+{+ "name": "@openremote/dashboard",+ "version": "1.0.0",+ "description": "OpenRemote Dashboard Viewer",+ "author": "OpenRemote",+ "license": "AGPL-3.0-or-later",+ "private": true,+ "exports": {+ "./*": "./lib/*.js"+ },+ "typesVersions": {+ "*": {+ "*": [+ "lib/*"+ ]+ }+ },+ "scripts": {+ "clean": "npx tsc -b --clean && npx shx rm -rf dist",+ "modelBuild": "npx orutil build",+ "modelWatch": "npx orutil watch",+ "build": "npx cross-env NODE_OPTIONS=--max_old_space_size=4096 webpack --mode production",+ "serve": "npx tsc -b --clean && npx shx rm -rf dist && npx orutil build && npx cross-env NODE_OPTIONS=--max_old_space_size=4096 webpack serve --mode development --env port=9001",+ "serveNoModelBuild": "npx tsc -b --clean && npx cross-env NODE_OPTIONS=--max_old_space_size=4096 webpack serve --mode development --env port=9001",+ "test": "echo \"Error: no test specified\" && exit 1"+ },+ "dependencies": {+ "@openremote/or-app": "^1.1.0"+ },+ "devDependencies": {+ "@openremote/util": "workspace:*"+ }+}diff --git a/ui/app/dashboard/src/index.ts b/ui/app/dashboard/src/index.tsnew file mode 100644index 000000000..e956c756b--- /dev/null+++ b/ui/app/dashboard/src/index.ts@@ -0,0 +1,39 @@+import {combineReducers, configureStore} from "@reduxjs/toolkit";+import {+ OrApp,+ AppConfig,+ appReducer,+ getRealmQueryParameter,+ PageProvider} from "@openremote/or-app";+import {pageDashboardProvider} from "./pages/page-dashboard";++++const rootReducer = combineReducers({+ app: appReducer+});++type RootState = ReturnType<typeof rootReducer>;++export const store = configureStore({+ reducer: rootReducer+});++const orApp = new OrApp(store);++// Configure manager connection and i18next settings+orApp.managerConfig = {+ realm: getRealmQueryParameter(),+ autoLogin: false+};++export const DefaultPagesConfig: PageProvider<any>[] = [+ pageDashboardProvider(store)+];++// Configure app pages and per realm styling/settings+orApp.appConfig = {+ pages: [...DefaultPagesConfig],+};++document.body.appendChild(orApp);diff --git a/ui/app/dashboard/src/pages/page-dashboard.ts b/ui/app/dashboard/src/pages/page-dashboard.tsnew file mode 100644index 000000000..9215c2358--- /dev/null+++ b/ui/app/dashboard/src/pages/page-dashboard.ts@@ -0,0 +1,82 @@+import {css, html, PropertyValues, TemplateResult, unsafeCSS} from "lit";+import {customElement, query, state} from "lit/decorators.js";+import {AppStateKeyed, Page, PageProvider, router} from "@openremote/or-app";+import {EnhancedStore} from "@reduxjs/toolkit";+import "@openremote/or-dashboard-builder"+import { Dashboard, DashboardTemplate } from "@openremote/model";+import manager from "@openremote/core";+import "@openremote/or-chart";++export function pageDashboardProvider(store: EnhancedStore<AppStateKeyed>): PageProvider<AppStateKeyed> {+ return {+ name: "dashboard",+ routes: [+ "dashboard/:id"+ ],+ pageCreator: () => {+ const page = new PageDashboard(store);+ return page;+ }+ };+}++@customElement("page-dashboard")+export class PageDashboard extends Page<AppStateKeyed> {++ @state()+ private template: DashboardTemplate;++ @state()+ private dashboardId: string;++ @state()+ private isLoading: boolean = true;+++ get name(): string {+ return "dashboard"+ }++ static get styles() {+ // language=CSS+ return [css`+ .text {+ height: 100%;+ width: 100%;+ display: flex;+ justify-content: center;+ align-items: center;+ }+ `]+ }++ fetchDashboard(dashboardId: string) {+ manager.rest.api.DashboardResource.get(dashboardId).then((dashboard) => {+ this.template = (dashboard.data as Dashboard).template;+ this.isLoading = false;+ });+ }+++ stateChanged(state: AppStateKeyed): void {+ if(state.app.params && state.app.params.id) {+ this.dashboardId = state.app.params.id;+ this.fetchDashboard(state.app.params.id);+ }+ }++ protected render(): TemplateResult {+ return html`+ ${this.template != undefined ? html`+ <or-dashboard-preview .template="${this.template}" .realm="${manager.displayRealm}"+ .editMode="${false}" .readonly="${true}" .fullscreen="${true}"+ ></or-dashboard-preview>+ ` : (this.isLoading ? html`+ <span class="text">Loading..</span>+ ` : html`+ <span class="text">No dashboard found..</span>+ `)}+ `+ }++}diff --git a/ui/app/dashboard/tsconfig.json b/ui/app/dashboard/tsconfig.jsonnew file mode 100644index 000000000..893d4f4e5--- /dev/null+++ b/ui/app/dashboard/tsconfig.json@@ -0,0 +1,14 @@+{+ "extends": "../../tsconfig",+ "compilerOptions": {+ "outDir": "./lib",+ "rootDir": "src",+ "strict": false+ },+ "include": [+ "./src"+ ],+ "references": [+ { "path": "../../component/or-app" }+ ]+}diff --git a/ui/app/dashboard/webpack.config.js b/ui/app/dashboard/webpack.config.jsnew file mode 100644index 000000000..528f9ed14--- /dev/null+++ b/ui/app/dashboard/webpack.config.js@@ -0,0 +1,55 @@+const util = require("@openremote/util");+const CopyWebpackPlugin = require("copy-webpack-plugin");+const webpack = require("webpack");++module.exports = (env, argv) => {++ const customConfigDir = env.config;+ const managerUrl = env.managerUrl;+ const keycloakUrl = env.keycloakUrl;+ const port = env.port;+ const IS_DEV_SERVER = !!process.argv.find(arg => arg.includes("serve"));+++ const config = util.getAppConfig(argv.mode, IS_DEV_SERVER, __dirname, managerUrl, keycloakUrl, port);+++ if (IS_DEV_SERVER && customConfigDir) {+ console.log("CUSTOM_CONFIG_DIR: " + customConfigDir);+ // Try and include the static files in the specified config dir if we're in dev server mode+ config.plugins.push(new CopyWebpackPlugin({+ patterns: [+ {+ from: customConfigDir+ },+ ]+ }));+ }++ if (IS_DEV_SERVER && customConfigDir) {+ // Try and include the static files in the specified config dir if we're in dev server mode+ config.plugins.push(new CopyWebpackPlugin({+ patterns: [+ {+ from: customConfigDir+ }+ ]+ }));+ }++ if (IS_DEV_SERVER) {+ config.performance = {+ hints: false+ };+ }+++ // Add a custom base URL to resolve the config dir to the path of the dev server not root+ config.plugins.push(+ new webpack.DefinePlugin({+ CONFIG_URL_PREFIX: JSON.stringify(IS_DEV_SERVER && customConfigDir ? "/dashboard" : "")+ })+ );++ return config;+};diff --git a/ui/app/manager/src/pages/page-insights.ts b/ui/app/manager/src/pages/page-insights.tsindex 05d0c9d6c..504503104 100644--- a/ui/app/manager/src/pages/page-insights.ts+++ b/ui/app/manager/src/pages/page-insights.ts@@ -1,13 +1,17 @@import {css, html, TemplateResult} from "lit";-import {customElement, property, query} from "lit/decorators.js";+import {customElement, property, query, state } from "lit/decorators.js";import "@openremote/or-data-viewer";import {DataViewerConfig, OrDataViewer} from "@openremote/or-data-viewer";-import {Page, PageProvider} from "@openremote/or-app";+import {Page, PageProvider, router} from "@openremote/or-app";import {AppStateKeyed} from "@openremote/or-app";import {Store} from "@reduxjs/toolkit";import i18next from "i18next";import {createSelector} from "reselect";import { manager } from "@openremote/core";+import "@openremote/or-dashboard-builder";+import {ClientRole, Dashboard} from "@openremote/model";+import {getInsightsRoute} from "../routes";+import { showSnackbar } from "@openremote/or-mwc-components/or-mwc-snackbar";export interface PageInsightsConfig {dataViewer?: DataViewerConfig@@ -18,7 +22,8 @@ export function pageInsightsProvider(store: Store<AppStateKeyed>, config?: PageIname: "insights",routes: ["insights",- "insights/:id"+ "insights/:editMode",+ "insights/:editMode/:id"],pageCreator: () => {const page = new PageInsights(store);@@ -33,51 +38,15 @@ export class PageInsights extends Page<AppStateKeyed> {static get styles() {// language=CSS- return css`- .hideMobile {- display: none;- }-- #wrapper {- height: 100%;- width: 100%;- display: flex;- flex-direction: column;- overflow: auto;- }-- #title {- margin: 20px auto 0;- padding: 0;- font-size: 18px;- font-weight: bold;- width: 100%;- max-width: 1360px;- align-items: center;- display: flex;- }+ return css`- or-data-viewer {- width: 100%;- max-width: 1400px;- margin: 0 auto;- }-- #title > or-icon {- margin-right: 10px;- margin-left: 14px;- --or-icon-width: 20px;- --or-icon-height: 20px;+ :host {+ overflow: hidden;}- @media only screen and (min-width: 768px){- .hideMobile {- display: flex;- }-- #title {- padding: 0 20px;- }+ #builder {+ z-index: 0;+ background: transparent;}`;}@@ -85,12 +54,30 @@ export class PageInsights extends Page<AppStateKeyed> {@property()public config?: PageInsightsConfig;- @property()- protected _assetId;-@query("#data-viewer")protected _dataviewer!: OrDataViewer;+ @property()+ protected _editMode: boolean = true;++ @property()+ protected _fullscreen: boolean = true;++ @property()+ private _dashboardId: string;++ @state()+ private _userId?: string;+++ /* ------------------ */++ updated(changedProperties: Map<string, any>) {+ if(changedProperties.has("_dashboardId")) {+ this._updateRoute();+ }+ }+protected _realmSelector = (state: AppStateKeyed) => state.app.realm || manager.displayRealm;get name(): string {@@ -101,11 +88,19 @@ export class PageInsights extends Page<AppStateKeyed> {[this._realmSelector],async () => {if (this._dataviewer) this._dataviewer.refresh();+ this._updateRoute(true);+ this.requestUpdate();})constructor(store: Store<AppStateKeyed>) {super(store);+ manager.rest.api.UserResource.getCurrent().then((response: any) => {+ this._userId = response.data.id;+ }).catch((ex) => {+ console.error(ex);+ showSnackbar(undefined, i18next.t('errorOccurred'));+ })}public connectedCallback() {@@ -114,11 +109,13 @@ export class PageInsights extends Page<AppStateKeyed> {protected render(): TemplateResult | void {return html`- <div id="wrapper">- <div id="title">- <or-icon icon="chart-areaspline"></or-icon>${i18next.t("insights")}- </div>- <or-data-viewer id="data-viewer" .config="${this.config?.dataViewer}"></or-data-viewer>+ <div style="width: 100%;">+ <or-dashboard-builder id="builder" .editMode="${this._editMode}" .fullscreen="${this._fullscreen}" .selectedId="${this._dashboardId}"+ .realm="${manager.displayRealm}" .userId="${this._userId}" .readonly="${!manager.hasRole(ClientRole.WRITE_INSIGHTS)}"+ @selected="${(event: CustomEvent) => { this._dashboardId = (event.detail as Dashboard)?.id }}"+ @editToggle="${(event: CustomEvent) => { this._editMode = event.detail; this._fullscreen = true; this._updateRoute(true); }}"+ @fullscreenToggle="${(event: CustomEvent) => { this._fullscreen = event.detail; }}"+ ></or-dashboard-builder></div>`;}@@ -126,5 +123,14 @@ export class PageInsights extends Page<AppStateKeyed> {stateChanged(state: AppStateKeyed) {// State is only utilised for initial loadingthis.getRealmState(state); // Order is important here!+ this._editMode = (state.app.params && state.app.params.editMode) ? (state.app.params.editMode == "true") : false;+ this._dashboardId = (state.app.params && state.app.params.id) ? state.app.params.id : undefined;+ }++ protected _updateRoute(silent: boolean = true) {+ router.navigate(getInsightsRoute(this._editMode, this._dashboardId), {+ callHooks: !silent,+ callHandler: !silent+ });}}diff --git a/ui/app/manager/src/routes.ts b/ui/app/manager/src/routes.tsindex a3711ce14..d52dcc528 100644--- a/ui/app/manager/src/routes.ts+++ b/ui/app/manager/src/routes.ts@@ -16,3 +16,11 @@ export function getAssetsRoute(editMode?: boolean, assetId?: string) {return route;}++export function getInsightsRoute(editMode?: boolean, dashboardId?: string) {+ let route = "insights/" + (editMode ? "true" : "false");+ if(dashboardId) {+ route += "/" + dashboardId;+ }+ return route;+}diff --git a/ui/component/or-app/package.json b/ui/component/or-app/package.jsonindex cb26929b7..12e22228b 100644--- a/ui/component/or-app/package.json+++ b/ui/component/or-app/package.json@@ -25,6 +25,8 @@"@openremote/or-attribute-input": "^1.1.0","@openremote/or-attribute-picker": "^1.1.0","@openremote/or-chart": "^1.1.0",+ "@openremote/or-dashboard-builder": "^1.0.0",+ "@openremote/or-gauge": "^1.0.0","@openremote/or-map": "^1.1.0","@openremote/or-mwc-components": "^1.1.0","@openremote/or-rules": "^1.1.0",diff --git a/ui/component/or-app/tsconfig.json b/ui/component/or-app/tsconfig.jsonindex 4dbc53145..99e2258fe 100644--- a/ui/component/or-app/tsconfig.json+++ b/ui/component/or-app/tsconfig.json@@ -20,6 +20,8 @@{ "path": "../../component/or-data-viewer" },{ "path": "../../component/or-log-viewer" },{ "path": "../../component/or-chart" },- { "path": "../../component/or-rules" }+ { "path": "../../component/or-rules" },+ { "path": "../../component/or-dashboard-builder" },+ { "path": "../../component/or-gauge" }]}diff --git a/ui/component/or-attribute-card/src/index.ts b/ui/component/or-attribute-card/src/index.tsindex 3e5ce1ad1..70bb93e30 100644--- a/ui/component/or-attribute-card/src/index.ts+++ b/ui/component/or-attribute-card/src/index.ts@@ -26,6 +26,7 @@ import {OrAssetTreeSelectionEvent} from "@openremote/or-asset-tree";import {OrMwcDialog, showDialog} from "@openremote/or-mwc-components/or-mwc-dialog";import {OrAttributePicker, OrAttributePickerPickedEvent} from "@openremote/or-attribute-picker";import {getContentWithMenuTemplate} from "@openremote/or-mwc-components/or-mwc-menu";+import {debounce} from "lodash";export type ContextMenuOption = "editAttribute" | "editDelta" | "editCurrentValue" | "delete";@@ -45,6 +46,7 @@ const style = css`.panel {position: relative;+ height: 100%;}.panel.panel-empty {display: flex;@@ -60,7 +62,7 @@ const style = css`}.panel-content-wrapper {- height: 200px;+ height: 100%;display: flex;flex-direction: column;}@@ -68,7 +70,7 @@ const style = css`.panel-title {display: flex;align-items: center;- margin: -15px -15px 0 0; /* compensate for the click-space of the plusminus button */+ /*margin: -15px -15px 0 0;*/ /* compensate for the click-space of the plusminus button */font-weight: bolder;line-height: 1em;color: var(--internal-or-asset-viewer-title-text-color);@@ -113,6 +115,7 @@ const style = css`.main-number-icon {font-size: 24px;margin-right: 10px;+ display: flex;}.main-number-unit {@@ -145,7 +148,7 @@ const style = css`}.delta-wrapper {- flex: 0 0 75px;+ flex: 0 0 50px;text-align: right;/*position: absolute;*/@@ -160,7 +163,7 @@ const style = css`.period-selector {position: absolute;- right: -16px;+ right: -12px;bottom: 0;}@@ -203,6 +206,10 @@ export class OrAttributeCard extends LitElement {@property()private deltaFormat: "absolute" | "percentage" = "absolute";@property()+ public showControls: boolean = true;+ @property()+ public showTitle: boolean = true;+ @property()protected _loading: boolean = false;private error: boolean = false;@@ -215,6 +222,7 @@ export class OrAttributeCard extends LitElement {@query("#chart")private _chartElem!: HTMLCanvasElement;private _chart?: Chart<"line", ScatterDataPoint[]>;+ private resizeObserver?: ResizeObserver;static get styles() {return [@@ -242,7 +250,7 @@ export class OrAttributeCard extends LitElement {updated(changedProperties: PropertyValues) {- if (changedProperties.has("realm")) {+ if (changedProperties.has("realm") && changedProperties.get("realm") != undefined) {this.assets = [];this.loadSettings();}@@ -328,6 +336,13 @@ export class OrAttributeCard extends LitElement {}}+ shouldShowControls(): boolean { // Checking for string input as well since that was not working+ return (this.showControls && this.showControls.toString() == "true");+ }+ shouldShowTitle(): boolean {+ return (this.showTitle && this.showTitle.toString() == "true");+ }+protected render() {if (!this.assets || !this.assetAttributes || this.assetAttributes.length === 0) {@@ -335,7 +350,12 @@ export class OrAttributeCard extends LitElement {<div class="panel panel-empty"><div class="panel-content-wrapper"><div class="panel-content">- <or-mwc-input class="button" .type="${InputType.BUTTON}" label="${i18next.t("selectAttribute")}" icon="plus" @or-mwc-input-changed="${() => this._openDialog("editAttribute")}"></or-mwc-input>+ ${this.shouldShowControls() ? html`+ <or-mwc-input class="button" .type="${InputType.BUTTON}" label="${i18next.t("selectAttribute")}" icon="plus" @or-mwc-input-changed="${() => this._openDialog("editAttribute")}"></or-mwc-input>+ ` : html`+ <span>${i18next.t('noAttributesConnected')}</span>+ <or-mwc-input class="button" .type="${InputType.BUTTON}" icon="reload" @or-mwc-input-changed="${() => { this.requestUpdate(); }}"></or-mwc-input>+ `}</div></div></div>@@ -348,19 +368,31 @@ export class OrAttributeCard extends LitElement {<div class="panel-content-wrapper"><div class="panel-content"><span>${i18next.t("couldNotRetrieveAttribute")}</span>- <or-mwc-input class="button" .type="${InputType.BUTTON}" label="${i18next.t("selectAttribute")}" icon="plus" @or-mwc-input-changed="${() => this._openDialog("editAttribute")}"></or-mwc-input>+ ${this.shouldShowControls() ? html`+ <or-mwc-input class="button" .type="${InputType.BUTTON}" label="${i18next.t("selectAttribute")}" icon="plus" @or-mwc-input-changed="${() => this._openDialog("editAttribute")}"></or-mwc-input>+ ` : html`+ <or-mwc-input class="button" .type="${InputType.BUTTON}" icon="reload" @or-mwc-input-changed="${() => { this.requestUpdate(); }}"></or-mwc-input>+ `}</div></div></div>`;}+ this.updateComplete.then(() => {+ this.resizeObserver = new ResizeObserver(debounce((entries: ResizeObserverEntry[]) => {+ const elemSize = entries[0].devicePixelContentBoxSize[0].blockSize;+ this.setLabelSizeByWidth(elemSize);+ }, 200))+ this.resizeObserver.observe(this.shadowRoot!.querySelector(".graph-wrapper")!);+ })+return html`<div class="panel" id="attribute-card"><div class="panel-content-wrapper"><div class="panel-title">- <span class="panel-title-text">${this.assets[0].name + " - " + i18next.t(this.assetAttributes[0][1].name!)}</span>- ${getContentWithMenuTemplate(html`+ ${this.shouldShowTitle() ? html`<span class="panel-title-text">${this.assets[0].name + " - " + i18next.t(this.assetAttributes[0][1].name!)}</span>` : undefined}+ ${this.shouldShowControls() ? getContentWithMenuTemplate(html`<or-mwc-input icon="dots-vertical" type="button"></or-mwc-input>`,[@@ -382,7 +414,7 @@ export class OrAttributeCard extends LitElement {}],undefined,- (option) => this.handleMenuSelect(option as ContextMenuOption))}+ (option) => this.handleMenuSelect(option as ContextMenuOption)) : undefined}</div><div class="panel-content"><div class="mainvalue-wrapper">@@ -398,17 +430,21 @@ export class OrAttributeCard extends LitElement {<span class="delta">${this.delta ? this.deltaPlus + (this.delta.val !== undefined && this.delta.val !== null ? this.delta.val : "") + (this.delta.unit || "") : ""}</span></div>- <div class="period-selector-wrapper">- ${getContentWithMenuTemplate(- html`<or-mwc-input class="period-selector" .type="${InputType.BUTTON}" .label="${i18next.t(this.period ? this.period : "-")}"></or-mwc-input>`,- [{value: "hour", text: "hour"}, {value: "day", text: "day"}, {value: "week", text: "week"}, {value: "month", text: "month"}, {value: "year", text: "year"}]- .map((option) => {- option.text = i18next.t(option.value);- return option;- }),- this.period,- (value) => this._setPeriodOption(value))}- </div>+ ${this.shouldShowControls() ? html`+ <div class="period-selector-wrapper">+ ${getContentWithMenuTemplate(+ html`<or-mwc-input class="period-selector" .type="${InputType.BUTTON}" .label="${i18next.t(this.period ? this.period : "-")}"></or-mwc-input>`,+ [{value: "hour", text: "hour"}, {value: "day", text: "day"}, {value: "week", text: "week"}, {value: "month", text: "month"}, {value: "year", text: "year"}].map((option) => {+ option.text = i18next.t(option.value);+ return option;+ }),+ this.period,+ (value) => this._setPeriodOption(value)+ )}+ </div>+ ` : html`+ <or-mwc-input class="period-selector" .type="${InputType.BUTTON}" disabled .label="${i18next.t(this.period ? this.period : "-")}"></or-mwc-input>+ `}</div></div></div>@@ -524,12 +560,12 @@ export class OrAttributeCard extends LitElement {}}- protected async loadSettings() {+ protected async loadSettings(reset: boolean = false) {this.assetAttributes = [];- this.period = "day";- this.deltaFormat = "absolute";- this.mainValueDecimals = 0;+ if(!this.period || reset) { this.period = "day"; }+ if(!this.deltaFormat || reset) { this.deltaFormat = "absolute"; }+ if(!this.mainValueDecimals || reset) { this.mainValueDecimals = 0; }if (!this.realm) {this.realm = manager.getRealm();@@ -736,7 +772,7 @@ export class OrAttributeCard extends LitElement {const roundedVal = +value.toFixed(this.mainValueDecimals); // + operator prevents str returnconst attributeDescriptor = AssetModelUtil.getAttributeDescriptor(attr.name!, this.assets[0].type!);const units = Util.resolveUnits(Util.getAttributeUnits(attr, attributeDescriptor, this.assets[0].type));- this.setMainValueSize(roundedVal.toString());+ this.setLabelSizeByLength(roundedVal.toString());if (!units) { return {value: roundedVal, unit: "" }; }return {@@ -790,7 +826,7 @@ export class OrAttributeCard extends LitElement {}}- protected setMainValueSize(value: string) {+ protected setLabelSizeByLength(value: string) {if (value.length >= 20) { this.mainValueSize = "xs" }if (value.length < 20) { this.mainValueSize = "s" }if (value.length < 15) { this.mainValueSize = "m" }@@ -798,6 +834,13 @@ export class OrAttributeCard extends LitElement {if (value.length < 5) { this.mainValueSize = "xl" }}+ protected setLabelSizeByWidth(blockSize: number) {+ if(blockSize < 60) { this.mainValueSize = "s"; }+ else if(blockSize < 100) { this.mainValueSize = "m"; }+ else if(blockSize < 200) { this.mainValueSize = "l"; }+ else { this.mainValueSize = "xl"; }+ }+protected _setPeriodOption(value: any) {this.period = value;this.saveSettings();diff --git a/ui/component/or-chart/src/index.ts b/ui/component/or-chart/src/index.tsindex b586050af..0d2f71456 100644--- a/ui/component/or-chart/src/index.ts+++ b/ui/component/or-chart/src/index.ts@@ -38,6 +38,8 @@ import "chartjs-adapter-moment";import {GenericAxiosResponse } from "@openremote/rest";import {OrAttributePicker, OrAttributePickerPickedEvent} from "@openremote/or-attribute-picker";import { showDialog } from "@openremote/or-mwc-components/or-mwc-dialog";+import { cache } from "lit/directives/cache.js";+import { throttle } from "lodash";Chart.register(LineController, ScatterController, LineElement, PointElement, LinearScale, TimeScale, Title, Filler, Legend, Tooltip, ChartAnnotation);@@ -168,6 +170,7 @@ const style = css`display: flex;min-width: 0;flex-direction: row;+ height: 100%;}#msg {@@ -203,13 +206,15 @@ const style = css`}#attribute-list {- overflow: auto;+ /*overflow: auto;*/flex: 1 1 0;- min-height: 150px;- width: 100%;+ width: 95%;display: flex;flex-direction: column;}+ .attribute-list-dense {+ flex-wrap: wrap;+ }.attribute-list-item {cursor: pointer;@@ -219,6 +224,9 @@ const style = css`padding: 0;min-height: 50px;}+ .attribute-list-item-dense {+ min-height: 28px;+ }.button-clear {background: none;@@ -247,8 +255,8 @@ const style = css`}.attribute-list-item-bullet {- width: 14px;- height: 14px;+ width: 12px;+ height: 12px;border-radius: 7px;margin-right: 10px;}@@ -284,13 +292,13 @@ const style = css`#chart-container {flex: 1 1 0;position: relative;- overflow: auto;- min-height: 400px;- max-height: 550px;+ overflow: hidden;+ /*min-height: 400px;+ max-height: 550px;*/}-canvas {width: 100% !important;+ height: 100%; !important;}@media screen and (max-width: 1280px) {@@ -338,7 +346,10 @@ export class OrChart extends translate(i18next)(LitElement) {private activeAsset?: Asset;@property({type: Object})- public assetAttributes: [number, Attribute<any>][] = [];+ public assetAttributes: [number, Attribute<any>][] = [];++ @property()+ public dataProvider?: (startOfPeriod: number, endOfPeriod: number, timeUnits: TimeUnit, stepSize: number) => Promise<ChartDataset<"line", ScatterDataPoint[]>[]>@property({type: Array})public colors: string[] = ["#3869B1", "#DA7E30", "#3F9852", "#CC2428", "#6B4C9A", "#922427", "#958C3D", "#535055"];@@ -361,6 +372,18 @@ export class OrChart extends translate(i18next)(LitElement) {@property()public panelName?: string;+ @property()+ public attributeControls: boolean = true;++ @property()+ public timestampControls: boolean = true;++ @property()+ public showLegend: boolean = true;++ @property()+ public denseLegend: boolean = false;+@property()protected _loading: boolean = false;@@ -399,19 +422,21 @@ export class OrChart extends translate(i18next)(LitElement) {}firstUpdated() {- this.loadSettings();+ this.loadSettings(false);}updated(changedProperties: PropertyValues) {super.updated(changedProperties);if (changedProperties.has("realm")) {- this.assets = [];- this.loadSettings();+ if(changedProperties.get("realm") != undefined) { // Checking whether it was undefined previously, to prevent loading 2 times and resetting attribute properties.+ this.assets = [];+ this.loadSettings(true);+ }}const reloadData = changedProperties.has("period") || changedProperties.has("compareTimestamp")- || changedProperties.has("timestamp") || changedProperties.has("assetAttributes") || changedProperties.has("realm");+ || changedProperties.has("timestamp") || changedProperties.has("assetAttributes") || changedProperties.has("realm") || changedProperties.has("dataProvider");if (reloadData) {this._data = undefined;@@ -437,7 +462,7 @@ export class OrChart extends translate(i18next)(LitElement) {options: {responsive: true,maintainAspectRatio: false,- onResize:() => this.dispatchEvent(new OrChartEvent("resize")),+ onResize: throttle(() => { this.dispatchEvent(new OrChartEvent("resize")); this.applyChartResponsiveness(); }, 200),showLines: true,plugins: {legend: {@@ -489,6 +514,7 @@ export class OrChart extends translate(i18next)(LitElement) {second: 'HH:mm:ss',minute: "HH:mm",hour: "HH:mm",+ day: "MMM D",week: "w"},unit: this._timeUnits,@@ -496,7 +522,6 @@ export class OrChart extends translate(i18next)(LitElement) {},ticks: {autoSkip: true,- maxTicksLimit: 30,color: "#000",font: {family: "'Open Sans', Helvetica, Arial, Lucida, sans-serif",@@ -530,6 +555,25 @@ export class OrChart extends translate(i18next)(LitElement) {});}+ applyChartResponsiveness(): void {+ if(this.shadowRoot) {+ const container = this.shadowRoot.getElementById('container');+ if(container) {+ const bottomLegenda = (container.clientWidth < 600);+ container.style.flexDirection = bottomLegenda ? 'column' : 'row';+ const attributeList = this.shadowRoot.getElementById('attribute-list');+ if(attributeList) {+ attributeList.style.gap = bottomLegenda ? '0 12px' : '';+ attributeList.style.maxHeight = bottomLegenda ? '90px' : '';+ attributeList.style.flexDirection = bottomLegenda ? 'row' : 'column'+ }+ this.shadowRoot.querySelectorAll('.attribute-list-item').forEach((item: Element) => {+ (item as HTMLElement).style.minHeight = bottomLegenda ? '' : '44px';+ (item.children[1] as HTMLElement).style.flexDirection = bottomLegenda ? 'row' : 'column';+ });+ }+ }+ }render() {const disabled = this._loading;@@ -539,70 +583,78 @@ export class OrChart extends translate(i18next)(LitElement) {<div id="chart-container"><canvas id="chart"></canvas></div>-- <div id="controls">- <div class="interval-controls" style="margin-right: 6px;">- ${getContentWithMenuTemplate(- html`<or-mwc-input .type="${InputType.BUTTON}" .label="${i18next.t("timeframe")}: ${i18next.t(this.period ? this.period : "-")}"></or-mwc-input>`,- this._getPeriodOptions(),- this.period,- (value) => this.setPeriodOption(value))}-- ${!!this.compareTimestamp ? html `- <or-mwc-input style="margin-left:auto;" .type="${InputType.BUTTON}" .label="${i18next.t("period")}" @or-mwc-input-changed="${() => this.setPeriodCompare(false)}" icon="minus"></or-mwc-input>- ` : html`- <or-mwc-input style="margin-left:auto;" .type="${InputType.BUTTON}" .label="${i18next.t("period")}" @or-mwc-input-changed="${() => this.setPeriodCompare(true)}" icon="plus"></or-mwc-input>- `}- </div>-- <div class="period-controls">-- ${!!this.compareTimestamp ? html `- <span class="line-label solid"></span>- `: ``}- <or-mwc-input id="ending-date"- .checkAssetWrite="${false}"- .type="${endDateInputType}"- ?disabled="${disabled}"- .value="${this.timestamp}"- @or-mwc-input-changed="${(evt: OrInputChangedEvent) => this._updateTimestamp(moment(evt.detail.value as string).toDate())}"></or-mwc-input>- <or-icon class="button-icon" icon="chevron-left" @click="${() => this._updateTimestamp(this.timestamp!, false, undefined, 0)}"></or-icon>- <or-icon class="button-icon" icon="chevron-right" @click="${() =>this._updateTimestamp(this.timestamp!, true, undefined, 0)}"></or-icon>- </div>- ${!!this.compareTimestamp ? html `- <div class="period-controls">- <span class="line-label dashed"></span>- <or-mwc-input id="ending-date"- .checkAssetWrite="${false}"- .type="${endDateInputType}"- ?disabled="${disabled}"- .value="${this.compareTimestamp}"- @or-mwc-input-changed="${(evt: OrInputChangedEvent) => this._updateTimestamp(moment(evt.detail.value as string).toDate(), undefined, true)}"></or-mwc-input>- <or-icon class="button-icon" icon="chevron-left" @click="${() => this._updateTimestamp(this.compareTimestamp!, false, true, 0)}"></or-icon>- <or-icon class="button-icon" icon="chevron-right" @click="${() => this._updateTimestamp(this.compareTimestamp!, true, true, 0)}"></or-icon>- </div>- ` : html``}-- <div id="attribute-list">- ${this.assetAttributes && this.assetAttributes.map(([assetIndex, attr], index) => {- const colourIndex = index % this.colors.length;- const descriptors = AssetModelUtil.getAttributeAndValueDescriptors(this.assets[assetIndex]!.type, attr.name, attr);- const label = Util.getAttributeLabel(attr, descriptors[0], this.assets[assetIndex]!.type, true);- const bgColor = this.colors[colourIndex] || "";- return html`- <div class="attribute-list-item" @mouseover="${()=> this.addDatasetHighlight(this.assets[assetIndex]!.id, attr.name)}" @mouseout="${()=> this.removeDatasetHighlight(bgColor)}">- <span style="margin-right: 10px; --or-icon-width: 20px;">${getAssetDescriptorIconTemplate(AssetModelUtil.getAssetDescriptor(this.assets[assetIndex]!.type!), undefined, undefined, bgColor.split('#')[1])}</span>- <div class="attribute-list-item-label">- <span>${this.assets[assetIndex].name}</span>- <span style="font-size:14px; color:grey;">${label}</span>++ ${(this.timestampControls || this.attributeControls || this.showLegend) ? html`+ <div id="chart-controls" style="overflow: hidden auto;">+ ${this.timestampControls || this.attributeControls ? html`+ <div id="controls">+ ${this.timestampControls ? html`+ <div class="interval-controls" style="margin-right: 6px;">+ ${getContentWithMenuTemplate(+ html`<or-mwc-input .type="${InputType.BUTTON}" .label="${i18next.t("timeframe")}: ${i18next.t(this.period ? this.period : "-")}"></or-mwc-input>`,+ this._getPeriodOptions(),+ this.period,+ (value) => this.setPeriodOption(value)+ )}+ ${!!this.compareTimestamp ? html`+ <or-mwc-input style="margin-left:auto;" .type="${InputType.BUTTON}" .label="${i18next.t("period")}" @or-mwc-input-changed="${() => this.setPeriodCompare(false)}" icon="minus"></or-mwc-input>+ ` : html`+ <or-mwc-input style="margin-left:auto;" .type="${InputType.BUTTON}" .label="${i18next.t("period")}" @or-mwc-input-changed="${() => this.setPeriodCompare(true)}" icon="plus"></or-mwc-input>+ `}+ </div>++ <div class="period-controls">+ ${!!this.compareTimestamp ? html`+ <span class="line-label solid"></span>+ `: undefined}+ <or-mwc-input id="ending-date" .checkAssetWrite="${false}" .type="${endDateInputType}" ?disabled="${disabled}" .value="${this.timestamp}"+ @or-mwc-input-changed="${(evt: OrInputChangedEvent) => this._updateTimestamp(moment(evt.detail.value as string).toDate())}">+ </or-mwc-input>+ <or-icon class="button-icon" icon="chevron-left" @click="${() => this._updateTimestamp(this.timestamp!, false, undefined, 0)}"></or-icon>+ <or-icon class="button-icon" icon="chevron-right" @click="${() =>this._updateTimestamp(this.timestamp!, true, undefined, 0)}"></or-icon></div>- <button class="button-clear" @click="${() => this._deleteAttribute(index)}"><or-icon icon="close-circle"></or-icon></button>- </div>- `- })}+ ${!!this.compareTimestamp ? html `+ <div class="period-controls">+ <span class="line-label dashed"></span>+ <or-mwc-input id="ending-date" .checkAssetWrite="${false}" .type="${endDateInputType}" ?disabled="${disabled}" .value="${this.compareTimestamp}"+ @or-mwc-input-changed="${(evt: OrInputChangedEvent) => this._updateTimestamp(moment(evt.detail.value as string).toDate(), undefined, true)}">+ </or-mwc-input>+ <or-icon class="button-icon" icon="chevron-left" @click="${() => this._updateTimestamp(this.compareTimestamp!, false, true, 0)}"></or-icon>+ <or-icon class="button-icon" icon="chevron-right" @click="${() => this._updateTimestamp(this.compareTimestamp!, true, true, 0)}"></or-icon>+ </div>+ ` : undefined}+ ` : undefined}+ ${this.attributeControls ? html`+ <or-mwc-input class="button" .type="${InputType.BUTTON}" ?disabled="${disabled}" label="${i18next.t("selectAttributes")}" icon="plus" @or-mwc-input-changed="${() => this._openDialog()}"></or-mwc-input>+ ` : undefined}+ </div>+ ` : undefined}+ ${cache(this.showLegend ? html`+ <div id="attribute-list" class="${this.denseLegend ? 'attribute-list-dense' : undefined}" style="padding: ${this.denseLegend ? '6px' : '12px'};">+ ${this.assetAttributes == null || this.assetAttributes.length == 0 ? html`+ <div>+ <span>${i18next.t('noAttributesConnected')}</span>+ </div>+ ` : undefined}+ ${this.assetAttributes && this.assetAttributes.map(([assetIndex, attr], index) => {+ const colourIndex = index % this.colors.length;+ const descriptors = AssetModelUtil.getAttributeAndValueDescriptors(this.assets[assetIndex]!.type, attr.name, attr);+ const label = Util.getAttributeLabel(attr, descriptors[0], this.assets[assetIndex]!.type, true);+ const bgColor = this.colors[colourIndex] || "";+ return html`+ <div class="attribute-list-item ${this.denseLegend ? 'attribute-list-item-dense' : undefined}" @mouseover="${()=> this.addDatasetHighlight(this.assets[assetIndex]!.id, attr.name)}" @mouseout="${()=> this.removeDatasetHighlight(bgColor)}">+ <span style="margin-right: 10px; --or-icon-width: 20px;">${getAssetDescriptorIconTemplate(AssetModelUtil.getAssetDescriptor(this.assets[assetIndex]!.type!), undefined, undefined, bgColor.split('#')[1])}</span>+ <div class="attribute-list-item-label ${this.denseLegend ? 'attribute-list-item-label-dense' : undefined}">+ <span style="font-size:12px; ${this.denseLegend ? 'margin-right: 8px' : undefined}">${this.assets[assetIndex].name}</span>+ <span style="font-size:12px; color:grey;">${label}</span>+ </div>+ </div>+ `+ })}+ </div>+ ` : undefined)}</div>- <or-mwc-input class="button" .type="${InputType.BUTTON}" ?disabled="${disabled}" label="${i18next.t("selectAttributes")}" icon="plus" @or-mwc-input-changed="${() => this._openDialog()}"></or-mwc-input>- </div>+ ` : undefined}</div>`;}@@ -635,7 +687,7 @@ export class OrChart extends translate(i18next)(LitElement) {this.saveSettings();this.requestUpdate();}-+getInputType() {switch (this.period) {case "hour":@@ -678,12 +730,20 @@ export class OrChart extends translate(i18next)(LitElement) {}}- async loadSettings() {+ async loadSettings(reset: boolean) {- this.assetAttributes = [];- this.period = "day";- this.timestamp = moment().set('minute', 0).toDate();- this.compareTimestamp = undefined;+ if(this.assetAttributes == undefined || reset) {+ this.assetAttributes = [];+ }+ if(this.period == undefined || reset) {+ this.period = "day";+ }+ if(this.timestamp == undefined || reset) {+ this.timestamp = moment().set('minute', 0).toDate();+ }+ if(this.compareTimestamp == undefined || reset) {+ this.compareTimestamp = undefined;+ }if (!this.realm) {this.realm = manager.getRealm();@@ -765,7 +825,7 @@ export class OrChart extends translate(i18next)(LitElement) {return;}- const viewSelector = window.location.hash;+ const viewSelector = window.location.hash;const allConfigs: OrChartConfig[] = await manager.console.retrieveData("OrChartConfig") || [];let config: OrChartConfig | undefined = allConfigs.find(e => e.realm === this.realm);@@ -797,7 +857,7 @@ export class OrChart extends translate(i18next)(LitElement) {manager.console.storeData("OrChartConfig", [...allConfigs.filter(e => e.realm !== this.realm), config]);}-+_openDialog() {const dialog = showDialog(new OrAttributePicker().setShowOnlyDatapointAttrs(true)@@ -841,6 +901,7 @@ export class OrChart extends translate(i18next)(LitElement) {if (this._chart) {this._chart.destroy();this._chart = undefined;+ this.requestUpdate();}}@@ -942,8 +1003,7 @@ export class OrChart extends translate(i18next)(LitElement) {}protected async _loadData() {-- if (this._loading || this._data || !this.assetAttributes || !this.assets || this.assets.length === 0 || this.assetAttributes.length === 0 || !this.period || !this.timestamp) {+ if (this._loading || this._data || !this.assetAttributes || !this.assets || (this.assets.length === 0 && !this.dataProvider) || (this.assetAttributes.length === 0 && !this.dataProvider) || !this.period || !this.timestamp) {return;}@@ -984,44 +1044,54 @@ export class OrChart extends translate(i18next)(LitElement) {let predictedFromTimestamp = now < this._startOfPeriod ? this._startOfPeriod : now;const data: ChartDataset<"line", ScatterDataPoint[]>[] = [];- const promises = this.assetAttributes.map(async ([assetIndex, attribute], index) => {-- const asset = this.assets[assetIndex];- const descriptors = AssetModelUtil.getAttributeAndValueDescriptors(asset.type, attribute.name, attribute);- const label = Util.getAttributeLabel(attribute, descriptors[0], asset.type, false);- const unit = Util.resolveUnits(Util.getAttributeUnits(attribute, descriptors[0], asset.type));- const colourIndex = index % this.colors.length;- let dataset = await this._loadAttributeData(asset, attribute, this.colors[colourIndex], interval, this._startOfPeriod!, this._endOfPeriod!, false, asset.name + " " + label);- (dataset as any).assetId = asset.id;- (dataset as any).attrName = attribute.name;- (dataset as any).unit = unit;- data.push(dataset);-- dataset = await this._loadAttributeData(this.assets[assetIndex], attribute, this.colors[colourIndex], interval, predictedFromTimestamp, this._endOfPeriod!, true, asset.name + " " + label + " " + i18next.t("predicted"));- data.push(dataset);-- if (this.compareTimestamp) {- const startOfPeriod = moment(this.compareTimestamp).startOf(this.period!).startOf(lowerCaseInterval as moment.unitOfTime.StartOf).add(1, lowerCaseInterval as moment.unitOfTime.Base).toDate().getTime();- const endOfPeriod = moment(this.compareTimestamp).endOf(this.period!).startOf(lowerCaseInterval as moment.unitOfTime.StartOf).add(1, lowerCaseInterval as moment.unitOfTime.Base).toDate().getTime();- const offset = this._startOfPeriod! - startOfPeriod;-- dataset = await this._loadAttributeData(this.assets[assetIndex], attribute, this.colors[colourIndex], interval, startOfPeriod, endOfPeriod, false, asset.name + " " + label + " " + i18next.t("compare"));- dataset.data.forEach((dp) => dp.x += offset);- dataset.borderDash = [10, 10];- (dataset as any).isComparisonDataset = true;+ let promises;++ if(this.dataProvider) {+ await this.dataProvider(this._startOfPeriod, this._endOfPeriod, this._timeUnits, this._stepSize).then((dataset) => {+ dataset.forEach((set) => { data.push(set); });+ });+ } else {+ promises = this.assetAttributes.map(async ([assetIndex, attribute], index) => {++ const asset = this.assets[assetIndex];+ const descriptors = AssetModelUtil.getAttributeAndValueDescriptors(asset.type, attribute.name, attribute);+ const label = Util.getAttributeLabel(attribute, descriptors[0], asset.type, false);+ const unit = Util.resolveUnits(Util.getAttributeUnits(attribute, descriptors[0], asset.type));+ const colourIndex = index % this.colors.length;+ let dataset = await this._loadAttributeData(asset, attribute, this.colors[colourIndex], interval, this._startOfPeriod!, this._endOfPeriod!, false, asset.name + " " + label);+ (dataset as any).assetId = asset.id;+ (dataset as any).attrName = attribute.name;+ (dataset as any).unit = unit;data.push(dataset);- predictedFromTimestamp = now < startOfPeriod ? startOfPeriod : now;- dataset = await this._loadAttributeData(this.assets[assetIndex], attribute, this.colors[colourIndex], interval, startOfPeriod, endOfPeriod, true, asset.name + " " + label + " " + i18next.t("compare") + " " + i18next.t("predicted"));- dataset.data.forEach((dp) => dp.x += offset);- dataset.borderDash = [6, 8];- (dataset as any).isComparisonDataset = true;+ dataset = await this._loadAttributeData(this.assets[assetIndex], attribute, this.colors[colourIndex], interval, predictedFromTimestamp, this._endOfPeriod!, true, asset.name + " " + label + " " + i18next.t("predicted"));data.push(dataset);- }- });++ if (this.compareTimestamp) {+ const startOfPeriod = moment(this.compareTimestamp).startOf(this.period!).startOf(lowerCaseInterval as moment.unitOfTime.StartOf).add(1, lowerCaseInterval as moment.unitOfTime.Base).toDate().getTime();+ const endOfPeriod = moment(this.compareTimestamp).endOf(this.period!).startOf(lowerCaseInterval as moment.unitOfTime.StartOf).add(1, lowerCaseInterval as moment.unitOfTime.Base).toDate().getTime();+ const offset = this._startOfPeriod! - startOfPeriod;++ dataset = await this._loadAttributeData(this.assets[assetIndex], attribute, this.colors[colourIndex], interval, startOfPeriod, endOfPeriod, false, asset.name + " " + label + " " + i18next.t("compare"));+ dataset.data.forEach((dp) => dp.x += offset);+ dataset.borderDash = [10, 10];+ (dataset as any).isComparisonDataset = true;+ data.push(dataset);++ predictedFromTimestamp = now < startOfPeriod ? startOfPeriod : now;+ dataset = await this._loadAttributeData(this.assets[assetIndex], attribute, this.colors[colourIndex], interval, startOfPeriod, endOfPeriod, true, asset.name + " " + label + " " + i18next.t("compare") + " " + i18next.t("predicted"));+ dataset.data.forEach((dp) => dp.x += offset);+ dataset.borderDash = [6, 8];+ (dataset as any).isComparisonDataset = true;+ data.push(dataset);+ }+ });+ }this._loading = false;- await Promise.all(promises);+ if(promises) {+ await Promise.all(promises);+ }this._data = data;}@@ -1051,7 +1121,7 @@ export class OrChart extends translate(i18next)(LitElement) {return newMoment.format();}-+protected async _loadAttributeData(asset: Asset, attribute: Attribute<any>, color: string | undefined, interval: DatapointInterval, from: number, to: number, predicted: boolean, label: string | undefined): Promise<ChartDataset<"line", ScatterDataPoint[]>> {const dataset: ChartDataset<"line", ScatterDataPoint[]> = {@@ -1115,5 +1185,5 @@ export class OrChart extends translate(i18next)(LitElement) {this.saveSettings();}, timeout);}-+}diff --git a/ui/component/or-dashboard-builder/README.md b/ui/component/or-dashboard-builder/README.mdnew file mode 100644index 000000000..cce52a090--- /dev/null+++ b/ui/component/or-dashboard-builder/README.md@@ -0,0 +1 @@+Documentation coming soon.diff --git a/ui/component/or-dashboard-builder/build.gradle b/ui/component/or-dashboard-builder/build.gradlenew file mode 100644index 000000000..ca7ec13c1--- /dev/null+++ b/ui/component/or-dashboard-builder/build.gradle@@ -0,0 +1,15 @@+buildDir = "dist"++task clean() {+ doLast {+ delete "dist"+ }+}++task prepareUi() {+ dependsOn clean, npmPrepare+}++task publishUi() {+ dependsOn clean, npmPublish+}diff --git a/ui/component/or-dashboard-builder/package.json b/ui/component/or-dashboard-builder/package.jsonnew file mode 100644index 000000000..8a4403c6e--- /dev/null+++ b/ui/component/or-dashboard-builder/package.json@@ -0,0 +1,31 @@+{+ "name": "@openremote/or-dashboard-builder",+ "version": "1.0.0",+ "description": "OpenRemote Dashboard Builder",+ "main": "dist/umd/index.bundle.js",+ "module": "lib/index.js",+ "exports": {+ ".": "./lib/index.js",+ "./*": "./lib/*.js"+ },+ "types": "lib/index.d.ts",+ "scripts": {+ "test": "echo \"No tests\" && exit 0",+ "prepublishOnly": "npx webpack"+ },+ "author": "OpenRemote",+ "license": "AGPL-3.0-or-later",+ "dependencies": {+ "@openremote/core": "workspace:*",+ "@openremote/model": "workspace:*",+ "@openremote/rest": "workspace:*",+ "gridstack": "^6.0.2",+ "lit": "^2.0.2"+ },+ "devDependencies": {+ "@openremote/util": "workspace:*"+ },+ "publishConfig": {+ "access": "public"+ }+}diff --git a/ui/component/or-dashboard-builder/src/index.ts b/ui/component/or-dashboard-builder/src/index.tsnew file mode 100644index 000000000..ee812bb77--- /dev/null+++ b/ui/component/or-dashboard-builder/src/index.ts@@ -0,0 +1,680 @@+import {css, html, LitElement, unsafeCSS} from "lit";+import {customElement, property, state} from "lit/decorators.js";+import {when} from 'lit/directives/when.js';+import "./or-dashboard-tree";+import "./or-dashboard-browser";+import "./or-dashboard-preview";+import "./or-dashboard-widgetsettings";+import "./or-dashboard-boardsettings";+import {InputType, OrInputChangedEvent} from '@openremote/or-mwc-components/or-mwc-input';+import "@openremote/or-icon";+import {style} from "./style";+import {ORGridStackNode} from "./or-dashboard-preview";+import {+ ClientRole,+ Dashboard,+ DashboardAccess,+ DashboardGridItem,+ DashboardScalingPreset,+ DashboardScreenPreset,+ DashboardTemplate,+ DashboardWidget+} from "@openremote/model";+import manager, {DefaultColor3, DefaultColor5} from "@openremote/core";+import {ListItem} from "@openremote/or-mwc-components/or-mwc-list";+import {OrMwcTabItem} from "@openremote/or-mwc-components/or-mwc-tabs";+import "@openremote/or-mwc-components/or-mwc-tabs";+import {showSnackbar} from "@openremote/or-mwc-components/or-mwc-snackbar";+import {i18next} from "@openremote/or-translate";+import { showOkCancelDialog } from "@openremote/or-mwc-components/or-mwc-dialog";+import {DashboardKeyEmitter} from "./or-dashboard-keyhandler";+import {OrWidgetEntity} from "./widgets/or-base-widget";+import {OrChartWidget} from "./widgets/or-chart-widget";+import { OrKpiWidget } from "./widgets/or-kpi-widget";+import { OrGaugeWidget } from "./widgets/or-gauge-widget";++// language=CSS+const styling = css`++ @media only screen and (min-width: 641px){+ #tree {+ max-width: 300px !important;+ }+ }++ #tree {+ flex-shrink: 0;+ align-items: stretch;+ z-index: 1;+ box-shadow: rgb(0 0 0 / 21%) 0px 1px 3px 0px;+ }++ /* Header related styling */+ #header {+ display: table-row;+ height: 1px;+ background: white;+ }+ #header-wrapper {+ padding: 14px 30px;+ display: flex;+ flex-direction: row;+ align-items: center;+ border-bottom: 1px solid ${unsafeCSS(DefaultColor5)};+ }+ #header-title {+ font-size: 18px;+ }+ #header-title > or-icon {+ margin-right: 10px;+ }+ #header-actions {+ flex: 1 1 auto;+ text-align: right;+ }+ #header-actions-content {+ display: flex;+ flex-direction: row;+ align-items: center;+ float: right;+ }++ /* Header related styling */+ #fullscreen-header {+ display: table-row;+ height: 1px;+ }+ @media screen and (max-width: 700px) {+ #fullscreen-header-wrapper {+ padding: 11px !important;+ }+ }+ #fullscreen-header-wrapper {+ min-height: 36px;+ padding: 20px 30px 15px;+ display: flex;+ flex-direction: row;+ align-items: center;+ }+ #fullscreen-header-title {+ font-size: 18px;+ font-weight: bold;+ }+ #fullscreen-header-title > or-mwc-input {+ margin-right: 4px;+ --or-icon-fill: ${unsafeCSS(DefaultColor3)};+ }+ #fullscreen-header-actions {+ flex: 1 1 auto;+ text-align: right;+ }+ #fullscreen-header-actions-content {+ display: flex;+ flex-direction: row;+ align-items: center;+ float: right;+ }++ /* ----------------------------- */+ /* Editor/builder related styling */+ #builder {+ flex: 1 0 auto;+ height: 100%;+ }++ /* ----------------------------- */+ /* Sidebar related styling (drag and drop widgets / configuration) */+ #sidebar {+ vertical-align: top;+ position: relative;+ width: 300px;+ background: white;+ border-left: 1px solid ${unsafeCSS(DefaultColor5)};+ }+ #sidebar-widget-headeractions {+ flex: 0;+ display: flex;+ flex-direction: row;+ padding-right: 5px;+ }+ .settings-container {+ display: flex;+ flex-direction: column;+ height: 100%;+ }+ #browser {+ flex-grow: 1;+ align-items: stretch;+ z-index: 1;+ max-width: 300px;+ }++ #save-btn { margin-left: 15px; }+ #view-btn { margin-left: 18px; }++ .small-btn {+ height: 36px;+ margin-top: -12px;+ }++ .hidescroll {+ -ms-overflow-style: none; /* for Internet Explorer, Edge */+ scrollbar-width: none; /* for Firefox */+ }+ .hidescroll::-webkit-scrollbar {+ display: none; /* for Chrome, Safari, and Opera */+ }+`;++export interface DashboardBuilderConfig {+ // no configuration built yet+}+export const MAX_BREAKPOINT = 1000000;++// Enum to Menu String method+export function scalingPresetToString(scalingPreset: DashboardScalingPreset | undefined): string {+ return (scalingPreset != null ? i18next.t("dashboard.presets." + scalingPreset.toLowerCase()) : "undefined");+}+export function dashboardAccessToString(access: DashboardAccess): string {+ return i18next.t("dashboard.access." + access.toLowerCase());+}++export function sortScreenPresets(presets: DashboardScreenPreset[], largetosmall: boolean = false): DashboardScreenPreset[] {+ return presets.sort((a, b) => {+ if(a.breakpoint != null && b.breakpoint != null) {+ if(a.breakpoint > b.breakpoint) {+ return (largetosmall ? 1 : -1);+ }+ if(a.breakpoint < b.breakpoint) {+ return (largetosmall ? 1 : -1);+ }+ }+ return 0;+ });+}++export function getActivePreset(gridWidth: number, presets: DashboardScreenPreset[]): DashboardScreenPreset | undefined {+ let activePreset: DashboardScreenPreset | undefined;+ sortScreenPresets(presets, true).forEach((preset) => {+ if(preset.breakpoint != null && gridWidth <= preset.breakpoint) {+ activePreset = preset;+ }+ });+ return activePreset;+}+export const widgetTypes: Map<string, OrWidgetEntity> = new Map<string, OrWidgetEntity>();+++@customElement("or-dashboard-builder")+export class OrDashboardBuilder extends LitElement {++ // Importing Styles; the unsafe GridStack css, and all custom css+ static get styles() {+ return [styling, style]+ }++ @property()+ protected readonly config: DashboardBuilderConfig | undefined;++ @property() // Originally from URL+ protected readonly editMode: boolean = false;++ @property()+ protected readonly fullscreen: boolean = true;++ @property() // Originally from URL+ protected readonly selectedId: string | undefined;++ @property() // Originally just manager.displayRealm+ protected realm: string | undefined;++ @property() // REQUIRED userId+ protected userId: string | undefined;++ @property()+ protected readonly: boolean = true;+++ /* ------------------- */++ @state()+ protected dashboards: Dashboard[] | undefined;++ @state() // Separate local template object+ protected currentTemplate: DashboardTemplate | undefined;++ @state()+ protected selectedDashboard: Dashboard | undefined;++ @state()+ protected selectedWidgetId: string | undefined;++ @state() // Used to toggle the SAVE button depending on whether changes have been made.+ protected initialDashboardJSON: string | undefined;++ @state() // Used to toggle the SAVE button depending on whether changes have been made.+ protected initialTemplateJSON: string | undefined;++ @state()+ protected isInitializing: boolean;++ @state()+ protected isLoading: boolean;++ @state() // Whether changes have been made+ protected hasChanged: boolean;++ @state()+ protected rerenderPending: boolean;++ private readonly keyEmitter: DashboardKeyEmitter = new DashboardKeyEmitter();+++ /* ------------- */++ constructor() {+ super();+ this.isInitializing = true;+ this.isLoading = true;+ this.hasChanged = false;+ this.rerenderPending = false;++ this.registerWidgetType("linechart", new OrChartWidget());+ this.registerWidgetType("kpi", new OrKpiWidget());+ this.registerWidgetType("gauge", new OrGaugeWidget());++ this.updateComplete.then(async () => {+ await this.updateDashboards(this.realm!);+ });+ }++ connectedCallback() {+ super.connectedCallback();+ this.keyEmitter.addListener('delete', (_e: KeyboardEvent) => {+ if(this.selectedWidgetId) {+ const selectedWidget = this.selectedDashboard?.template?.widgets?.find(w => w.id == this.selectedWidgetId);+ if(selectedWidget) { showOkCancelDialog(i18next.t('areYouSure'), i18next.t('dashboard.deleteWidgetWarning'), i18next.t('delete')).then((ok: boolean) => { if(ok) { this.deleteWidget(selectedWidget); }}); }+ }+ });+ this.keyEmitter.addListener('deselect', (_e: KeyboardEvent) => { this.deselectWidget(); });+ this.keyEmitter.addListener('save', (_e: KeyboardEvent) => { this.saveDashboard(); });+ }+ disconnectedCallback() {+ super.disconnectedCallback();+ this.keyEmitter.removeAllListeners();+ }++ async updateDashboards(realm: string) {++ // Getting dashboards+ await manager.rest.api.DashboardResource.getAllRealmDashboards(realm).then((result) => {+ this.dashboards = result.data;+ }).catch((reason) => {+ showSnackbar(undefined, i18next.t('errorOccurred'));+ console.error(reason);+ });++ // Setting dashboard if selectedId is given by parent component+ if(this.selectedId != undefined) {+ this.selectedDashboard = Object.assign({}, this.dashboards?.find(x => { return x.id == this.selectedId; }));+ }+ }++ /* ------------- */++ // On every property update+ updated(changedProperties: Map<string, any>) {+ this.isLoading = (this.dashboards == undefined);+ this.isInitializing = (this.dashboards == undefined);+ if(this.realm == undefined) { this.realm = manager.displayRealm; }++ // On any update (except widget selection), check whether hasChanged should be updated.+ if(!(changedProperties.size == 1 && changedProperties.has('selectedWidget'))) {+ this.hasChanged = (JSON.stringify(this.selectedDashboard) != this.initialDashboardJSON || JSON.stringify(this.currentTemplate) != this.initialTemplateJSON);+ }++ // Support for realm switching+ if(changedProperties.has("realm") && changedProperties.get("realm") != undefined) {+ this.updateDashboards(this.realm);+ }++ // Any update on the dashboard+ if(changedProperties.has("selectedDashboard")) {+ this.deselectWidget();+ this.currentTemplate = this.selectedDashboard?.template;+ this.dispatchEvent(new CustomEvent("selected", { detail: this.selectedDashboard }))+ }++ // Update on the Grid and its widget+ if(changedProperties.has("currentTemplate")) {+ if(this.selectedDashboard != null) {+ this.selectedDashboard.template = this.currentTemplate;+ }+ }+ // When edit/view mode gets toggled+ if(changedProperties.has("editMode")) {+ this.deselectWidget();+ this.showDashboardTree = true;+ }+ }++ /* ----------------- */+++ createWidget(gridStackNode: ORGridStackNode): DashboardWidget {+ const randomId = (Math.random() + 1).toString(36).substring(2);+ let displayName = widgetTypes.get(gridStackNode.widgetTypeId)?.DISPLAY_NAME;+ if(displayName == undefined) { displayName = (i18next.t('dashboard.widget') + " #" + randomId); } // If no displayName, set random ID as name.+ const gridItem: DashboardGridItem = generateGridItem(gridStackNode, displayName);++ const widget = {+ id: randomId,+ displayName: displayName,+ gridItem: gridItem,+ widgetTypeId: gridStackNode.widgetTypeId,+ } as DashboardWidget;+ widget.widgetConfig = widgetTypes.get(gridStackNode.widgetTypeId)?.getDefaultConfig(widget);++ const tempTemplate = JSON.parse(JSON.stringify(this.currentTemplate)) as DashboardTemplate;+ if(tempTemplate.widgets == undefined) {+ tempTemplate.widgets = [];+ }+ tempTemplate.widgets?.push(widget);+ this.currentTemplate = tempTemplate;+ return widget;+ }++ deleteWidget(widget: DashboardWidget) {+ if(this.currentTemplate != null && this.currentTemplate.widgets != null) {+ const tempTemplate = this.currentTemplate;+ tempTemplate.widgets = tempTemplate.widgets?.filter((x: DashboardWidget) => { return x.id != widget.id; });+ this.currentTemplate = tempTemplate;+ }+ if(this.selectedWidgetId == widget.id) {+ this.deselectWidget();+ }+ }++ /* ------------------------------ */++ selectWidget(widget: DashboardWidget): void {+ const foundWidget = this.currentTemplate?.widgets?.find((x) => { return x.gridItem?.id == widget.gridItem?.id; });+ if(foundWidget != null) {+ this.selectedWidgetId = foundWidget.id;+ } else {+ console.error("The selected widget does not exist!");+ }+ }+ deselectWidget() {+ this.selectedWidgetId = undefined;+ }++ /* --------------------- */++ selectDashboard(dashboard: Dashboard | undefined) {+ if(this.dashboards != null) {+ if(this.selectedDashboard && this.initialDashboardJSON) {+ const indexOf = this.dashboards.indexOf(this.selectedDashboard);+ if(indexOf) {+ this.dashboards[indexOf] = JSON.parse(this.initialDashboardJSON) as Dashboard;+ }+ }+ this.selectedDashboard = (dashboard ? this.dashboards.find((x) => { return x.id == dashboard.id; }) : undefined);+ this.initialDashboardJSON = JSON.stringify(this.selectedDashboard);+ this.initialTemplateJSON = JSON.stringify(this.selectedDashboard?.template);+ }+ }++ changeDashboardName(value: string) {+ if(this.selectedDashboard != null) {+ const dashboard = this.selectedDashboard;+ dashboard.displayName = value;+ this.selectedDashboard = Object.assign({}, dashboard);+ }+ }++ shareUrl(method: string) {+ let url = window.location.href.replace("true", "false");+ if(method == 'copy') {+ navigator.clipboard.writeText(url);+ } else if(method == 'tab') {+ window.open(url, '_blank')?.focus()+ }+ }++ /* ----------------------------------- */++ saveDashboard() {+ if(this.selectedDashboard != null && !this._isReadonly() && this._hasEditAccess()) {+ this.isLoading = true;++ // Saving object into the database+ manager.rest.api.DashboardResource.update(this.selectedDashboard).then(() => {+ if(this.dashboards != null && this.selectedDashboard != null) {+ this.initialDashboardJSON = JSON.stringify(this.selectedDashboard);+ this.initialTemplateJSON = JSON.stringify(this.selectedDashboard.template);+ this.dashboards[this.dashboards?.indexOf(this.selectedDashboard)] = this.selectedDashboard;+ this.currentTemplate = Object.assign({}, this.selectedDashboard.template);+ showSnackbar(undefined, i18next.t('dashboard.saveSuccessful'));+ }+ }).catch((reason) => {+ console.error(reason);+ showSnackbar(undefined, i18next.t('errorOccurred'));+ }).finally(() => {+ this.isLoading = false;+ })+ } else {+ console.error("The selected dashboard could not be found..");+ showSnackbar(undefined, i18next.t('errorOccurred'));+ }+ }++ protected _isReadonly(): boolean {+ return this.readonly || !manager.hasRole(ClientRole.WRITE_INSIGHTS);+ }+ protected _hasEditAccess(): boolean {+ return this.userId != null && (this.selectedDashboard?.editAccess == DashboardAccess.PRIVATE ? this.selectedDashboard?.ownerId == this.userId : true)+ }+ protected _hasViewAccess(): boolean {+ return this.userId != null && (this.selectedDashboard?.viewAccess == DashboardAccess.PRIVATE ? this.selectedDashboard?.ownerId == this.userId : true)+ }++ /* ----------------- */++ @state()+ protected sidebarMenuIndex: number = 0;++ @state()+ protected showDashboardTree: boolean = true;++ private readonly menuItems: ListItem[] = [+ { icon: "content-copy", text: (i18next.t("copy") + " URL"), value: "copy" },+ { icon: "open-in-new", text: i18next.t("dashboard.openInNewTab"), value: "tab" },+ ];+ private readonly tabItems: OrMwcTabItem[] = [+ { name: i18next.t("dashboard.widgets") }, { name: i18next.t("settings") }+ ];++ // Rendering the page+ render(): any {+ if(window.matchMedia("(max-width: 600px)").matches && this.editMode) {+ this.dispatchEvent(new CustomEvent('editToggle', { detail: false }));+ this.showDashboardTree = true;+ }+ return (!this.isInitializing || (this.dashboards != null && this.dashboards.length == 0)) ? html`+ <div id="container">+ ${(this.showDashboardTree) ? html`+ <or-dashboard-tree id="tree" class="${this.selectedDashboard ? 'hideMobile' : undefined}"+ .realm="${this.realm}" .hasChanged="${this.hasChanged}" .selected="${this.selectedDashboard}" .dashboards="${this.dashboards}" .showControls="${true}" .userId="${this.userId}" .readonly="${this._isReadonly()}"+ @created="${(_event: CustomEvent) => { this.dispatchEvent(new CustomEvent('editToggle', { detail: true })); }}"+ @updated="${(event: CustomEvent) => { this.dashboards = event.detail; this.selectedDashboard = undefined; }}"+ @select="${(event: CustomEvent) => { this.selectDashboard(event.detail); }}"+ ></or-dashboard-tree>+ ` : undefined}+ <div id="container" class="${this.selectedDashboard == null ? 'hideMobile' : undefined}" style="display: table;">+ ${this.editMode ? html`+ <div id="header" class="hideMobile" style="display: ${this.selectedDashboard == null && 'none'}">+ <div id="header-wrapper">+ <div id="header-title">+ <or-icon icon="view-dashboard"></or-icon>+ ${this.selectedDashboard != null ? html`+ <or-mwc-input .type="${InputType.TEXT}" min="1" max="1023" comfortable required outlined .label="${i18next.t('name') + '*\xa0'}"+ ?readonly="${this._isReadonly()}" .value="${this.selectedDashboard.displayName}"+ .disabled="${this.isLoading}" style="width: 300px;"+ @or-mwc-input-changed="${(event: OrInputChangedEvent) => { this.changeDashboardName(event.detail.value); }}"+ ></or-mwc-input>+ ` : undefined}+ </div>+ <div id="header-actions">+ <div id="header-actions-content">+ <or-mwc-input id="refresh-btn" class="small-btn" .disabled="${this.isLoading || (this.selectedDashboard == null)}" type="${InputType.BUTTON}" icon="refresh"+ @or-mwc-input-changed="${() => { this.rerenderPending = true; }}">+ </or-mwc-input>+ <or-mwc-input id="responsive-btn" class="small-btn" .disabled="${this.isLoading || (this.selectedDashboard == null)}" type="${InputType.BUTTON}" icon="responsive"+ @or-mwc-input-changed="${() => { this.dispatchEvent(new CustomEvent('fullscreenToggle', { detail: !this.fullscreen })); }}">+ </or-mwc-input>+ <or-mwc-input id="save-btn" ?hidden="${this._isReadonly() || !this._hasEditAccess()}" .disabled="${this.isLoading || !this.hasChanged || (this.selectedDashboard == null)}" type="${InputType.BUTTON}" raised label="${i18next.t('save')}"+ @or-mwc-input-changed="${() => { this.saveDashboard(); }}">+ </or-mwc-input>+ <or-mwc-input id="view-btn" ?hidden="${this._isReadonly() || !this._hasViewAccess()}" type="${InputType.BUTTON}" outlined icon="eye" label="${i18next.t('viewAsset')}"+ @or-mwc-input-changed="${() => { this.dispatchEvent(new CustomEvent('editToggle', { detail: false })); }}">+ </or-mwc-input>+ </div>+ </div>+ </div>+ </div>+ ` : html`+ <div id="fullscreen-header">+ <div id="fullscreen-header-wrapper">+ <div id="fullscreen-header-title" style="display: flex; align-items: center;">+ <or-icon class="showMobile" style="margin-right: 10px;" icon="chevron-left" @click="${() => { this.selectedDashboard = undefined; }}"></or-icon>+ <or-icon class="hideMobile" style="margin-right: 10px;" icon="menu" @click="${() => { this.showDashboardTree = !this.showDashboardTree; }}"></or-icon>+ <span>${this.selectedDashboard?.displayName}</span>+ </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="view-btn" class="hideMobile" ?hidden="${this.selectedDashboard == null || this._isReadonly() || !this._hasEditAccess()}" type="${InputType.BUTTON}" outlined icon="pencil" label="${i18next.t('editAsset')}"+ @or-mwc-input-changed="${() => { this.dispatchEvent(new CustomEvent('editToggle', { detail: true })); }}"></or-mwc-input>+ </div>+ </div>+ </div>+ </div>+ `}+ <div id="content">+ <div id="container">+ ${(this.editMode && (this._isReadonly() || !this._hasEditAccess())) ? html`+ <div style="display: flex; justify-content: center; align-items: center; height: 100%;">+ <span>${!this._hasEditAccess() ? i18next.t('noDashboardWriteAccess') : i18next.t('errorOccurred')}.</span>+ </div>+ ` : undefined}+ <div id="builder" style="${(this.editMode && (this._isReadonly() || !this._hasEditAccess())) ? 'display: none' : undefined}">+ ${(this.selectedDashboard != null) ? html`+ <or-dashboard-preview class="editor" style="background: transparent;"+ .realm="${this.realm}" .template="${this.currentTemplate}" .rerenderPending="${this.rerenderPending}"+ .selectedWidget="${this.selectedDashboard?.template?.widgets?.find(w => w.id == this.selectedWidgetId)}" .editMode="${this.editMode}"+ .fullscreen="${this.fullscreen}" .readonly="${this._isReadonly()}"+ @selected="${(event: CustomEvent) => { this.selectWidget(event.detail); }}"+ @deselected="${() => { this.deselectWidget(); }}"+ @dropped="${(event: CustomEvent) => { this.createWidget(event.detail as ORGridStackNode)}}"+ @changed="${(event: CustomEvent) => { this.currentTemplate = event.detail.template; }}"+ @rerenderfinished="${(event: CustomEvent) => { this.rerenderPending = false; }}"+ ></or-dashboard-preview>+ ` : html`+ <div style="display: flex; justify-content: center; align-items: center; height: 100%;">+ <span>${i18next.t('noDashboardSelected')}</span>+ </div>+ `}+ </div>+ ${when((this.selectedDashboard != null && this.editMode && !this._isReadonly() && this._hasEditAccess()), () => {+ const selectedWidget = this.selectedDashboard?.template?.widgets?.find(w => w.id == this.selectedWidgetId);+ return html`+ <div id="sidebar" class="hideMobile">+ ${this.selectedWidgetId != null ? html`+ <div class="settings-container">+ <div id="menu-header">+ <div id="title-container">+ <span id="title" title="${selectedWidget?.displayName}">${selectedWidget?.displayName}</span>+ </div>+ <div id="sidebar-widget-headeractions">+ <or-mwc-input type="${InputType.BUTTON}" icon="delete" @or-mwc-input-changed="${() => {+ showOkCancelDialog(i18next.t('areYouSure'), i18next.t('dashboard.deleteWidgetWarning'), i18next.t('delete')).then((ok: boolean) => {+ if(ok) { this.deleteWidget(selectedWidget!); }+ })+ }}"></or-mwc-input>+ <or-mwc-input type="${InputType.BUTTON}" icon="close" @or-mwc-input-changed="${() => { this.deselectWidget(); }}"></or-mwc-input>+ </div>+ </div>+ <div id="content" class="hidescroll" style="flex: 1; overflow: hidden auto;">+ <div style="position: relative;">+ <or-dashboard-widgetsettings style="position: absolute;" .selectedWidget="${selectedWidget}" .realm="${this.realm}"+ @delete="${(event: CustomEvent) => { this.deleteWidget(event.detail); }}"+ @update="${(event: CustomEvent) => {+ this.currentTemplate = Object.assign({}, this.selectedDashboard?.template);+ if(event.detail.force) { this.rerenderPending = true; }}}"+ ></or-dashboard-widgetsettings>+ </div>+ </div>+ </div>+ ` : undefined}+ <div class="settings-container" style="${this.selectedWidgetId != null ? css`display: none` : null}">+ <div style="border-bottom: 1px solid ${unsafeCSS(DefaultColor5)};">+ <or-mwc-tabs .items="${this.tabItems}" noScroll @activated="${(event: CustomEvent) => { this.sidebarMenuIndex = event.detail.index; }}" style="pointer-events: ${this.selectedDashboard ? undefined : 'none'}"></or-mwc-tabs>+ </div>+ <div id="content" class="hidescroll" style="flex: 1; overflow: hidden auto;">+ <div style="position: relative;">+ <or-dashboard-browser id="browser" style="position: absolute; ${this.sidebarMenuIndex != 0 ? css`display: none` : null}"></or-dashboard-browser>+ <or-dashboard-boardsettings style="position: absolute; ${this.sidebarMenuIndex != 1 ? css`display: none` : null}"+ .dashboard="${this.selectedDashboard}" .showPerms="${this.selectedDashboard?.ownerId == this.userId}"+ @update="${(event: CustomEvent) => {+ this.currentTemplate = Object.assign({}, this.selectedDashboard?.template);+ if(event.detail.force) { this.rerenderPending = true; }}}"+ ></or-dashboard-boardsettings>+ </div>+ </div>+ </div>+ </div>+ `+ })}+ </div>+ </div>+ </div>+ </div>+ ` : html`+ <div id="container" style="justify-content: center; align-items: center;">+ ${this.isInitializing ? html`+ <span>${i18next.t("loading")}.</span>+ ` : html`+ <span>${i18next.t("errorOccurred")}.</span>+ `}+ </div>+ `+ }++ registerWidgetType(name: string, widget: OrWidgetEntity) {+ widgetTypes.set(name, widget);+ }++ /* ======================== */++}++// Generating the Grid Item details like X and Y coordinates for GridStack to work.+export function generateGridItem(gridstackNode: ORGridStackNode, _displayName: string): DashboardGridItem {+ const randomId = (Math.random() + 1).toString(36).substring(2);+ const widgetType = widgetTypes.get(gridstackNode.widgetTypeId)!;+ return {+ id: randomId,+ x: gridstackNode.x,+ y: gridstackNode.y,+ w: 2,+ h: 2,+ minW: widgetType.MIN_COLUMN_WIDTH,+ minH: widgetType.MIN_COLUMN_WIDTH,+ minPixelW: widgetType.MIN_PIXEL_WIDTH,+ minPixelH: widgetType.MIN_PIXEL_HEIGHT,+ noResize: false,+ noMove: false,+ locked: false,+ }+}diff --git a/ui/component/or-dashboard-builder/src/or-dashboard-boardsettings.ts b/ui/component/or-dashboard-builder/src/or-dashboard-boardsettings.tsnew file mode 100644index 000000000..0e7e1db32--- /dev/null+++ b/ui/component/or-dashboard-builder/src/or-dashboard-boardsettings.ts@@ -0,0 +1,274 @@+import {Dashboard, DashboardAccess, DashboardScreenPreset, DashboardScalingPreset } from "@openremote/model";+import {css, html, LitElement, TemplateResult } from "lit";+import { customElement, property, state } from "lit/decorators.js";+import { InputType, OrInputChangedEvent } from "@openremote/or-mwc-components/or-mwc-input";+import {style} from './style';+import { i18next } from "@openremote/or-translate";+import {unsafeHTML} from 'lit/directives/unsafe-html.js';+import {+ dashboardAccessToString,+ scalingPresetToString,+ sortScreenPresets+} from ".";++//language=css+const boardSettingsStyling = css`+ .label {+ margin-bottom: 4px;+ }+`++@customElement("or-dashboard-boardsettings")+export class OrDashboardBoardsettings extends LitElement {++ @property()+ protected readonly dashboard!: Dashboard;++ @property()+ protected readonly showPerms?: boolean;++ @state()+ protected expandedPanels: string[] = [i18next.t('permissions'), i18next.t('layout'), i18next.t('display'), "Breakpoints"];++ constructor() {+ super();+ this.updateComplete.then(() => {+ if(this.shadowRoot != null) {+ this.shadowRoot.querySelectorAll(".displayInput").forEach(element => {+ (element.shadowRoot?.querySelector(".mdc-menu") as HTMLElement).style.minWidth = "250px"; // small fix for dropdown menu's to be the correct width+ })+ this.shadowRoot.querySelectorAll(".permissionInput").forEach(element => {+ (element.shadowRoot?.querySelector(".mdc-menu") as HTMLElement).style.minWidth = "250px"; // small fix for dropdown menu's to be the correct width+ })+ }+ })+ }+ /* ------------------------- */++ static get styles() {+ return [boardSettingsStyling, style]+ }++ forceParentUpdate(force: boolean = false) {+ this.dispatchEvent(new CustomEvent('update', { detail: { force: force }}));+ }++ /* ------------------------- */++ // Method when a user opens or closes an expansion panel. (UI related)+ expandPanel(panelName: string): void {+ if(this.expandedPanels.includes(panelName)) {+ const indexOf = this.expandedPanels.indexOf(panelName, 0);+ if(indexOf > -1) { this.expandedPanels.splice(indexOf, 1); }+ } else {+ this.expandedPanels.push(panelName);+ }+ this.requestUpdate();+ }++ /* -------------------------------- */++ 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.requestUpdate();+ this.forceParentUpdate(false);+ }+ private setEditAccess(access: DashboardAccess) {+ this.dashboard.editAccess = access;+ this.requestUpdate();+ this.forceParentUpdate(false);+ }+ private setBreakpoint(presetIndex: number, value: number) {+ this.dashboard.template!.screenPresets![presetIndex].breakpoint = value;+ this.requestUpdate();+ this.forceParentUpdate(true);+ }++ 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 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) });+ });+ return html`+ <!-------------------->+ <div>${this.showPerms ? this.generateExpandableHeader(i18next.t('permissions')) : undefined}</div>+ <div>+ ${this.showPerms && this.expandedPanels.includes(i18next.t('permissions')) ? html`+ <div style="padding: 12px 24px 24px 24px;">+ <div style="margin-bottom: 24px;">+ <div class="label">+ ${html`<span>${unsafeHTML(i18next.t('dashboard.whoCanView').toString())}</span>`}+ </div>+ <or-mwc-input class="permissionInput" comfortable type="${InputType.SELECT}" style="width: 250px;"+ .options="${accessOptions.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>+ </div>+ <div style="margin-bottom: 24px;">+ <div class="label">+ ${html`<span>${unsafeHTML(i18next.t('dashboard.whoCanEdit').toString())}</span>`}+ </div>+ <or-mwc-input class="permissionInput" comfortable type="${InputType.SELECT}" style="width: 250px;"+ .disabled="${(this.dashboard.viewAccess == DashboardAccess.PRIVATE)}"+ .options="${accessOptions.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>+ </div>+ </div>+ ` : null}+ </div>+ <!-------------------->+ <div>${this.generateExpandableHeader(i18next.t('layout'))}</div>+ <div>+ ${this.expandedPanels.includes(i18next.t('layout')) ? html`+ <div style="padding: 12px 24px 24px 24px;">+ <!-- Number of Columns control -->+ <div style="margin-bottom: 24px; display: flex; align-items: center;">+ <span style="min-width: 180px;">${i18next.t("dashboard.numberOfColumns")}</span>+ <or-mwc-input type="${InputType.NUMBER}" comfortable .value="${this.dashboard.template.columns}" min="1" max="24" @or-mwc-input-changed="${(event: OrInputChangedEvent) => {+ if(this.dashboard.template != null && event.detail.value as number <= 24 && event.detail.value as number >= 1) {+ this.dashboard.template.columns = event.detail.value as number; this.forceParentUpdate(true);+ }+ }}"></or-mwc-input>+ </div>+ ${screenPresets.length == 1 ? html`+ ${this.scalingPresetTemplate(screenPresets, scalingPresets)}+ ` : undefined}+ ${screenPresets.length == 1 ? html`+ ${this.screenPresetTemplate(screenPresets, ['Mobile breakpoint'])}+ ` : undefined}+ <!-- Max Screen Width control-->+ <div style="margin-bottom: 24px; display: flex; align-items: center; justify-content: space-between;">+ <span style="min-width: 150px;">${i18next.t('dashboard.maxScreenWidth')}</span>+ <div>+ <or-mwc-input type="${InputType.NUMBER}" comfortable .value="${this.dashboard.template.maxScreenWidth}" style="width: 70px;"+ @or-mwc-input-changed="${(event: OrInputChangedEvent) => { if(this.dashboard.template != null) {+ this.dashboard.template.maxScreenWidth = event.detail.value as number; this.forceParentUpdate(true);+ }}}">+ </or-mwc-input>+ <span style="margin-left: 2px;">px</span>+ </div>+ </div>+ <div>+ <or-mwc-input type="${InputType.BUTTON}" comfortable label="${i18next.t('dashboard.setToMobilePreset')}"+ @or-mwc-input-changed="${() => { this.setToMobilePreset(); }}">+ </or-mwc-input>+ </div>+ </div>+ ` : null}+ </div>+ <!-------------------->+ ${screenPresets.length > 1 ? html`+ <div>${this.generateExpandableHeader(i18next.t('display'))}</div>+ <div>+ ${this.expandedPanels.includes(i18next.t('display')) ? html`+ <div style="padding: 24px 24px 24px 24px;">+ ${this.scalingPresetTemplate(screenPresets, scalingPresets)}+ </div>+ ` : null}+ </div>+ ` : undefined}+ <!-------------------->+ ${screenPresets.length > 1 ? html`+ <div>${this.generateExpandableHeader('Breakpoints')}</div>+ <div>+ ${this.expandedPanels.includes('Breakpoints') ? html`+ <div style="padding: 24px 24px 24px 24px;">+ ${this.screenPresetTemplate(screenPresets)}+ </div>+ ` : null}+ </div>+ ` : undefined}+ <!-------------------->+ `+ } else {+ return html`+ <div style="padding: 24px;">+ <span>${i18next.t('errorOccured')}</span><br/>+ <span>${i18next.t('noDashboardFound')}</span>+ </div>+ `+ }+ }++ // Button to switch to a mobile preset of layout settings.+ // TODO: Make these values not hardcoded anymore, and depend on the getDefault functions in or-dashboard-tree (that probably should move to somewhere else)+ setToMobilePreset() {+ this.dashboard.template!.columns = 4;+ this.dashboard.template!.screenPresets![0].scalingPreset = DashboardScalingPreset.KEEP_LAYOUT;+ this.dashboard.template!.maxScreenWidth = 700;+ this.requestUpdate();+ this.forceParentUpdate(true);+ }+++ /* ======================== */++ // UI generation of an expandable panel header.+ generateExpandableHeader(name: string): TemplateResult {+ return html`+ <span class="expandableHeader panel-title" @click="${() => { this.expandPanel(name); }}">+ <or-icon icon="${this.expandedPanels.includes(name) ? 'chevron-down' : 'chevron-right'}"></or-icon>+ <span style="margin-left: 6px; height: 25px; line-height: 25px;">${name}</span>+ </span>+ `+ }+ scalingPresetTemplate(screenPresets: DashboardScreenPreset[], scalingPresets: {key: DashboardScalingPreset, value: string}[]) {+ return html`+ ${screenPresets.map((preset) => {+ return html`+ <div style="margin-bottom: ${screenPresets.length > 1 ? '24px' : '16px'}">+ <div class="label">+ ${html`<span>${unsafeHTML(i18next.t("dashboard.onScreenMyBoardShould").replace("{{size}}", ("<b>" + i18next.t(preset.displayName!) + "</b>")))}</span>`}+ </div>+ <or-mwc-input class="displayInput" type="${InputType.SELECT}" comfortable style="width: 100%;"+ .options="${scalingPresets.map((x) => x.value)}"+ .value="${scalingPresets.find((p) => p.key == preset.scalingPreset)?.value}"+ @or-mwc-input-changed="${(event: OrInputChangedEvent) => {+ preset.scalingPreset = scalingPresets.find((p) => p.value == event.detail.value)?.key;+ this.forceParentUpdate(true);+ this.requestUpdate();+ }}"+ ></or-mwc-input>+ </div>+ `+ })}+ `+ }+ screenPresetTemplate(screenPresets: DashboardScreenPreset[], customLabels?: string[]) {+ return html`+ ${screenPresets.map((preset, index) => {+ return html`+ <div style="margin-bottom: 12px; display: flex; align-items: center; justify-content: space-between;">+ <span style="min-width: 140px;">${customLabels ? customLabels[index] : (preset.displayName + " " + i18next.t('screen'))}</span>+ <div>+ <span style="margin-right: 4px;">${(screenPresets.indexOf(preset) == 0) ? '>' : '<'}</span>+ <or-mwc-input type="${InputType.NUMBER}" comfortable .disabled="${(screenPresets.length > 1 && screenPresets.indexOf(preset) == 0)}" style="width: 70px;"+ .value="${(screenPresets.length > 1 && screenPresets.indexOf(preset) == 0 ? screenPresets[1].breakpoint : preset.breakpoint)}"+ @or-mwc-input-changed="${(event: OrInputChangedEvent) => { this.setBreakpoint(screenPresets.indexOf(preset), event.detail.value)}}"+ ></or-mwc-input>+ <span style="margin-left: 2px;">px</span>+ </div>+ </div>+ `+ })}+ `+ }+++ /* ------------------------- */++}diff --git a/ui/component/or-dashboard-builder/src/or-dashboard-browser.ts b/ui/component/or-dashboard-builder/src/or-dashboard-browser.tsnew file mode 100644index 000000000..27927e29b--- /dev/null+++ b/ui/component/or-dashboard-builder/src/or-dashboard-browser.ts@@ -0,0 +1,149 @@+import {GridStack, GridStackNode } from "gridstack";+import {css, html, LitElement, unsafeCSS } from "lit";+import { customElement, state} from "lit/decorators.js";+import {style} from "./style";+import {widgetTypes} from "./index";++// TODO: Add webpack/rollup to build so consumers aren't forced to use the same tooling+const gridcss = require('gridstack/dist/gridstack.min.css');+const extracss = require('gridstack/dist/gridstack-extra.css');++//language=css+const browserStyling = css`+ #sidebar {+ display: grid;+ padding: 16px;+ }+ #sidebarElement, #sidebarBgElement {+ grid-column: 1;+ grid-row: 1;+ }+ .grid-stack-item {+ cursor: grab;+ }+ .sidebarItem {+ height: 100%;+ background: white;+ display: flex;+ align-items: center;+ justify-content: center;+ overflow: hidden;+ border: 1px solid #E0E0E0;+ border-radius: 8px;+ box-sizing: border-box;+ flex-direction: column;+ font-size: 14px;+ --or-icon-width: 36px;+ }+ .itemText {+ margin-top: 10px;+ }+`++@customElement("or-dashboard-browser")+export class OrDashboardBrowser extends LitElement {++ @state()+ private sidebarGrid?: GridStack;++ @state()+ private backgroundGrid?: GridStack;+++ static get styles() {+ return [unsafeCSS(gridcss), unsafeCSS(extracss), browserStyling, style];+ }++ constructor() {+ super();+ this.updateComplete.then(() => {+ this.renderGrid();+ })+ }++ /* --------------------------------- */++ protected renderGrid() {+ const sidebarElement = this.shadowRoot?.getElementById("sidebarElement");+ const coords: Array<[number, number]> = new Array<[number, number]>([0,0], [2,0], [0,2], [2,2], [4,2], [4,4], [6,4], [6,6], [8,6], [8,8]) // TODO: make this unlimited possibilities with a formula+ const sidebarItems: any[] = Array.from(widgetTypes).map((typeArr, index) => {+ return {x: coords[index][0], y: coords[index][1], w: 2, h: 2, widgetTypeId: typeArr[0], locked: true, content: `<div class="sidebarItem"><or-icon icon="${typeArr[1].DISPLAY_MDI_ICON}"></or-icon><span class="itemText">${typeArr[1].DISPLAY_NAME}</span>`}+ });++ // Setting Sidebar height depending on sidebarItems+ let sidebarHeight = 0;+ sidebarItems.forEach((item) => {+ if((item.y + item.h) > sidebarHeight) {+ sidebarHeight = (item.y + item.h);+ }+ });++ // Creation of the sidebarGrid. Only loads items if already existing+ if(this.sidebarGrid != undefined) {+ this.sidebarGrid.removeAll();+ this.sidebarGrid.load(sidebarItems);+ } else {+ this.sidebarGrid = GridStack.init({+ acceptWidgets: false,+ column: 4,+ cellHeight: 67,+ disableOneColumnMode: true,+ disableResize: true,+ draggable: {+ appendTo: 'parent'+ },+ margin: 8,+ row: sidebarHeight++ // @ts-ignore typechecking, because we can only provide an HTMLElement (which GridHTMLElement inherits)+ }, sidebarElement);+ this.sidebarGrid.load(sidebarItems);++ // If an item gets dropped on the main grid, the dragged item needs to be reset to the sidebar.+ // This is done by just loading the initial/original widget back in the sidebar.+ // @ts-ignore typechecking since we assume they are not undefined+ this.sidebarGrid.on('removed', (_event: Event, items: GridStackNode[]) => {+ if(items.length == 1) {+ const filteredItems = sidebarItems.filter(widget => {+ return (widget.content == items[0].content);+ });+ this.sidebarGrid?.load([filteredItems[0]]);+ }+ });++ // On any change, recreate the grid to prevent users moving Sidebar items around.+ // @ts-ignore typechecking since we assume they are not undefined+ this.sidebarGrid.on('change', (_event: Event, _items: GridStackNode[]) => {+ this.renderGrid();+ });+ }+++ // Seperate Static Background grid (to make it look like the items duplicate)+ const sidebarBgElement = this.shadowRoot?.getElementById("sidebarBgElement");+ if(this.backgroundGrid != undefined) {+ this.backgroundGrid.removeAll();+ this.backgroundGrid.load(sidebarItems);+ } else {+ this.backgroundGrid = GridStack.init({+ staticGrid: true,+ column: 4,+ cellHeight: 67,+ disableOneColumnMode: true,+ margin: 8++ // @ts-ignore typechecking, because we can only provide an HTMLElement (which GridHTMLElement inherits)+ }, sidebarBgElement);+ this.backgroundGrid.load(sidebarItems);+ }+ }++ protected render() {+ return html`+ <div id="sidebar">+ <div id="sidebarElement" class="grid-stack" style="width: 100%; z-index: 3;"></div>+ <div id="sidebarBgElement" class="grid-stack" style="width: 100%; z-index: 2"></div>+ </div>+ `+ }+}diff --git a/ui/component/or-dashboard-builder/src/or-dashboard-keyhandler.ts b/ui/component/or-dashboard-builder/src/or-dashboard-keyhandler.tsnew file mode 100644index 000000000..b21bb3259--- /dev/null+++ b/ui/component/or-dashboard-builder/src/or-dashboard-keyhandler.ts@@ -0,0 +1,25 @@+import { EventEmitter } from "events";++// Inspired by or-rules flow editor Input class+export class DashboardKeyEmitter extends EventEmitter {++ constructor() {+ super();+ window.addEventListener("keydown", this.onkeydown);+ }++ /* ------------------------------------- */++ private onkeydown = (e: KeyboardEvent) => {+ if(e.key == 'Delete') {+ e.preventDefault();+ this.emit('delete', e);+ } else if(e.key == 'Escape') {+ e.preventDefault();+ this.emit('deselect', e);+ } else if(e.key == 's' && e.ctrlKey) {+ e.preventDefault();+ this.emit('save', e);+ }+ }+}diff --git a/ui/component/or-dashboard-builder/src/or-dashboard-preview.ts b/ui/component/or-dashboard-builder/src/or-dashboard-preview.tsnew file mode 100644index 000000000..07034664e--- /dev/null+++ b/ui/component/or-dashboard-builder/src/or-dashboard-preview.ts@@ -0,0 +1,664 @@+import manager, {DefaultColor4, DefaultColor5} from "@openremote/core";+import {css, html, LitElement, TemplateResult, unsafeCSS} from "lit";+import {customElement, property, state} from "lit/decorators.js";+import {style} from "./style";+import "./or-dashboard-widget";+import {debounce} from "lodash";+import {+ DashboardGridItem,+ DashboardScalingPreset,+ DashboardScreenPreset,+ DashboardTemplate,+ DashboardWidget+} from "@openremote/model";+import { getActivePreset } from "./index";+import {InputType, OrInputChangedEvent} from "@openremote/or-mwc-components/or-mwc-input";+import {repeat} from 'lit/directives/repeat.js';+import {GridItemHTMLElement, GridStack, GridStackElement, GridStackNode} from "gridstack";+import {showSnackbar} from "@openremote/or-mwc-components/or-mwc-snackbar";+import { i18next } from "@openremote/or-translate";+import { when } from "lit/directives/when.js";+import { cache } from "lit/directives/cache.js";++// TODO: Add webpack/rollup to build so consumers aren't forced to use the same tooling+const gridcss = require('gridstack/dist/gridstack.min.css');+const extracss = require('gridstack/dist/gridstack-extra.css');++//language=css+const editorStyling = css`++ #view-options {+ padding: 24px;+ display: flex;+ justify-content: center;+ align-items: center;+ }+ /* Margins on view options */+ #fit-btn { margin-right: 10px; }+ #view-preset-select { margin-left: 20px; }+ #width-input { margin-left: 20px; }+ #height-input { margin-left: 10px; }+ #rotate-btn { margin-left: 10px; }++ .maingridContainer {+ position: absolute;+ padding-bottom: 64px;+ }+ .maingridContainer__fullscreen {+ width: 100%;+ }++ .maingrid {+ border: 3px solid #909090;+ background: #FFFFFF;+ border-radius: 8px;+ overflow-x: hidden;+ overflow-y: scroll;+ padding: 4px;+ z-index: 0;+ }+ .maingrid__fullscreen {+ border: none;+ background: transparent;+ border-radius: 0;+ overflow-x: hidden;+ overflow-y: scroll;+ /*height: 100% !important;*/ /* To override .maingrid */+ width: 100% !important; /* To override .maingrid */+ padding: 0;+ /*pointer-events: none;*/+ position: relative;+ z-index: 0;+ }+ .maingrid__disabled {+ pointer-events: none;+ opacity: 40%;+ }+ .grid-stack-item-content {+ background: white;+ box-sizing: border-box;+ border: 1px solid ${unsafeCSS(DefaultColor5)};+ border-radius: 4px;+ overflow: hidden !important;+ }+ .grid-stack-item-content__active {+ border: 2px solid ${unsafeCSS(DefaultColor4)};+ margin: -1px !important; /* to compromise with the extra pixel of border. */+ }++ /* Grid lines on the background of the grid */+ .grid-element {+ background-image:+ linear-gradient(90deg, #E0E0E0, transparent 1px),+ linear-gradient(90deg, transparent calc(100% - 1px), #E0E0E0),+ linear-gradient(#E0E0E0, transparent 1px),+ linear-gradient(transparent calc(100% - 1px), #E0E0E0 100%);+ }+`++/* -------------------------------------------------- */++export interface ORGridStackNode extends GridStackNode {+ widgetTypeId: string;+}+export interface DashboardPreviewSize {+ displayName: string;+ width?: number,+ height?: number,+}++/* ------------------------------------------------------------ */++@customElement("or-dashboard-preview")+export class OrDashboardPreview extends LitElement {++ // Monitoring the changes in the template, save the changes to this.latestChanges,+ // so we can check afterwards which changes are made. Used for+ @property({ hasChanged(oldValue, newValue) { return JSON.stringify(oldValue) != JSON.stringify(newValue); }})+ set template(newValue: DashboardTemplate) {+ const currentValue = this._template;+ if(currentValue != undefined) {+ const changes = {+ changedKeys: Object.keys(newValue).filter(key => (JSON.stringify(newValue[key as keyof DashboardTemplate]) !== JSON.stringify(currentValue[key as keyof DashboardTemplate]))),+ oldValue: currentValue,+ newValue: newValue+ };+ this._template = JSON.parse(JSON.stringify(newValue));+ this.latestChanges = changes;+ this.requestUpdate("template", currentValue);++ // If there is no value yet, do initial setup:+ } else if(newValue != undefined) {+ this._template = newValue;+ this.setupGrid(false, false);+ }+ }++ private _template?: DashboardTemplate;++ get template() {+ return this._template!;+ }++ /* ------------------------ */++ @property() // Optional alternative for template+ protected readonly dashboardId?: string;++ @property() // Normally manager.displayRealm+ protected realm?: string;++ @property({type: Object})+ protected selectedWidget: DashboardWidget | undefined;++ @property()+ protected editMode: boolean = false;++ @property() // For example when no permission+ protected readonly: boolean = true;++ @property()+ protected previewWidth?: string;++ @property()+ protected previewHeight?: string;++ @property()+ protected previewZoom: number = 1;++ @property()+ protected previewSize?: DashboardPreviewSize;++ @property()+ protected availablePreviewSizes?: DashboardPreviewSize[];++ @property()+ protected fullscreen: boolean = true;++ @property() // Property that, when toggled on, shows a "loading" state for 200ms, and then renders the component again.+ protected rerenderPending: boolean = false;++ /* -------------- */++ @state()+ protected grid?: GridStack;++ @state() // State where the changes of the template are saved temporarily (for comparison with incoming data)+ protected latestChanges?: {+ changedKeys: string[],+ oldValue: DashboardTemplate,+ newValue: DashboardTemplate+ }++ @state() // Records time a user is dragging+ protected latestDragWidgetStart?: Date;++ @state()+ protected activePreset?: DashboardScreenPreset;++ @state()+ private rerenderActive: boolean = false;+++ /* ------------------------------------------- */++ // Using constructor to set initial values+ constructor() {+ super();+ if(!this.realm) { this.realm = manager.displayRealm; }+ if(!this.availablePreviewSizes) {+ this.availablePreviewSizes = [+ { displayName: "4k Television", width: 3840, height: 2160 },+ { displayName: "Desktop", width: 1920, height: 1080 },+ { displayName: "Small desktop", width: 1280, height: 720 },+ { displayName: "Phone", width: 360, height: 800 },+ { displayName: "Custom" }+ ]+ }+ // Defaulting to a Phone view+ if(!this.previewSize) { this.previewSize = this.availablePreviewSizes[3]; }+ }++ static get styles() {+ return [unsafeCSS(gridcss), unsafeCSS(extracss), editorStyling, style];+ }++ /* ------------------------------ */++ // Checking whether actual changes have been made; if not, prevent updating.+ shouldUpdate(changedProperties: Map<PropertyKey, unknown>): boolean {+ const changed = changedProperties;+ if(changedProperties.has('latestChanges')+ && this.latestChanges?.changedKeys.length == 0+ && (JSON.stringify((changedProperties.get('latestChanges') as any)?.oldValue)) == (JSON.stringify((changedProperties.get('latestChanges') as any)?.newValue))) {+ changed.delete('latestChanges');+ }+ // Delete ones that not actually change anything+ changed.delete('latestDragWidgetStart');++ return (changed.size == 0 ? false : super.shouldUpdate(changedProperties));+ }+++ // Main method for executing actions after property changes+ updated(changedProperties: Map<string, any>) {+ if(this.realm == undefined) { this.realm = manager.displayRealm; }++ // Setup template (list of widgets and properties)+ if(!this.template && this.dashboardId) {+ manager.rest.api.DashboardResource.get(this.dashboardId)+ .then((response) => { this.template = response.data.template!; })+ .catch((reason) => { console.error(reason); showSnackbar(undefined, i18next.t('errorOccurred')); });+ } else if(this.template == null && this.dashboardId == null) {+ console.warn("Neither the template nor dashboardId attributes have been specified!");+ }++ // If changes to the template have been made+ if(changedProperties.has("latestChanges")) {+ if(this.latestChanges) {+ this.processTemplateChanges(this.latestChanges);+ this.latestChanges = undefined;+ }+ }++ if(changedProperties.has("selectedWidget")) {+ if(this.selectedWidget) {+ if(changedProperties.get("selectedWidget") != undefined) { // if previous selected state was a different widget, dispatch event as well+ this.dispatchEvent(new CustomEvent("deselected", { detail: changedProperties.get("selectedWidget") as DashboardWidget }));+ }+ if(this.grid?.el != null) {+ const foundItem = this.grid?.getGridItems().find((item) => item.gridstackNode?.id == this.selectedWidget?.gridItem?.id);+ if(foundItem != null) { this.selectGridItem(foundItem); }+ this.dispatchEvent(new CustomEvent("selected", { detail: this.selectedWidget }));+ }++ } else {+ // Checking whether the mainGrid is not destroyed and there are Items to deselect...+ if(this.grid?.el != undefined && this.grid?.getGridItems() != null) {+ this.deselectGridItems(this.grid.getGridItems());+ }+ this.dispatchEvent(new CustomEvent("deselected", { detail: changedProperties.get("selectedWidget") as DashboardWidget }));+ }+ }++ // Switching edit/view mode needs recreation of Grid+ if(changedProperties.has("editMode")) {+ if(changedProperties.get('editMode') != undefined) {+ this.setupGrid(true, true);+ }+ }++ // Adjusting previewSize when manual pixels control changes+ if(changedProperties.has("previewWidth") || changedProperties.has("previewHeight")) {+ if(this.template?.screenPresets) {+ this.previewSize = this.availablePreviewSizes?.find(s => ((s.width + "px" == this.previewWidth) && (s.height + "px" == this.previewHeight)));+ }+ }++ // Adjusting pixels control when previewSize changes.+ if(changedProperties.has('previewSize')) {+ if(this.previewSize) {+ this.previewWidth = this.previewSize.width + "px";+ this.previewHeight = this.previewSize.height + "px";+ }+ }++ if(changedProperties.has("rerenderPending")) {+ if(this.rerenderPending) {+ this.setupGrid(true, true).then(() => {+ this.rerenderPending = false;+ this.dispatchEvent(new CustomEvent("rerenderfinished"));+ });+ }+ }++ // When parent component requests a forced rerender+ if(changedProperties.has("rerenderActive")) {+ if(this.rerenderActive) {+ this.rerenderActive = false;+ }+ }+ }+++ /* ---------------------------------------- */++ // Main setup Grid method (often used)+ async setupGrid(recreate: boolean, force: boolean = false) {+ await this.waitUntil((_: any) => this.shadowRoot?.getElementById("gridElement") != null)+ let gridElement = this.shadowRoot?.getElementById("gridElement");+ if(gridElement != null) {+ if(recreate && this.grid != null) {+ this.grid.destroy(false);++ if(force) { // Fully rerender the grid by switching rerenderPending on and off, and continue after that.+ this.rerenderActive = true;+ await this.updateComplete;+ await this.waitUntil((_: any) => !this.rerenderActive);+ gridElement = this.shadowRoot?.getElementById("gridElement");+ this.grid = undefined;+ }+ }+ const width: number = (this.fullscreen ? this.clientWidth : (+(this.previewWidth?.replace(/\D/g, "")!)));+ const newPreset = getActivePreset(width, this.template.screenPresets!);+ if(newPreset?.scalingPreset != this.activePreset?.scalingPreset) {+ if(!(recreate && force)) { // Fully rerender the grid by switching rerenderPending on and off, and continue after that.+ if(!recreate) { // If not destroyed yet, destroy first.+ this.grid?.destroy(false);+ }+ this.rerenderActive = true;+ await this.updateComplete;+ await this.waitUntil((_: any) => !this.rerenderActive);+ gridElement = this.shadowRoot?.getElementById("gridElement");+ this.grid = undefined;+ }+ }+ this.activePreset = newPreset;+++ // If grid got reset, setup the ResizeObserver again.+ if(this.grid == null) {+ const gridHTML = this.shadowRoot?.querySelector(".maingrid");+ this.setupResizeObserver(gridHTML!);+ }++ gridElement!.style.maxWidth = this.template.maxScreenWidth + "px";++ this.grid = GridStack.init({+ acceptWidgets: (this.editMode),+ animate: true,+ cellHeight: (this.activePreset?.scalingPreset == DashboardScalingPreset.WRAP_TO_SINGLE_COLUMN ? (width / (this.template?.columns ? (this.template.columns / 4) : 2)) : 'initial'),+ column: this.template?.columns,+ disableOneColumnMode: (this.activePreset?.scalingPreset != DashboardScalingPreset.WRAP_TO_SINGLE_COLUMN),+ oneColumnModeDomSort: true,+ draggable: {+ appendTo: 'parent', // Required to work, seems to be Shadow DOM related.+ },+ float: true,+ margin: 5,+ resizable: {+ handles: 'all'+ },+ staticGrid: (this.activePreset?.scalingPreset == DashboardScalingPreset.WRAP_TO_SINGLE_COLUMN ? true : (!this.editMode)),+ styleInHead: false+ }, gridElement!);++ gridElement!.style.backgroundSize = "" + this.grid.cellWidth() + "px " + this.grid.getCellHeight() + "px";+ gridElement!.style.height = "100%";+ gridElement!.style.minHeight = "100%";++ this.grid.on('dropped', (_event: Event, _previousWidget: any, newWidget: GridStackNode | undefined) => {+ if(this.grid != null && newWidget != null) {+ this.grid.removeWidget((newWidget.el) as GridStackElement, true, false); // Removes dragged widget first+ this.dispatchEvent(new CustomEvent("dropped", { detail: newWidget }));+ }+ });+ this.grid.on('change', (_event: Event, items: any) => {+ if(this.template != null && this.template.widgets != null) {+ (items as GridStackNode[]).forEach(node => {+ const foundWidget: DashboardWidget | undefined = this.template?.widgets?.find(widget => { return widget.gridItem?.id == node.id; });+ foundWidget!.gridItem!.x = node.x;+ foundWidget!.gridItem!.y = node.y;+ foundWidget!.gridItem!.w = node.w;+ foundWidget!.gridItem!.h = node.h;+ });+ this.dispatchEvent(new CustomEvent("changed", {detail: { template: this.template }}));+ }+ });+ this.grid.on('resizestart', (_event: Event) => {+ this.latestDragWidgetStart = new Date();+ });+ this.grid.on('resizestop', (_event: Event) => {+ setTimeout(() => { this.latestDragWidgetStart = undefined; }, 200);+ });+ }+ }+++ /* ------------------------------- */++ selectGridItem(gridItem: GridItemHTMLElement) {+ if(this.grid != null) {+ this.deselectGridItems(this.grid.getGridItems()); // deselecting all other items+ gridItem.querySelectorAll<HTMLElement>(".grid-stack-item-content").forEach((item: HTMLElement) => {+ item.classList.add('grid-stack-item-content__active'); // Apply active CSS class+ });+ }+ }+ deselectGridItem(gridItem: GridItemHTMLElement) {+ gridItem.querySelectorAll<HTMLElement>(".grid-stack-item-content").forEach((item: HTMLElement) => {+ item.classList.remove('grid-stack-item-content__active'); // Remove active CSS class+ });+ }++ deselectGridItems(gridItems: GridItemHTMLElement[]) {+ gridItems.forEach(item => {+ this.deselectGridItem(item);+ })+ }++ onGridItemClick(gridItem: DashboardGridItem | undefined) {+ if(!this.latestDragWidgetStart && !this.grid?.opts.staticGrid) {+ if(!gridItem) {+ this.selectedWidget = undefined;+ } else if(this.selectedWidget?.gridItem?.id != gridItem.id) {+ this.selectedWidget = this.template?.widgets?.find(widget => { return widget.gridItem?.id == gridItem.id; });+ }+ }+ }++ onFitToScreenClick() {+ const container = this.shadowRoot?.querySelector('#container');+ if(container) {+ const zoomWidth = +((0.95 * container.clientWidth) / +this.previewWidth!.replace('px', '')).toFixed(2);+ this.previewZoom = (zoomWidth > 1 ? 1 : zoomWidth);+ }+ }++ // Render+ protected render() {++ try { // to correct the list of gridItems each render (Hopefully temporarily since it's quite compute heavy)+ if(this.grid?.el && this.grid?.getGridItems()) {+ this.grid?.getGridItems().forEach((gridItem: GridItemHTMLElement) => {+ if(this.template?.widgets?.find((widget) => widget.id == gridItem.id) == undefined) {+ this.grid?.removeWidget(gridItem);+ }+ })+ }+ } catch (e) { console.error(e); }++ // Set manual px height in case of fullscreen, to make scrollbar work without issues (especially when drag-and-dropping widgets)+ this.waitUntil((_: any) => this.shadowRoot?.querySelector('.maingrid') != null).then(() => {+ const grid: HTMLElement = this.shadowRoot?.querySelector('.maingrid') as HTMLElement;+ if(grid && this.fullscreen) {+ grid.style.height = grid.parentElement!.clientHeight + "px";+ }+ const background: HTMLElement = this.shadowRoot?.getElementById('gridElement') as HTMLElement;+ if(background) {+ background.style.height = grid.scrollHeight + "px";+ }+ })++ const customPreset = "Custom";+ let screenPresets = this.template?.screenPresets?.map(s => s.displayName);+ screenPresets?.push(customPreset);+ return html`+ <div id="buildingArea" style="display: flex; flex-direction: column; height: 100%;" @click="${(event: PointerEvent) => { if((event.composedPath()[1] as HTMLElement).id === 'buildingArea') { this.onGridItemClick(undefined); }}}">+ ${this.editMode && !this.fullscreen ? html`+ <div id="view-options">+ <or-mwc-input id="fit-btn" type="${InputType.BUTTON}" icon="fit-to-screen"+ @or-mwc-input-changed="${() => this.onFitToScreenClick()}">+ </or-mwc-input>+ <or-mwc-input id="zoom-input" type="${InputType.NUMBER}" outlined label="${i18next.t('dashboard.zoomPercent')}" min="25" .value="${(this.previewZoom * 100)}" style="width: 90px"+ @or-mwc-input-changed="${debounce((event: OrInputChangedEvent) => { this.previewZoom = event.detail.value / 100; }, 50)}"+ ></or-mwc-input>+ <or-mwc-input id="view-preset-select" type="${InputType.SELECT}" outlined label="${i18next.t('dashboard.presetSize')}" style="min-width: 220px;"+ .value="${this.previewSize == undefined ? customPreset : this.previewSize.displayName}" .options="${this.availablePreviewSizes?.map((x) => x.displayName)}"+ @or-mwc-input-changed="${(event: OrInputChangedEvent) => { this.previewSize = this.availablePreviewSizes?.find(s => s.displayName == event.detail.value); }}"+ ></or-mwc-input>+ <or-mwc-input id="width-input" type="${InputType.NUMBER}" outlined label="${i18next.t('width')}" min="100" .value="${this.previewWidth?.replace('px', '')}" style="width: 90px"+ @or-mwc-input-changed="${debounce((event: OrInputChangedEvent) => { this.previewWidth = event.detail.value + 'px'; }, 550)}"+ ></or-mwc-input>+ <or-mwc-input id="height-input" type="${InputType.NUMBER}" outlined label="${i18next.t('height')}" min="100" .value="${this.previewHeight?.replace('px', '')}" style="width: 90px;"+ @or-mwc-input-changed="${(event: OrInputChangedEvent) => { this.previewHeight = event.detail.value + 'px'; }}"+ ></or-mwc-input>+ <or-mwc-input id="rotate-btn" type="${InputType.BUTTON}" icon="screen-rotation"+ @or-mwc-input-changed="${() => { const newWidth = this.previewHeight; const newHeight = this.previewWidth; this.previewWidth = newWidth; this.previewHeight = newHeight; }}">+ </or-mwc-input>+ </div>+ ` : undefined}+ ${this.rerenderActive ? html`+ <div id="container" style="justify-content: center; align-items: center;">+ <span>${i18next.t('dashboard.renderingGrid')}</span>+ </div>+ ` : html`+ <div id="container" style="justify-content: center; overflow: ${this.fullscreen ? undefined : 'hidden auto'}; position: relative;">+ ${this.activePreset?.scalingPreset == DashboardScalingPreset.BLOCK_DEVICE ? html`+ <div style="position: absolute; z-index: 3; height: 100%; display: flex; align-items: center;">+ <span>${i18next.t('dashboard.deviceNotSupported')}</span>+ </div>+ ` : undefined}+ <div class="${this.fullscreen ? 'maingridContainer__fullscreen' : 'maingridContainer'}">+ <div class="maingrid ${this.fullscreen ? 'maingrid__fullscreen' : undefined }"+ @click="${(ev: MouseEvent) => { if((ev.composedPath()[0] as HTMLElement).id == 'gridElement') { this.onGridItemClick(undefined) }}}"+ style="width: ${this.previewWidth}; height: ${this.previewHeight}; visibility: ${this.activePreset?.scalingPreset == DashboardScalingPreset.BLOCK_DEVICE ? 'hidden' : 'visible'}; zoom: ${this.editMode && !this.fullscreen ? this.previewZoom : 'normal'}; ${this.editMode && !this.fullscreen ? ('-moz-transform: scale(' + this.previewZoom + ')') : undefined}; transform-origin: top;"+ >+ <!-- Gridstack element on which the Grid will be rendered -->+ <div id="gridElement" class="grid-stack ${this.editMode ? 'grid-element' : undefined}" style="margin: auto;">+ ${this.template?.widgets ? repeat(this.template.widgets, (item) => item.id, (widget) => {+ return html`+ <div class="grid-stack-item" id="${widget.id}" gs-id="${widget.gridItem?.id}" gs-x="${widget.gridItem?.x}" gs-y="${widget.gridItem?.y}" gs-w="${widget.gridItem?.w}" gs-h="${widget.gridItem?.h}" @click="${() => { this.onGridItemClick(widget.gridItem); }}">+ <div class="grid-stack-item-content" style="display: flex;">+ <or-dashboard-widget .widget="${widget}" .editMode="${this.editMode}" .realm="${this.realm}" style="width: 100%; height: auto;"></or-dashboard-widget>+ </div>+ </div>+ `+ }) : undefined}+ </div>+ </div>+ </div>+ </div>+ `}+ </div>+ <style>+ ${cache(when(this.isExtraLargeGrid(),+ () => this.applyCustomGridstackGridCSS(this.getGridstackColumns(this.grid) ? this.getGridstackColumns(this.grid)! : this.template.columns!)+ ))}+ </style>+ `+ }++ getGridstackColumns(grid: GridStack | undefined): number | undefined {+ try { return grid?.getColumn(); }+ catch (e) { return undefined; }+ }++ isExtraLargeGrid(): boolean {+ return !!this.grid && (+ (this.getGridstackColumns(this.grid) && this.getGridstackColumns(this.grid)! > 12)+ || !!(this.template?.columns && this.template.columns > 12)+ );+ }++++ private cachedGridstackCSS: Map<number, TemplateResult[]> = new Map<number, TemplateResult[]>();++ // Provides support for > 12 columns in GridStack (which requires manual css edits)+ //language=html+ applyCustomGridstackGridCSS(columns: number): TemplateResult {+ if(this.cachedGridstackCSS.has(columns)) {+ return html`${this.cachedGridstackCSS.get(columns)!.map((x) => x)}`;+ } else {+ const htmls: TemplateResult[] = [];+ for(let i = 0; i < (columns + 1); i++) {+ htmls.push(html`+ <style>+ .grid-stack > .grid-stack-item[gs-w="${i}"]:not(.ui-draggable-dragging):not(.ui-resizable-resizing) { width: ${100 - (columns - i) * (100 / columns)}% !important; }+ .grid-stack > .grid-stack-item[gs-x="${i}"]:not(.ui-draggable-dragging):not(.ui-resizable-resizing) { left: ${100 - (columns - i) * (100 / columns)}% !important; }+ </style>+ `);+ }+ this.cachedGridstackCSS.set(columns, htmls);+ return html`${htmls.map((x) => x)}`;+ }+ }++++ /* ---------------------------------------------- */+++ @state()+ protected resizeObserver?: ResizeObserver;++ protected previousObserverEntry?: ResizeObserverEntry;++ // Triggering a Grid rerender on every time the element resizes.+ // In fullscreen, debounce (only trigger after 550ms of no changes) to limit amount of rerenders.+ setupResizeObserver(element: Element): ResizeObserver {+ this.resizeObserver?.disconnect();+ if(this.fullscreen) {+ this.resizeObserver = new ResizeObserver(debounce(this.resizeObserverCallback, 200));+ } else {+ this.resizeObserver = new ResizeObserver(this.resizeObserverCallback);+ }+ this.resizeObserver.observe(element);+ return this.resizeObserver;+ }++ protected resizeObserverCallback: ResizeObserverCallback = (entries: ResizeObserverEntry[]) => {+ if((this.previousObserverEntry?.contentRect.width + "px") !== (entries[0].contentRect.width + "px")) {+ this._onGridResize();+ }+ this.previousObserverEntry = entries[0];+ }++ _onGridResize() {+ this.setupGrid(true, false);+ }++ /* --------------------------------------- */++ processTemplateChanges(changes: { changedKeys: string[], oldValue: DashboardTemplate, newValue: DashboardTemplate }) {++ // If only columns property changed, change columns through the framework and then recreate grid.+ if(changes.changedKeys.length == 1 && changes.changedKeys.includes('columns') && this.grid) {+ this.grid.column(changes.newValue.columns!);+ let maingrid = this.shadowRoot?.querySelector(".maingrid");+ let gridElement = this.shadowRoot?.getElementById("gridElement");+ gridElement!.style.backgroundSize = "" + this.grid.cellWidth() + "px " + this.grid.getCellHeight() + "px";+ gridElement!.style.height = maingrid!.scrollHeight + 'px';+ this.setupGrid(true, false);+ }++ // If multiple properties changed, just force rerender all of it.+ else if(changes.changedKeys.length > 1) {+ this.setupGrid(true, true);+ }++ // On widgets change, check whether they are programmatically added to GridStack. If not, adding them.+ else if(changes.changedKeys.includes('widgets')) {+ if(this.grid?.el != null) {+ this.grid.getGridItems().forEach((gridElement) => {+ if(!gridElement.classList.contains('ui-draggable')) {+ this.grid?.makeWidget(gridElement);+ }+ })+ }+ }+ else if(changes.changedKeys.includes('screenPresets')) {+ this.setupGrid(true, true);+ }+ }++ // Wait until function that waits until a boolean returns differently+ waitUntil(conditionFunction: any) {+ const poll = (resolve: any) => {+ if(conditionFunction()) resolve();+ else setTimeout(_ => poll(resolve), 400);+ }+ return new Promise(poll);+ }+}diff --git a/ui/component/or-dashboard-builder/src/or-dashboard-settingspanel.ts b/ui/component/or-dashboard-builder/src/or-dashboard-settingspanel.tsnew file mode 100644index 000000000..5255557d8--- /dev/null+++ b/ui/component/or-dashboard-builder/src/or-dashboard-settingspanel.ts@@ -0,0 +1,334 @@+import manager, { DefaultColor5, Util } from "@openremote/core";+import {Asset, AssetModelUtil, AttributeRef} from "@openremote/model";+import {OrAttributePicker, OrAttributePickerPickedEvent} from "@openremote/or-attribute-picker";+import {getAssetDescriptorIconTemplate} from "@openremote/or-icon";+import {showDialog} from "@openremote/or-mwc-components/or-mwc-dialog";+import {InputType} from "@openremote/or-mwc-components/or-mwc-input";+import {showSnackbar} from "@openremote/or-mwc-components/or-mwc-snackbar";+import {i18next} from "@openremote/or-translate";+import {css, html, LitElement, unsafeCSS} from "lit";+import {customElement, property, state} from "lit/decorators.js";+import { until } from "lit/directives/until.js";+import {OrWidgetConfig} from "./widgets/or-base-widget";+import {style} from "./style";++//language=css+export const widgetSettingsStyling = css`++ /* ------------------------------- */+ .switchMwcInputContainer {+ display: flex;+ align-items: center;+ justify-content: space-between;+ }++ /* ---------------------------- */+ #attribute-list {+ overflow: auto;+ flex: 1 1 0;+ min-height: 150px;+ width: 100%;+ display: flex;+ flex-direction: column;+ }++ .attribute-list-item {+ cursor: pointer;+ display: flex;+ flex-direction: row;+ align-items: center;+ padding: 0;+ min-height: 50px;+ }++ .attribute-list-item-label {+ display: flex;+ flex: 1 1 0;+ line-height: 16px;+ flex-direction: column;+ }++ .attribute-list-item-bullet {+ width: 14px;+ height: 14px;+ border-radius: 7px;+ margin-right: 10px;+ }++ .attribute-list-item .button.delete {+ display: none;+ }++ .attribute-list-item:hover .button.delete {+ display: block;+ }++ /* ---------------------------- */+ .button-clear {+ background: none;+ visibility: hidden;+ color: ${unsafeCSS(DefaultColor5)};+ --or-icon-fill: ${unsafeCSS(DefaultColor5)};+ display: inline-block;+ border: none;+ padding: 0;+ cursor: pointer;+ }++ .attribute-list-item:hover .button-clear {+ visibility: visible;+ }++ .button-clear:hover {+ --or-icon-fill: var(--or-app-color4);+ }++ /* ---------------------------- */++ .threshold-list-item:hover .button-clear {+ visibility: visible;+ }+`++export enum SettingsPanelType {+ SINGLE_ATTRIBUTE, MULTI_ATTRIBUTE, THRESHOLDS,+}+++@customElement('or-dashboard-settingspanel')+export class OrDashboardSettingsPanel extends LitElement {++ @property()+ private readonly type?: SettingsPanelType;++ @property()+ private readonly widgetConfig: OrWidgetConfig | any;+ private _config?: OrWidgetConfig | any; // local duplicate that does not update parent. Sent back in dispatchEvent() only.++ @property({type: Boolean}) // used for SINGLE_ATTRIBUTE and MULTI_ATTRIBUTE types.+ private readonly onlyDataAttrs: boolean = true;++ @state()+ private loadedAssets?: Asset[];++ static get styles() {+ return [style, widgetSettingsStyling];+ }+++ /* ---------------------------- */++ // Setting local duplicate config before triggering update,+ // and fetching assets if any of the AttributeRefs are not pulled yet.+ willUpdate(changedProperties: Map<string, any>) {+ if(changedProperties.has("widgetConfig")) {+ if(!this._config || (changedProperties.get("widgetConfig") != this._config) && this.widgetConfig.attributeRefs) {+ const loadedRefs: AttributeRef[] = this.widgetConfig.attributeRefs.filter((attrRef: AttributeRef) => this.isAttributeRefLoaded(attrRef));+ if(loadedRefs.length != this.widgetConfig.attributeRefs.length) {+ this.fetchAssets(this.widgetConfig).then(assets => {+ this.loadedAssets = assets;+ });+ }+ }+ this._config = (this.widgetConfig ? JSON.parse(JSON.stringify(this.widgetConfig)) : undefined);+ }+ }+++ /* ---------------------------------- */++ render() {+ switch (this.type) {++ case SettingsPanelType.SINGLE_ATTRIBUTE:+ case SettingsPanelType.MULTI_ATTRIBUTE: {+ if (!this._config.attributeRefs) {+ return html`<span>${i18next.t('errorOccurred')}</span>`;+ } else {+ return html`+ ${until(this.getAttributeHTML(this._config, (this.type == SettingsPanelType.MULTI_ATTRIBUTE), this.onlyDataAttrs), html`${i18next.t('loading')}`)}+ `;+ }+ }+ case SettingsPanelType.THRESHOLDS: {+ if (!this._config.thresholds) {+ return html`<span>${i18next.t('errorOccurred')}</span>`;+ } else {+ return html`+ ${until(this.getThresholdsHTML(this._config), html`${i18next.t('loading')}`)}+ `;+ }+ }+ }+ }+++ /* --------------------------------- */++ // UTILITY FUNCTIONS+++ // Method to update the Grid. For example after changing a setting.+ updateParent(changes: Map<string, any>, force: boolean = false) {+ this.dispatchEvent(new CustomEvent('updated', {detail: {changes: changes, force: force}}));+ }++ async getAttributeHTML(config: any, multi: boolean, onlyDataAttrs: boolean = true) {+ return html`+ <div style="padding: 0 14px 12px 14px;">+ ${(config.attributeRefs == null || config.attributeRefs.length == 0) ? html`+ <span>${i18next.t('noAttributesConnected')}</span>+ ` : undefined}+ <div id="attribute-list">+ ${(config.attributeRefs != null && this.loadedAssets != null) ? config.attributeRefs.map((attributeRef: AttributeRef) => {+ const asset = this.loadedAssets?.find((x: Asset) => {+ return x.id == attributeRef.id;+ }) as Asset;+ if(asset) {+ const attribute = asset.attributes![attributeRef.name!];+ const descriptors = AssetModelUtil.getAttributeAndValueDescriptors(asset.type, attributeRef.name, attribute);+ const label = Util.getAttributeLabel(attribute, descriptors[0], asset.type, true);+ return html`+ <div class="attribute-list-item">+ <span style="margin-right: 10px; --or-icon-width: 20px;">${getAssetDescriptorIconTemplate(AssetModelUtil.getAssetDescriptor(asset.type))}</span>+ <div class="attribute-list-item-label">+ <span>${asset.name}</span>+ <span style="font-size:14px; color:grey;">${label}</span>+ </div>+ <button class="button-clear" @click="${() => this.removeWidgetAttribute(attributeRef)}">+ <or-icon icon="close-circle"></or-icon>+ </button>+ </div>+ `;+ } else {+ return undefined;+ }+ }) : undefined}+ </div>+ <or-mwc-input .type="${InputType.BUTTON}" label="${i18next.t('attribute')}" icon="plus"+ style="margin-top: 24px; margin-left: -7px;"+ @or-mwc-input-changed="${() => this.openDialog(config.attributeRefs, multi, onlyDataAttrs)}">+ </or-mwc-input>+ </div>+ `+ }++ isAttributeRefLoaded(attrRef: AttributeRef) {+ return this.loadedAssets?.find((asset) => asset.id == attrRef.id)+ }++ // Fetching the assets according to the AttributeRef[] input in DashboardWidget if required.+ async fetchAssets(config: OrWidgetConfig | any): Promise<Asset[] | undefined> {+ if (config.attributeRefs) {+ let assets: Asset[] = [];+ await manager.rest.api.AssetResource.queryAssets({+ ids: config.attributeRefs?.map((x: AttributeRef) => x.id) as string[],+ select: {+ attributes: config.attributeRefs?.map((x: AttributeRef) => x.name) as string[]+ }+ }).then(response => {+ assets = response.data;+ }).catch((reason) => {+ console.error(reason);+ showSnackbar(undefined, i18next.t('errorOccurred'));+ });+ return assets;+ } else {+ console.error("Error: attributeRefs are not present in widget config!");+ }+ }++ setWidgetAttributes(selectedAttrs?: AttributeRef[]) {+ if (this._config != null) {+ this._config.attributeRefs = selectedAttrs;+ this.fetchAssets(this._config).then((assets) => {+ this.loadedAssets = assets;+ this.updateComplete.then(() => {+ this.updateParent(new Map<string, any>([["config", this._config], ["loadedAssets", assets]]));+ });+ });+ }+ }++ removeWidgetAttribute(attributeRef: AttributeRef) {+ if (this._config.attributeRefs != null) {+ this._config.attributeRefs.splice(this._config.attributeRefs.indexOf(attributeRef), 1);+ this.updateParent(new Map<string, any>([["config", this._config]]));+ }+ }++ // Opening the attribute picker dialog, and listening to its result. (UI related)+ openDialog(attributeRefs: AttributeRef[], multi: boolean, onlyDataAttrs: boolean = true) {+ let dialog: OrAttributePicker;+ if (attributeRefs != null) {+ dialog = showDialog(new OrAttributePicker().setMultiSelect(multi).setSelectedAttributes(attributeRefs).setShowOnlyDatapointAttrs(onlyDataAttrs));+ } else {+ dialog = showDialog(new OrAttributePicker().setMultiSelect(multi).setShowOnlyDatapointAttrs(onlyDataAttrs))+ }+ dialog.addEventListener(OrAttributePickerPickedEvent.NAME, (event: CustomEvent) => {+ this.setWidgetAttributes(event.detail);+ })+ }++++ /* ---------------------------------------------------- */++ async getThresholdsHTML(config: OrWidgetConfig | any) {+ if(config.thresholds) {+ return html`+ <div id="thresholds-list" style="padding: 0 14px 12px 14px;">+ ${(config.thresholds as [number, string][]).sort((x, y) => (x[0] < y[0]) ? -1 : 1).map((threshold, index) => {+ return html`+ <div class="threshold-list-item" style="padding: 8px 0; display: flex; flex-direction: row; align-items: center;">+ <div style="height: 100%; padding: 8px 14px 8px 0;">+ <or-mwc-input type="${InputType.COLOUR}" value="${threshold[1]}" style="width: 32px; height: 32px;"+ @or-mwc-input-changed="${(event: CustomEvent) => {+ this._config.thresholds[index][1] = event.detail.value;+ this.updateParent(new Map<string, any>([["config", this._config]]));+ }}"+ ></or-mwc-input>+ </div>+ <or-mwc-input type="${InputType.NUMBER}" comfortable .value="${threshold[0]}" ?disabled="${index == 0}"+ .min="${config.min}" .max="${config.max}"+ @or-mwc-input-changed="${(event: CustomEvent) => {+ if(event.detail.value >= config.min && event.detail.value <= config.max) {+ this._config.thresholds[index][0] = event.detail.value;+ this.updateParent(new Map<string, any>([["config", this._config]]));+ }+ }}"+ ></or-mwc-input>+ <button class="button-clear" style="margin-left: 8px; ${index == 0 ? 'visibility: hidden;' : undefined}"+ @click="${() => { this.removeThreshold(this._config, threshold); }}">+ <or-icon icon="close-circle"></or-icon>+ </button>+ </div>+ `+ })}+ <or-mwc-input .type="${InputType.BUTTON}" label="${i18next.t('threshold')}" icon="plus"+ style="margin-top: 24px; margin-left: -7px;"+ @or-mwc-input-changed="${() => this.addNewThreshold(this._config)}">+ </or-mwc-input>+ </div>+ `+ }+ }++ removeThreshold(config: any, threshold: [number, string]) {+ config.thresholds = (config.thresholds as [number, string][]).filter((x) => x != threshold);+ this.updateParent(new Map<string, any>([["config", this._config]]));+ }+ addThreshold(config: any, threshold: [number, string]) {+ (config.thresholds as [number, string][]).push(threshold);+ this.updateParent(new Map<string, any>([["config", this._config]]));+ }+ addNewThreshold(config: any) {+ const suggestedValue = (config.thresholds[config.thresholds.length - 1][0] + 10);+ this.addThreshold(config, [(suggestedValue <= config.max ? suggestedValue : config.max), "#000000"]);+ this.updateComplete.then(() => {+ const elem = this.shadowRoot?.getElementById('thresholds-list') as HTMLElement;+ const inputField = Array.from(elem.children)[elem.children.length - 2] as HTMLElement;+ (inputField.children[1] as HTMLElement).setAttribute('focused', 'true');+ })+ }+}diff --git a/ui/component/or-dashboard-builder/src/or-dashboard-tree.ts b/ui/component/or-dashboard-builder/src/or-dashboard-tree.tsnew file mode 100644index 000000000..a74712b50--- /dev/null+++ b/ui/component/or-dashboard-builder/src/or-dashboard-tree.ts@@ -0,0 +1,282 @@+import {css, html, LitElement} from "lit";+import { customElement, property} from "lit/decorators.js";+import {InputType} from '@openremote/or-mwc-components/or-mwc-input';+import "@openremote/or-icon";+import {style} from "./style";+import {Dashboard, DashboardScalingPreset, DashboardScreenPreset} from "@openremote/model";+import manager from "@openremote/core";+import {ListItem} from "@openremote/or-mwc-components/or-mwc-list";+import "@openremote/or-mwc-components/or-mwc-menu";+import {showOkCancelDialog} from "@openremote/or-mwc-components/or-mwc-dialog";+import { i18next } from "@openremote/or-translate";+import {showSnackbar} from "@openremote/or-mwc-components/or-mwc-snackbar";+import {style as OrAssetTreeStyle} from "@openremote/or-asset-tree";++//language=css+const treeStyling = css`+ #header-btns {+ display: flex;+ flex-direction: row;+ padding-right: 5px;+ }+ .node-container {+ align-items: center;+ padding-left: 10px;+ }+`;++enum DashboardSizeOption {+ DESKTOP, MOBILE+}++@customElement("or-dashboard-tree")+export class OrDashboardTree extends LitElement {++ static get styles() {+ return [style, treeStyling, OrAssetTreeStyle];+ }++ @property()+ protected realm?: string;++ @property()+ private dashboards: Dashboard[] | undefined;++ @property({hasChanged: (oldVal, val): boolean => {+ return JSON.stringify(oldVal) != JSON.stringify(val);+ }})+ private selected: Dashboard | undefined;++ @property() // REQUIRED+ private readonly userId?: string;++ @property()+ private readonly readonly: boolean = true;++ @property()+ protected hasChanged: boolean = false;++ @property()+ protected showControls: boolean = true;+++ /* --------------- */++ constructor() {+ super();+ this.updateComplete.then(async () => {+ if(this.dashboards == undefined) {+ await this.getAllDashboards();+ }+ });+ }++ private async getAllDashboards() {+ return manager.rest.api.DashboardResource.getAllRealmDashboards(this.realm!)+ .then((result) => {+ this.dashboards = result.data;+ }).catch((reason) => {+ console.error(reason);+ showSnackbar(undefined, i18next.t('errorOccurred'));+ });+ }++ updated(changedProperties: Map<string, any>) {+ if(this.realm == undefined) { this.realm = manager.displayRealm; }++ if(changedProperties.has("dashboards") && changedProperties.get("dashboards") != null) {+ this.dispatchEvent(new CustomEvent("updated", { detail: this.dashboards }));+ }+ if(changedProperties.has("selected")) {+ this.dispatchEvent(new CustomEvent("select", { detail: this.selected }));+ }+ }+++ /* ---------------------- */++ private createDashboard(size: DashboardSizeOption) {+ const randomId = (Math.random() + 1).toString(36).substring(2);+ const dashboard = {+ realm: this.realm!,+ displayName: this.getDefaultDisplayName(size),+ template: {+ id: randomId,+ columns: this.getDefaultColumns(size),+ maxScreenWidth: this.getDefaultMaxScreenWidth(size),+ screenPresets: this.getDefaultScreenPresets(size),+ }+ } as Dashboard+ manager.rest.api.DashboardResource.create(dashboard).then((response => {+ if(response.status == 200) {+ this.dashboards?.push(response.data);+ this.requestUpdate("dashboards");+ this.dispatchEvent(new CustomEvent("created", { detail: { dashboard: response.data }}));++ // Select the item that was created+ this.selected = this.dashboards?.find((x) => { return x.id == response.data.id; });+ }+ })).catch((reason) => {+ console.error(reason);+ showSnackbar(undefined, i18next.t('errorOccurred'));+ })+ }++ private selectDashboard(id: string | Dashboard | undefined) {+ if(typeof id == 'string') {+ this.selected = this.dashboards?.find((dashboard) => { return dashboard.id == id; });+ } else {+ this.selected = id;+ }+ }++ private deleteDashboard(dashboard: Dashboard) {+ if(dashboard.id != null) {+ manager.rest.api.DashboardResource.delete({dashboardId: [dashboard.id]})+ .then((response) => {+ if(response.status == 204) {+ this.getAllDashboards();+ }+ }).catch((reason) => {+ console.error(reason);+ showSnackbar(undefined, i18next.t('errorOccurred'));+ })+ }+ }++ /* ---------------------- */++ protected render() {+ const dashboardItems: ListItem[][] = []+ if(this.dashboards!.length > 0) {+ if(this.userId) {+ const myDashboards: Dashboard[] = [];+ const otherDashboards: Dashboard[] = [];+ this.dashboards?.forEach((d) => {+ (d.ownerId == this.userId) ? myDashboards.push(d) : otherDashboards.push(d);+ })+ if(myDashboards.length > 0) {+ const items: ListItem[] = [];+ myDashboards.forEach((d) => { items.push({ icon: "view-dashboard", text: d.displayName, value: d.id }); });+ dashboardItems.push(items);+ }+ if(otherDashboards.length > 0) {+ const items: ListItem[] = [];+ otherDashboards.forEach((d) => { items.push({ icon: "view-dashboard", text: d.displayName, value: d.id }); });+ dashboardItems.push(items);+ }+ }+ }+ return html`+ <div id="menu-header">+ <div id="title-container">+ <span id="title">${i18next.t('insights')}</span>+ </div>+ ${this.showControls ? html`+ <div id="header-btns">+ ${this.selected != null ? html`+ <or-mwc-input type="${InputType.BUTTON}" icon="close" @or-mwc-input-changed="${() => { this.selectDashboard(undefined); }}"></or-mwc-input>+ ${!this.readonly ? html`+ <or-mwc-input type="${InputType.BUTTON}" icon="delete" @or-mwc-input-changed="${() => { if(this.selected != null) {+ showOkCancelDialog(i18next.t('areYouSure'), i18next.t('dashboard.deletePermanentWarning', { dashboard: this.selected.displayName }), i18next.t('delete')).then((ok: boolean) => { if(ok) { this.deleteDashboard(this.selected!); }});+ }}}"></or-mwc-input>+ ` : undefined}+ ` : undefined}+ ${!this.readonly ? html`+ <span style="--or-icon-fill: black">+ <or-mwc-input type="${InputType.BUTTON}" class="hideMobile" icon="plus" style="--or-icon-fill: white;"+ @or-mwc-input-changed="${() => { this.createDashboard(DashboardSizeOption.DESKTOP); }}"+ ></or-mwc-input>+ </span>+ ` : undefined}+ </div>+ ` : undefined}+ </div>+ <div id="content">+ <div style="padding-top: 8px;">+ ${dashboardItems.map((items, index) => {+ return (items != null && items.length > 0) ? html`+ <div style="padding: 8px 0;">+ <span style="font-weight: 500; padding-left: 14px; color: #000000;">${(index == 0 ? i18next.t('dashboard.myDashboards') : i18next.t('dashboard.createdByOthers'))}</span>+ <div id="list-container">+ <ol id="list">+ ${items.map((listItem: ListItem) => {+ return html`+ <li ?data-selected="${listItem.value == this.selected?.id}" @click="${(_evt: MouseEvent) => {+ if(listItem.value != this.selected?.id) {+ if(this.hasChanged) {+ showOkCancelDialog(i18next.t('areYouSure'), i18next.t('confirmContinueDashboardModified'), i18next.t('discard')).then((ok: boolean) => {+ if(ok) { this.selectDashboard(listItem.value); }+ });+ } else {+ this.selectDashboard(listItem.value);+ }+ }+ }}">+ <div class="node-container">+ <span class="node-name">${listItem.text} </span>+ </div>+ </li>+ `+ })}+ </ol>+ </div>+ </div>+ ` : undefined+ })}+ </div>+ </div>+ `+ }++++ /* ------------------ */++ // TODO: Needs to be moved to probably model itself+ private getDefaultColumns(preset: DashboardSizeOption): number {+ switch (preset) {+ case DashboardSizeOption.MOBILE: { return 4; }+ case DashboardSizeOption.DESKTOP: { return 12; }+ default: { return 12; }+ }+ }++ // TODO: Needs to be moved to probably model itself+ private getDefaultDisplayName(preset: DashboardSizeOption): string {+ switch (preset) {+ case DashboardSizeOption.DESKTOP: { return i18next.t('dashboard.initialName'); }+ case DashboardSizeOption.MOBILE: { return i18next.t('dashboard.initialName') + " (" + i18next.t('dashboard.size.mobile') + ")"; }+ }+ }++ // TODO: Needs to be moved to probably model itself+ private getDefaultScreenPresets(preset: DashboardSizeOption): DashboardScreenPreset[] {+ switch (preset) {+ case DashboardSizeOption.MOBILE: {+ return [{+ id: "mobile",+ displayName: 'dashboard.size.mobile',+ breakpoint: 640,+ scalingPreset: DashboardScalingPreset.KEEP_LAYOUT+ }];+ }+ default: { // DashboardSizeOption.DESKTOP since that is the default+ return [{+ id: "mobile",+ displayName: 'dashboard.size.mobile',+ breakpoint: 640,+ scalingPreset: DashboardScalingPreset.WRAP_TO_SINGLE_COLUMN+ }];+ }+ }+ }++ // TODO: Needs to be moved to probably model itself+ private getDefaultMaxScreenWidth(preset: DashboardSizeOption): number {+ switch (preset) {+ case DashboardSizeOption.DESKTOP: return 4000;+ case DashboardSizeOption.MOBILE: return 640;+ }+ }+}diff --git a/ui/component/or-dashboard-builder/src/or-dashboard-widget.ts b/ui/component/or-dashboard-builder/src/or-dashboard-widget.tsnew file mode 100644index 000000000..eac912167--- /dev/null+++ b/ui/component/or-dashboard-builder/src/or-dashboard-widget.ts@@ -0,0 +1,105 @@+import {DashboardWidget } from "@openremote/model";+import { InputType } from "@openremote/or-mwc-components/or-mwc-input";+import { i18next } from "@openremote/or-translate";+import {css, html, LitElement, TemplateResult } from "lit";+import { customElement, property, query, state } from "lit/decorators.js";+import { when } from "lit/directives/when.js";+import {throttle} from "lodash";+import {style} from "./style";+import {widgetTypes} from "./index";++//language=css+const styling = css`+`++/* ------------------------------------ */++@customElement("or-dashboard-widget")+export class OrDashboardWidget extends LitElement {++ @property({ hasChanged(oldValue, newValue) { return JSON.stringify(oldValue) != JSON.stringify(newValue); }})+ protected readonly widget?: DashboardWidget;++ @property()+ protected readonly editMode?: boolean;++ @property()+ protected readonly realm?: string;++ @property()+ protected loading: boolean = false;++ @state()+ protected error?: string;++ @state()+ protected resizeObserver?: ResizeObserver;++ @query("#widget-container")+ protected widgetContainerElement?: Element;+++ static get styles() {+ return [styling, style];+ }++ constructor() {+ super();+ }++ shouldUpdate(changedProperties: Map<PropertyKey, unknown>): boolean {+ const changed = changedProperties;+ changed.delete('resizeObserver');+ return changed.size > 0;+ }++ firstUpdated(_changedProperties: Map<string, any>) {+ this.updateComplete.then(() => {+ const gridItemElement = this.widgetContainerElement;+ if(gridItemElement) {+ this.resizeObserver?.disconnect();+ this.resizeObserver = new ResizeObserver(throttle(() => {+ const isMinimumSize: boolean = (this.widget?.gridItem?.minPixelW != null && this.widget.gridItem.minPixelH != null &&+ (this.widget.gridItem.minPixelW < gridItemElement.clientWidth) && (this.widget.gridItem.minPixelH < gridItemElement.clientHeight)+ );+ this.error = (isMinimumSize ? undefined : i18next.t('dashboard.widgetTooSmall'));+ }, 200));+ this.resizeObserver.observe(gridItemElement);+ } else {+ console.error("gridItemElement could not be found!");+ }+ });+ }+++ protected render() {+ return html`+ <div id="widget-container" style="height: 100%; padding: 8px 16px 8px 16px; display: flex; flex-direction: column; overflow: auto;">+ <div style="display: flex; justify-content: space-between; align-items: center; margin-right: -12px; height: 36px;">+ <span class="panel-title" style="width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">${this.widget?.displayName?.toUpperCase()}</span>+ <div>+ <!--<or-mwc-input type="${InputType.BUTTON}" outlined label="Period"></or-mwc-input>-->+ <!--<or-mwc-input type="${InputType.BUTTON}" label="Settings"></or-mwc-input>-->+ <!--<or-mwc-input type="${InputType.BUTTON}" icon="refresh" @or-mwc-input-changed="${() => { this.requestUpdate(); }}"></or-mwc-input>-->+ </div>+ </div>+ ${when((!this.error && !this.loading), () => html`+ ${this.getWidgetContent(this.widget!)}+ `, () => html`+ ${this.error ? html`${this.error}` : html`${i18next.t('loading')}`}+ `)}+ </div>+ `+ }++ getWidgetContent(widget: DashboardWidget): TemplateResult {+ const _widget = Object.assign({}, widget);+ if(_widget.gridItem) {++ const widgetEntity = widgetTypes.get(widget.widgetTypeId!);+ return widgetEntity!.getWidgetHTML(this.widget!, this.editMode!, this.realm!);++ }+ return html`<span>${i18next.t('error')}!</span>`;+ }+}diff --git a/ui/component/or-dashboard-builder/src/or-dashboard-widgetsettings.ts b/ui/component/or-dashboard-builder/src/or-dashboard-widgetsettings.tsnew file mode 100644index 000000000..dfd7d04dc--- /dev/null+++ b/ui/component/or-dashboard-builder/src/or-dashboard-widgetsettings.ts@@ -0,0 +1,162 @@+import {Asset, DashboardWidget } from "@openremote/model";+import {css, html, LitElement, TemplateResult, unsafeCSS } from "lit";+import { customElement, property, state } from "lit/decorators.js";+import { InputType, OrInputChangedEvent } from "@openremote/or-mwc-components/or-mwc-input";+import {style} from './style';+import {DefaultColor5} from "@openremote/core";+import { i18next } from "@openremote/or-translate";+import {widgetTypes} from "./index";++const tableStyle = require("@material/data-table/dist/mdc.data-table.css");++//language=css+const widgetSettingsStyling = css`++ /* ------------------------------- */+ .switchMwcInputContainer {+ display: flex;+ align-items: center;+ justify-content: space-between;+ }+ /* ---------------------------- */+ #attribute-list {+ overflow: auto;+ flex: 1 1 0;+ min-height: 150px;+ width: 100%;+ display: flex;+ flex-direction: column;+ }++ .attribute-list-item {+ cursor: pointer;+ display: flex;+ flex-direction: row;+ align-items: center;+ padding: 0;+ min-height: 50px;+ }++ .attribute-list-item-label {+ display: flex;+ flex: 1 1 0;+ line-height: 16px;+ flex-direction: column;+ }++ .attribute-list-item-bullet {+ width: 14px;+ height: 14px;+ border-radius: 7px;+ margin-right: 10px;+ }++ .attribute-list-item .button.delete {+ display: none;+ }++ .attribute-list-item:hover .button.delete {+ display: block;+ }++ /* ---------------------------- */+ .button-clear {+ background: none;+ visibility: hidden;+ color: ${unsafeCSS(DefaultColor5)};+ --or-icon-fill: ${unsafeCSS(DefaultColor5)};+ display: inline-block;+ border: none;+ padding: 0;+ cursor: pointer;+ }++ .attribute-list-item:hover .button-clear {+ visibility: visible;+ }++ .button-clear:hover {+ --or-icon-fill: var(--or-app-color4);+ }+ /* ---------------------------- */+`++/* ------------------------------------ */++@customElement("or-dashboard-widgetsettings")+export class OrDashboardWidgetsettings extends LitElement {++ static get styles() {+ return [unsafeCSS(tableStyle), widgetSettingsStyling, style]+ }++ @property({type: Object})+ protected selectedWidget: DashboardWidget | undefined;++ @property()+ protected realm?: string;++ @state() // list of assets that are loaded in the list+ protected loadedAssets: Asset[] | undefined;++ @state()+ protected expandedPanels: string[];++ constructor() {+ super();+ this.expandedPanels = [];+ }++ /* ------------------------------------ */+++ // Method to update the Grid. For example after changing a setting.+ forceParentUpdate(changes: Map<string, any>, force: boolean = false) {+ this.requestUpdate();+ this.dispatchEvent(new CustomEvent('update', { detail: { changes: changes, force: force }}));+ }++ protected render() {+ this.updateComplete.then(() => {+ const settingElem = this.shadowRoot?.children[0].children[1];+ settingElem!.addEventListener('updated', (event: any) => {+ this.forceParentUpdate(event.detail.changes, event.detail.force);+ });+ });+ if(this.selectedWidget?.widgetTypeId != null && this.selectedWidget.widgetConfig != null) {+ return this.generateHTML(this.selectedWidget.widgetTypeId, this.selectedWidget.widgetConfig);+ }+ return html`<span>${i18next.t('errorOccurred')}</span>`+ }+++++ /* ----------------------------------- */++ // UI generation of all settings fields. Depending on the WidgetType it will+ // return different HTML containing different settings.+ generateHTML(widgetTypeId: string, widgetConfig: any): TemplateResult {+ let htmlGeneral: TemplateResult;+ let htmlContent: TemplateResult;+ htmlGeneral = html`+ <div style="padding: 12px;">+ <div>+ <or-mwc-input .type="${InputType.TEXT}" style="width: 100%;" .value="${this.selectedWidget?.displayName}" label="${i18next.t('name')}"+ @or-mwc-input-changed="${(event: OrInputChangedEvent) => {+ this.selectedWidget!.displayName = event.detail.value;+ this.forceParentUpdate(new Map<string, any>([['widget', this.selectedWidget]])); }}"+ ></or-mwc-input>+ </div>+ </div>+ `+ htmlContent = widgetTypes.get(widgetTypeId)!.getSettingsHTML(this.selectedWidget!, this.realm!);++ return html`+ <div>+ ${htmlGeneral}+ ${htmlContent}+ </div>+ `+ }+}diff --git a/ui/component/or-dashboard-builder/src/style.ts b/ui/component/or-dashboard-builder/src/style.tsnew file mode 100644index 000000000..0db76d66b--- /dev/null+++ b/ui/component/or-dashboard-builder/src/style.ts@@ -0,0 +1,99 @@+import { css, unsafeCSS } from "lit";+import {DefaultColor1, DefaultColor2, DefaultColor4, DefaultColor5} from "@openremote/core";+++// language=CSS+export const style = css`++ :host {+ --internal-or-asset-tree-header-color: var(--or-asset-tree-header-color, var(--or-app-color4, ${unsafeCSS(DefaultColor4)}));+ --internal-or-asset-tree-header-text-color: var(--or-asset-tree-header-text-color, var(--or-app-color7, ${unsafeCSS(DefaultColor1)}));+ --internal-or-asset-tree-header-menu-background-color: var(--or-asset-tree-header-menu-background-color, var(--internal-or-asset-tree-header-text-color));+ --internal-or-asset-tree-header-menu-text-color: var(--or-asset-tree-header-menu-text-color, inherit);+ --internal-or-asset-tree-header-height: var(--or-asset-tree-header-height, 48px);+ --internal-or-asset-tree-background-color: var(--or-asset-tree-background-color, var(--or-app-color1, ${unsafeCSS(DefaultColor1)}));+ --internal-or-asset-tree-text-color: var(--or-asset-tree-text-color, inherit);+ --internal-or-asset-tree-item-height: var(--or-asset-tree-item-height, 24px);+ --internal-or-asset-tree-item-padding: var(--or-asset-tree-item-padding, 10px);+ --internal-or-asset-tree-selected-background-color: var(--or-asset-tree-selected-background-color, var(--or-app-color2, ${unsafeCSS(DefaultColor2)}));+ --internal-or-asset-tree-selected-color: var(--or-asset-tree-selected-color, var(--or-app-color4, ${unsafeCSS(DefaultColor4)}));+ --internal-or-asset-tree-button-color: var(--or-asset-tree-button-color, var(--or-app-color4, ${unsafeCSS(DefaultColor4)}));+ --internal-or-asset-tree-line-color: var(--or-asset-tree-line-color, var(--or-app-color5, ${unsafeCSS(DefaultColor5)}));++ display: flex;+ flex-direction: column;+ height: 100%;+ width: 100%;+ background-color: var(--internal-or-asset-tree-background-color);+ }++ @media only screen and (max-width: 640px){+ .hideMobile {+ display: none !important;+ }+ }+ @media only screen and (min-width: 641px){+ .showMobile {+ display: none !important;+ }+ }++ #content {+ display: table-row;+ }+ #container {+ display: flex;+ width: 100%;+ height: 100%;+ }++ #menu-header {+ background-color: var(--internal-or-asset-tree-header-color);+ display: flex;+ align-items: center;+ width: 100%;+ height: var(--internal-or-asset-tree-header-height);+ border-bottom: 1px solid ${unsafeCSS(DefaultColor5)};+ z-index: 3;+ line-height: var(--internal-or-asset-tree-header-height);+ color: var(--internal-or-asset-tree-header-text-color);+ --or-icon-fill: var(--internal-or-asset-tree-header-text-color);+ }++ #title-container {+ flex: 1;+ flex-direction: row;+ text-transform: capitalize;+ padding-left: 14px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ #title {+ font-weight: 500;+ font-size: 16px;+ }++ .expandableHeader {+ display: flex;+ align-items: center;+ padding: 12px;+ background: none;+ border-top: 1px solid ${unsafeCSS(DefaultColor5)};+ border-right: none;+ border-bottom: none;+ border-left: none;+ border-radius: 0;+ width: 100%;+ cursor: pointer;+ }+ .panel-title {+ text-transform: uppercase;+ font-weight: bolder;+ line-height: 1em;+ color: var(--internal-or-asset-viewer-title-text-color);+ /*margin-bottom: 20px;*/+ flex: 0 0 auto;+ }+`diff --git a/ui/component/or-dashboard-builder/src/widgets/or-base-widget.ts b/ui/component/or-dashboard-builder/src/widgets/or-base-widget.tsnew file mode 100644index 000000000..7e5fcb52f--- /dev/null+++ b/ui/component/or-dashboard-builder/src/widgets/or-base-widget.ts@@ -0,0 +1,19 @@+import {DashboardWidget} from "@openremote/model";+import {TemplateResult} from "lit";++export interface OrWidgetConfig {++}++export interface OrWidgetEntity {+ DISPLAY_NAME: string,+ DISPLAY_MDI_ICON: string; // https://materialdesignicons.com;+ MIN_COLUMN_WIDTH: number;+ MIN_PIXEL_WIDTH: number;+ MIN_PIXEL_HEIGHT: number;++ getDefaultConfig: (widget: DashboardWidget) => OrWidgetConfig;++ getWidgetHTML: (widget: DashboardWidget, editMode: boolean, realm: string) => TemplateResult;+ getSettingsHTML: (widget: DashboardWidget, realm: string) => TemplateResult;+}diff --git a/ui/component/or-dashboard-builder/src/widgets/or-chart-widget.ts b/ui/component/or-dashboard-builder/src/widgets/or-chart-widget.tsnew file mode 100644index 000000000..7fda6421b--- /dev/null+++ b/ui/component/or-dashboard-builder/src/widgets/or-chart-widget.ts@@ -0,0 +1,281 @@+import {Asset, Attribute, AttributeRef, DashboardWidget} from "@openremote/model";+import { InputType, OrInputChangedEvent } from "@openremote/or-mwc-components/or-mwc-input";+import {i18next} from "@openremote/or-translate";+import {html, LitElement, TemplateResult} from "lit";+import {customElement, property, state} from "lit/decorators.js";+import {OrWidgetConfig, OrWidgetEntity} from "./or-base-widget";+import {SettingsPanelType, widgetSettingsStyling} from "../or-dashboard-settingspanel";+import {style} from "../style";+import manager from "@openremote/core";+import { showSnackbar } from "@openremote/or-mwc-components/or-mwc-snackbar";+++export interface ChartWidgetConfig extends OrWidgetConfig {+ displayName: string;+ attributeRefs: AttributeRef[];+ period?: 'year' | 'month' | 'week' | 'day' | 'hour' | 'minute' | 'second';+ timestamp?: Date;+ compareTimestamp?: Date;+ showTimestampControls: boolean;+ showLegend: boolean;+}+++export class OrChartWidget implements OrWidgetEntity {++ // Properties+ readonly DISPLAY_NAME: string = "Line Chart";+ readonly DISPLAY_MDI_ICON: string = "chart-bell-curve-cumulative"; // https://materialdesignicons.com;+ readonly MIN_COLUMN_WIDTH: number = 2;+ readonly MIN_PIXEL_WIDTH: number = 0;+ readonly MIN_PIXEL_HEIGHT: number = 0;++ getDefaultConfig(widget: DashboardWidget): ChartWidgetConfig {+ return {+ displayName: widget?.displayName,+ attributeRefs: [],+ period: "day",+ timestamp: new Date(),+ showTimestampControls: false,+ showLegend: true+ } as ChartWidgetConfig;+ }++ getWidgetHTML(widget: DashboardWidget, editMode: boolean, realm: string): TemplateResult {+ return html`<or-chart-widget .widget="${widget}" .editMode="${editMode}" .realm="${realm}" style="overflow: auto; height: 100%;"></or-chart-widget>`;+ }++ getSettingsHTML(widget: DashboardWidget, realm: string): TemplateResult {+ return html`<or-chart-widgetsettings .widget="${widget}" .realm="${realm}"></or-chart-widgetsettings>`;+ }++}+++++@customElement('or-chart-widget')+export class OrChartWidgetContent extends LitElement {++ @property()+ public readonly widget?: DashboardWidget;++ @property()+ public editMode?: boolean;++ @property()+ public realm?: string;++ @state()+ private assets: Asset[] = [];++ @state()+ private assetAttributes: [number, Attribute<any>][] = [];++ /* ---------- */++ render() {+ return html`+ <or-chart .assets="${this.assets}" .assetAttributes="${this.assetAttributes}" .period="${this.widget?.widgetConfig?.period}" denseLegend="${true}"+ .showLegend="${(this.widget?.widgetConfig?.showLegend != null) ? this.widget?.widgetConfig?.showLegend : true}" .realm="${this.realm}"+ .attributeControls="${false}" .timestampControls="${this.widget?.widgetConfig?.showTimestampControls}"+ .compareTimestamp="${false}" style="height: 100%"+ ></or-chart>+ `+ }++ updated(changedProperties: Map<string, any>) {+ if(changedProperties.has("widget") || changedProperties.has("editMode")) {+ if(this.assetAttributes.length != this.widget!.widgetConfig.attributeRefs.length) {+ this.fetchAssets(this.widget?.widgetConfig).then((assets) => {+ this.assets = assets!;+ this.assetAttributes = this.widget?.widgetConfig.attributeRefs.map((attrRef: AttributeRef) => {+ const assetIndex = assets!.findIndex((asset) => asset.id === attrRef.id);+ const foundAsset = assetIndex >= 0 ? assets![assetIndex] : undefined;+ return foundAsset && foundAsset.attributes ? [assetIndex, foundAsset.attributes[attrRef.name!]] : undefined;+ }).filter((indexAndAttr: any) => !!indexAndAttr) as [number, Attribute<any>][];+ });+ }+ }+ }++ // Fetching the assets according to the AttributeRef[] input in DashboardWidget if required. TODO: Simplify this to only request data needed for attribute list+ async fetchAssets(config: OrWidgetConfig | any): Promise<Asset[] | undefined> {+ if(config.attributeRefs && config.attributeRefs.length > 0) {+ let assets: Asset[] = [];+ await manager.rest.api.AssetResource.queryAssets({+ ids: config.attributeRefs?.map((x: AttributeRef) => x.id) as string[],+ select: {+ attributes: config.attributeRefs?.map((x: AttributeRef) => x.name) as string[]+ }+ }).then(response => {+ assets = response.data;+ }).catch((reason) => {+ console.error(reason);+ showSnackbar(undefined, i18next.t('errorOccurred'));+ });+ return assets;+ } else if(!config.attributeRefs) {+ console.error("Error: attributeRefs are not present in widget config!");+ }+ }+++ /* --------------------------- */++ // Caching and generation of mockData, to prevent API call to be made.+ // Is currently not used anymore, but can be used with the dataProvider on or-chart.++ @state()+ private cachedMockData?: Map<string, { period: any, data: any[] }> = new Map<string, { period: any, data: any[] }>();++ generateMockData(widget: DashboardWidget, startOfPeriod: number, _endOfPeriod: number, amount: number = 10) {+ const mockTime: number = startOfPeriod;+ const chartData: any[] = [];+ const interval = (Date.now() - startOfPeriod) / amount;++ // Generating random coordinates on the chart+ let data: any[] = [];+ const cached: { period: any, data: any[] } | undefined = this.cachedMockData?.get(widget.id!);+ if(cached && (cached.data.length == widget.widgetConfig?.attributeRefs?.length) && (cached.period == widget.widgetConfig?.period)) {+ data = this.cachedMockData?.get(widget.id!)!.data!;+ } else {+ widget.widgetConfig?.attributeRefs?.forEach((_attrRef: AttributeRef) => {+ let valueEntries: any[] = [];+ let prevValue: number = 100;+ for(let i = 0; i < amount; i++) {+ const value = Math.floor(Math.random() * ((prevValue + 2) - (prevValue - 2)) + (prevValue - 2))+ valueEntries.push({+ x: (mockTime + (i * interval)),+ y: value+ });+ prevValue = value;+ }+ data.push(valueEntries);+ });+ this.cachedMockData?.set(widget.id!, { period: widget.widgetConfig?.period, data: data });+ }++ // Making a line for each attribute+ widget.widgetConfig?.attributeRefs?.forEach((attrRef: AttributeRef) => {+ chartData.push({+ backgroundColor: ["#3869B1", "#DA7E30", "#3F9852", "#CC2428", "#6B4C9A", "#922427", "#958C3D", "#535055"][chartData.length],+ borderColor: ["#3869B1", "#DA7E30", "#3F9852", "#CC2428", "#6B4C9A", "#922427", "#958C3D", "#535055"][chartData.length],+ data: data[chartData.length],+ fill: false,+ label: attrRef.name,+ pointRadius: 2+ });+ });+ return chartData;+ }+}++++++++@customElement("or-chart-widgetsettings")+class OrChartWidgetSettings extends LitElement {++ @property()+ public widget?: DashboardWidget;++ // Default values+ private expandedPanels: string[] = [i18next.t('attributes'), i18next.t('display')];+++ static get styles() {+ return [style, widgetSettingsStyling];+ }++ // UI Rendering+ render() {+ const config = JSON.parse(JSON.stringify(this.widget!.widgetConfig)) as ChartWidgetConfig; // duplicate to edit, to prevent parent updates. Please trigger updateConfig()+ return html`+ <div>+ ${this.generateExpandableHeader(i18next.t('attributes'))}+ </div>+ <div>+ ${this.expandedPanels.includes(i18next.t('attributes')) ? html`+ <or-dashboard-settingspanel .type="${SettingsPanelType.MULTI_ATTRIBUTE}" .widgetConfig="${this.widget?.widgetConfig}"+ @updated="${(event: CustomEvent) => { this.updateConfig(this.widget!, event.detail.changes.get('config')) }}"+ ></or-dashboard-settingspanel>+ ` : null}+ </div>+ <div>+ ${this.generateExpandableHeader(i18next.t('display'))}+ </div>+ <div>+ ${this.expandedPanels.includes(i18next.t('display')) ? html`+ <div style="padding: 24px 24px 48px 24px;">+ <div>+ <or-mwc-input .type="${InputType.SELECT}" style="width: 100%;"+ .options="${['year', 'month', 'week', 'day', 'hour', 'minute', 'second']}"+ .value="${config.period}" label="${i18next.t('timeframe')}"+ @or-mwc-input-changed="${(event: OrInputChangedEvent) => {+ config.period = event.detail.value;+ this.updateConfig(this.widget!, config);+ }}"+ ></or-mwc-input>+ </div>+ <div class="switchMwcInputContainer" style="margin-top: 18px;">+ <span>${i18next.t('dashboard.showTimestampControls')}</span>+ <or-mwc-input .type="${InputType.SWITCH}" style="width: 70px;"+ .value="${config.showTimestampControls}"+ @or-mwc-input-changed="${(event: OrInputChangedEvent) => {+ config.showTimestampControls = event.detail.value;+ this.updateConfig(this.widget!, config);+ }}"+ ></or-mwc-input>+ </div>+ <div class="switchMwcInputContainer">+ <span>${i18next.t('dashboard.showLegend')}</span>+ <or-mwc-input .type="${InputType.SWITCH}" style="width: 70px;"+ .value="${config.showLegend}"+ @or-mwc-input-changed="${(event: OrInputChangedEvent) => {+ config.showLegend = event.detail.value;+ this.updateConfig(this.widget!, config);+ }}"+ ></or-mwc-input>+ </div>+ </div>+ ` : null}+ </div>+ `+ }++ updateConfig(widget: DashboardWidget, config: OrWidgetConfig | any, force: boolean = false) {+ const oldWidget = JSON.parse(JSON.stringify(widget)) as DashboardWidget;+ widget.widgetConfig = config;+ this.requestUpdate("widget", oldWidget);+ this.forceParentUpdate(new Map<string, any>([["widget", widget]]), force);+ }++ // Method to update the Grid. For example after changing a setting.+ forceParentUpdate(changes: Map<string, any>, force: boolean = false) {+ this.dispatchEvent(new CustomEvent('updated', {detail: {changes: changes, force: force}}));+ }++ generateExpandableHeader(name: string): TemplateResult {+ return html`+ <span class="expandableHeader panel-title" @click="${() => { this.expandPanel(name); }}">+ <or-icon icon="${this.expandedPanels.includes(name) ? 'chevron-down' : 'chevron-right'}"></or-icon>+ <span style="margin-left: 6px; height: 25px; line-height: 25px;">${name}</span>+ </span>+ `+ }+ expandPanel(panelName: string): void {+ if (this.expandedPanels.includes(panelName)) {+ const indexOf = this.expandedPanels.indexOf(panelName, 0);+ if (indexOf > -1) {+ this.expandedPanels.splice(indexOf, 1);+ }+ } else {+ this.expandedPanels.push(panelName);+ }+ this.requestUpdate();+ }+}diff --git a/ui/component/or-dashboard-builder/src/widgets/or-gauge-widget.ts b/ui/component/or-dashboard-builder/src/widgets/or-gauge-widget.tsnew file mode 100644index 000000000..48c973aac--- /dev/null+++ b/ui/component/or-dashboard-builder/src/widgets/or-gauge-widget.ts@@ -0,0 +1,245 @@+import {OrWidgetConfig, OrWidgetEntity} from "./or-base-widget";+import {style} from "../style";+import {SettingsPanelType, widgetSettingsStyling} from "../or-dashboard-settingspanel";+import {Asset, Attribute, AttributeRef, DashboardWidget } from "@openremote/model";+import { html, LitElement, TemplateResult } from "lit";+import { customElement, property, state } from "lit/decorators.js";+import "@openremote/or-gauge";+import { i18next } from "@openremote/or-translate";+import manager from "@openremote/core";+import { showSnackbar } from "@openremote/or-mwc-components/or-mwc-snackbar";+import {InputType} from "@openremote/or-mwc-components/or-mwc-input";+import { when } from "lit/directives/when.js";++export interface GaugeWidgetConfig extends OrWidgetConfig {+ displayName: string;+ attributeRefs: AttributeRef[];+ thresholds: [number, string][];+ deltaFormat: "absolute" | "percentage";+ min: number,+ max: number+}++export class OrGaugeWidget implements OrWidgetEntity {++ readonly DISPLAY_MDI_ICON: string = "gauge";+ readonly DISPLAY_NAME: string = "Gauge";+ readonly MIN_COLUMN_WIDTH: number = 2;+ readonly MIN_PIXEL_HEIGHT: number = 0;+ readonly MIN_PIXEL_WIDTH: number = 0;++ getDefaultConfig(widget: DashboardWidget): OrWidgetConfig {+ return {+ displayName: widget.displayName,+ attributeRefs: [],+ thresholds: [[0, "#4caf50"],[75, "#ff9800"],[90, "#ef5350"]], // colors from https://mui.com/material-ui/customization/palette/ as reference (since material has no official colors)+ deltaFormat: "absolute",+ min: 0,+ max: 100+ } as GaugeWidgetConfig;+ }+ getWidgetHTML(widget: DashboardWidget, editMode: boolean, realm: string) {+ return html`<or-gauge-widget .widget="${widget}" .editMode="${editMode}" realm="${realm}" style="height: 100%; overflow: hidden;"></or-gauge-widget>`;+ }++ getSettingsHTML(widget: DashboardWidget, realm: string) {+ return html`<or-gauge-widgetsettings .widget="${widget}" realm="${realm}"></or-gauge-widgetsettings>`;+ }++}++@customElement("or-gauge-widget")+export class OrGaugeWidgetContent extends LitElement {++ @property()+ public readonly widget?: DashboardWidget;++ @property()+ public editMode?: boolean;++ @property()+ public realm?: string;++ @state()+ private assets: Asset[] = [];++ @state()+ private assetAttributes: [number, Attribute<any>][] = [];+++ render() {+ return html`+ ${when(this.assets && this.assetAttributes && this.assets.length > 0 && this.assetAttributes.length > 0, () => {+ return html`+ <or-gauge .asset="${this.assets[0]}" .assetAttribute="${this.assetAttributes[0]}" .thresholds="${this.widget?.widgetConfig.thresholds}"+ .min="${this.widget?.widgetConfig.min}" .max="${this.widget?.widgetConfig.max}"+ style="height: 100%;"></or-gauge>+ `;+ }, () => {+ return html`+ <span>No attributes selected.</span>+ `+ })}+ <!--<or-gauge .attrRef="${this.widget?.widgetConfig.attributeRefs[0]}"></or-gauge>-->+ `+ }++ updated(changedProperties: Map<string, any>) {+ if(changedProperties.has("widget") || changedProperties.has("editMode")) {+ this.fetchAssets(this.widget?.widgetConfig).then((assets) => {+ this.assets = assets!;+ this.assetAttributes = this.widget?.widgetConfig.attributeRefs.map((attrRef: AttributeRef) => {+ const assetIndex = assets!.findIndex((asset) => asset.id === attrRef.id);+ const foundAsset = assetIndex >= 0 ? assets![assetIndex] : undefined;+ return foundAsset && foundAsset.attributes ? [assetIndex, foundAsset.attributes[attrRef.name!]] : undefined;+ }).filter((indexAndAttr: any) => !!indexAndAttr) as [number, Attribute<any>][];+ this.requestUpdate();+ });+ }+ }++ // Fetching the assets according to the AttributeRef[] input in DashboardWidget if required. TODO: Simplify this to only request data needed for attribute list+ async fetchAssets(config: OrWidgetConfig | any): Promise<Asset[] | undefined> {+ if(config.attributeRefs && config.attributeRefs.length > 0) {+ let assets: Asset[] = [];+ await manager.rest.api.AssetResource.queryAssets({+ ids: config.attributeRefs?.map((x: AttributeRef) => x.id) as string[],+ select: {+ attributes: config.attributeRefs?.map((x: AttributeRef) => x.name) as string[]+ }+ }).then(response => {+ assets = response.data;+ }).catch((reason) => {+ console.error(reason);+ showSnackbar(undefined, i18next.t('errorOccurred'));+ });+ return assets;+ } else {+ console.error("Error: attributeRefs are not present in widget config!");+ }+ }+}++++@customElement("or-gauge-widgetsettings")+export class OrGaugeWidgetSettings extends LitElement {++ @property()+ public readonly widget?: DashboardWidget;++ // Default values+ private expandedPanels: string[] = [i18next.t('attributes'), i18next.t('values'), i18next.t('thresholds')];+ private loadedAsset?: Asset;++ static get styles() {+ return [style, widgetSettingsStyling];+ }++ // UI Rendering+ render() {+ const config = JSON.parse(JSON.stringify(this.widget!.widgetConfig)) as GaugeWidgetConfig; // duplicate to edit, to prevent parent updates. Please trigger updateConfig()+ return html`+ <div>+ ${this.generateExpandableHeader(i18next.t('attributes'))}+ </div>+ <div>+ ${this.expandedPanels.includes(i18next.t('attributes')) ? html`+ <or-dashboard-settingspanel .type="${SettingsPanelType.SINGLE_ATTRIBUTE}" .onlyDataAttrs="${false}" .widgetConfig="${this.widget?.widgetConfig}"+ @updated="${(event: CustomEvent) => {+ this.updateConfig(this.widget!, event.detail.changes.get('config'));+ this.onAttributesUpdate(event.detail.changes);+ }}"+ ></or-dashboard-settingspanel>+ ` : null}+ </div>+ <div>+ ${this.generateExpandableHeader(i18next.t('values'))}+ </div>+ <div>+ ${this.expandedPanels.includes(i18next.t('values')) ? html`+ <div style="padding: 12px 24px 48px 24px; display: flex; flex-direction: column; gap: 16px;">+ <div style="display: flex; gap: 8px;">+ <or-mwc-input type="${InputType.NUMBER}" label="${i18next.t('min')}" .max="${this.widget?.widgetConfig.max}" .value="${this.widget?.widgetConfig.min}"+ @or-mwc-input-changed="${(event: CustomEvent) => {+ if(event.detail.value < this.widget?.widgetConfig.max) {+ config.min = event.detail.value;+ if(config.thresholds[1][0] > event.detail.value) {+ config.thresholds[0][0] = event.detail.value;+ }+ this.updateConfig(this.widget!, config);+ }+ }}"+ ></or-mwc-input>+ <or-mwc-input type="${InputType.NUMBER}" label="${i18next.t('max')}" .min="${this.widget?.widgetConfig.min}" .value="${this.widget?.widgetConfig.max}"+ @or-mwc-input-changed="${(event: CustomEvent) => {+ if(event.detail.value > this.widget?.widgetConfig.min) {+ config.max = event.detail.value;+ this.updateConfig(this.widget!, config);+ }+ }}"+ ></or-mwc-input>+ </div>+ </div>+ ` : null}+ </div>+ <div>+ ${this.generateExpandableHeader(i18next.t('thresholds'))}+ </div>+ <div>+ ${this.expandedPanels.includes(i18next.t('thresholds')) ? html`+ <or-dashboard-settingspanel .type="${SettingsPanelType.THRESHOLDS}" .widgetConfig="${this.widget?.widgetConfig}"+ @updated="${(event: CustomEvent) => { this.updateConfig(this.widget!, event.detail.changes.get('config')); }}">+ </or-dashboard-settingspanel>+ ` : null}+ </div>+ `+ }++ updateConfig(widget: DashboardWidget, config: OrWidgetConfig | any, force: boolean = false) {+ const oldWidget = JSON.parse(JSON.stringify(widget)) as DashboardWidget;+ widget.widgetConfig = config;+ this.requestUpdate("widget", oldWidget);+ this.forceParentUpdate(new Map<string, any>([["widget", widget]]), force);+ }+++ /* ------------------------------ */++ onAttributesUpdate(changes: Map<string, any>) {+ if(changes.has('loadedAssets')) {+ this.loadedAsset = changes.get('loadedAssets')[0];+ }+ if(changes.has('config')) {+ const config = changes.get('config') as GaugeWidgetConfig;+ if(config.attributeRefs.length > 0) {+ this.widget!.displayName = this.loadedAsset?.name + " - " + this.loadedAsset?.attributes![config.attributeRefs[0].name!].name;+ }+ }+ }++ // Method to update the Grid. For example after changing a setting.+ forceParentUpdate(changes: Map<string, any>, force: boolean = false) {+ this.dispatchEvent(new CustomEvent('updated', {detail: {changes: changes, force: force}}));+ }++ generateExpandableHeader(name: string): TemplateResult {+ return html`+ <span class="expandableHeader panel-title" @click="${() => { this.expandPanel(name); }}">+ <or-icon icon="${this.expandedPanels.includes(name) ? 'chevron-down' : 'chevron-right'}"></or-icon>+ <span style="margin-left: 6px; height: 25px; line-height: 25px;">${name}</span>+ </span>+ `+ }+ expandPanel(panelName: string): void {+ if (this.expandedPanels.includes(panelName)) {+ const indexOf = this.expandedPanels.indexOf(panelName, 0);+ if (indexOf > -1) {+ this.expandedPanels.splice(indexOf, 1);+ }+ } else {+ this.expandedPanels.push(panelName);+ }+ this.requestUpdate();+ }+}diff --git a/ui/component/or-dashboard-builder/src/widgets/or-kpi-widget.ts b/ui/component/or-dashboard-builder/src/widgets/or-kpi-widget.tsnew file mode 100644index 000000000..1c1b89931--- /dev/null+++ b/ui/component/or-dashboard-builder/src/widgets/or-kpi-widget.ts@@ -0,0 +1,237 @@+import manager from "@openremote/core";+import {Asset, Attribute, AttributeRef, DashboardWidget } from "@openremote/model";+import { showSnackbar } from "@openremote/or-mwc-components/or-mwc-snackbar";+import { i18next } from "@openremote/or-translate";+import { html, LitElement, TemplateResult } from "lit";+import { customElement, property, state } from "lit/decorators.js";+import {OrWidgetConfig, OrWidgetEntity} from "./or-base-widget";+import {style} from "../style";+import {SettingsPanelType, widgetSettingsStyling} from "../or-dashboard-settingspanel";+import {InputType, OrInputChangedEvent } from "@openremote/or-mwc-components/or-mwc-input";++export interface KpiWidgetConfig extends OrWidgetConfig {+ displayName: string;+ attributeRefs: AttributeRef[];+ period?: 'year' | 'month' | 'week' | 'day' | 'hour' | 'minute' | 'second';+ decimals: number;+ deltaFormat: "absolute" | "percentage";+}++export class OrKpiWidget implements OrWidgetEntity {++ readonly DISPLAY_MDI_ICON: string = "label";+ readonly DISPLAY_NAME: string = "KPI";+ readonly MIN_COLUMN_WIDTH: number = 2;+ readonly MIN_PIXEL_HEIGHT: number = 0;+ readonly MIN_PIXEL_WIDTH: number = 0;++ getDefaultConfig(widget: DashboardWidget): OrWidgetConfig {+ return {+ displayName: widget.displayName,+ attributeRefs: [],+ period: "day",+ decimals: 0,+ deltaFormat: "absolute",+ showTimestampControls: false+ } as KpiWidgetConfig;+ }++ getSettingsHTML(widget: DashboardWidget, realm: string) {+ return html`<or-kpi-widgetsettings .widget="${widget}" realm="${realm}"></or-kpi-widgetsettings>`;+ }++ getWidgetHTML(widget: DashboardWidget, editMode: boolean, realm: string) {+ return html`<or-kpi-widget .widget="${widget}" .editMode="${editMode}" realm="${realm}" style="height: 100%; overflow: hidden;"></or-kpi-widget>`;+ }++}++@customElement("or-kpi-widget")+export class OrKpiWidgetContent extends LitElement {++ @property()+ public readonly widget?: DashboardWidget;++ @property()+ public editMode?: boolean;++ @property()+ public realm?: string;++ @state()+ private loadedAssets: Asset[] = [];++ @state()+ private assetAttributes: [number, Attribute<any>][] = [];++ render() {+ return html`+ <or-attribute-card .assets="${this.loadedAssets}" .assetAttributes="${this.assetAttributes}" .period="${this.widget?.widgetConfig.period}"+ .deltaFormat="${this.widget?.widgetConfig.deltaFormat}" .mainValueDecimals="${this.widget?.widgetConfig.decimals}"+ showControls="${false}" showTitle="${false}" realm="${this.realm}" style="height: 100%;">+ </or-attribute-card>+ `+ }++ updated(changedProperties: Map<string, any>) {+ if(changedProperties.has("widget") || changedProperties.has("editMode")) {+ this.fetchAssets(this.widget?.widgetConfig).then((assets) => {+ this.loadedAssets = (assets ? assets : []);+ this.assetAttributes = this.widget?.widgetConfig.attributeRefs.map((attrRef: AttributeRef) => {+ const assetIndex = assets!.findIndex((asset) => asset.id === attrRef.id);+ const foundAsset = assetIndex >= 0 ? assets![assetIndex] : undefined;+ return foundAsset && foundAsset.attributes ? [assetIndex, foundAsset.attributes[attrRef.name!]] : undefined;+ }).filter((indexAndAttr: any) => !!indexAndAttr) as [number, Attribute<any>][];+ this.requestUpdate();+ });+ }+ }++ // Fetching the assets according to the AttributeRef[] input in DashboardWidget if required. TODO: Simplify this to only request data needed for attribute list+ async fetchAssets(config: OrWidgetConfig | any): Promise<Asset[] | undefined> {+ if(config.attributeRefs && config.attributeRefs.length > 0) {+ let assets: Asset[] = [];+ await manager.rest.api.AssetResource.queryAssets({+ ids: config.attributeRefs?.map((x: AttributeRef) => x.id) as string[],+ select: {+ attributes: config.attributeRefs?.map((x: AttributeRef) => x.name) as string[]+ }+ }).then(response => {+ assets = response.data;+ }).catch((reason) => {+ console.error(reason);+ showSnackbar(undefined, i18next.t('errorOccurred'));+ });+ return assets;+ } else {+ console.error("Error: attributeRefs are not present in widget config!");+ }+ }+}++++@customElement("or-kpi-widgetsettings")+export class OrKpiWidgetSettings extends LitElement {++ @property()+ public readonly widget?: DashboardWidget;++ // Default values+ private expandedPanels: string[] = [i18next.t('attributes'), i18next.t('display'), i18next.t('values')];+ private loadedAsset?: Asset;+++ static get styles() {+ return [style, widgetSettingsStyling];+ }++ // UI Rendering+ render() {+ const config = JSON.parse(JSON.stringify(this.widget!.widgetConfig)) as KpiWidgetConfig; // duplicate to edit, to prevent parent updates. Please trigger updateConfig()+ return html`+ <div>+ ${this.generateExpandableHeader(i18next.t('attributes'))}+ </div>+ <div>+ ${this.expandedPanels.includes(i18next.t('attributes')) ? html`+ <or-dashboard-settingspanel .type="${SettingsPanelType.SINGLE_ATTRIBUTE}" .widgetConfig="${this.widget!.widgetConfig}"+ @updated="${(event: CustomEvent) => {+ this.onAttributesUpdate(event.detail.changes);+ this.updateConfig(this.widget!, event.detail.changes.get('config'));+ }}"+ ></or-dashboard-settingspanel>+ ` : null}+ </div>+ <div>+ ${this.generateExpandableHeader(i18next.t('display'))}+ </div>+ <div>+ ${this.expandedPanels.includes(i18next.t('display')) ? html`+ <div style="padding: 24px 24px 48px 24px;">+ <div>+ <or-mwc-input .type="${InputType.SELECT}" style="width: 100%;"+ .options="${['year', 'month', 'week', 'day', 'hour', 'minute', 'second']}"+ .value="${config.period}" label="${i18next.t('timeframe')}"+ @or-mwc-input-changed="${(event: OrInputChangedEvent) => {+ config.period = event.detail.value;+ this.updateConfig(this.widget!, config);+ }}"+ ></or-mwc-input>+ </div>+ </div>+ ` : null}+ </div>+ <div>+ ${this.generateExpandableHeader(i18next.t('values'))}+ </div>+ <div>+ ${this.expandedPanels.includes(i18next.t('values')) ? html`+ <div style="padding: 24px 24px 48px 24px;">+ <div>+ <or-mwc-input .type="${InputType.SELECT}" style="width: 100%;" .options="${['absolute', 'percentage']}" .value="${config.deltaFormat}" label="${i18next.t('dashboard.showValueAs')}"+ @or-mwc-input-changed="${(event: OrInputChangedEvent) => {+ config.deltaFormat = event.detail.value;+ this.updateConfig(this.widget!, config);+ }}"+ ></or-mwc-input>+ </div>+ <div style="margin-top: 18px;">+ <or-mwc-input .type="${InputType.NUMBER}" style="width: 100%;" .value="${config.decimals}" label="${i18next.t('decimals')}"+ @or-mwc-input-changed="${(event: OrInputChangedEvent) => {+ config.decimals = event.detail.value;+ this.updateConfig(this.widget!, config);+ }}"+ ></or-mwc-input>+ </div>+ </div>+ ` : null}+ </div>+ `+ }++ updateConfig(widget: DashboardWidget, config: OrWidgetConfig | any, force: boolean = false) {+ const oldWidget = JSON.parse(JSON.stringify(widget)) as DashboardWidget;+ widget.widgetConfig = config;+ this.requestUpdate("widget", oldWidget);+ this.forceParentUpdate(new Map<string, any>([["widget", widget]]), force);+ }++ onAttributesUpdate(changes: Map<string, any>) {+ if(changes.has('loadedAssets')) {+ this.loadedAsset = changes.get('loadedAssets')[0];+ }+ if(changes.has('config')) {+ const config = changes.get('config') as KpiWidgetConfig;+ if(config.attributeRefs.length > 0) {+ this.widget!.displayName = this.loadedAsset?.name + " - " + this.loadedAsset?.attributes![config.attributeRefs[0].name!].name;+ }+ }+ }++ // Method to update the Grid. For example after changing a setting.+ forceParentUpdate(changes: Map<string, any>, force: boolean = false) {+ this.requestUpdate();+ this.dispatchEvent(new CustomEvent('updated', {detail: {changes: changes, force: force}}));+ }++ generateExpandableHeader(name: string): TemplateResult {+ return html`+ <span class="expandableHeader panel-title" @click="${() => { this.expandPanel(name); }}">+ <or-icon icon="${this.expandedPanels.includes(name) ? 'chevron-down' : 'chevron-right'}"></or-icon>+ <span style="margin-left: 6px; height: 25px; line-height: 25px;">${name}</span>+ </span>+ `+ }+ expandPanel(panelName: string): void {+ if (this.expandedPanels.includes(panelName)) {+ const indexOf = this.expandedPanels.indexOf(panelName, 0);+ if (indexOf > -1) {+ this.expandedPanels.splice(indexOf, 1);+ }+ } else {+ this.expandedPanels.push(panelName);+ }+ this.requestUpdate();+ }+}diff --git a/ui/component/or-dashboard-builder/tsconfig.json b/ui/component/or-dashboard-builder/tsconfig.jsonnew file mode 100644index 000000000..c5261c716--- /dev/null+++ b/ui/component/or-dashboard-builder/tsconfig.json@@ -0,0 +1,15 @@+{+ "extends": "../../tsconfig",+ "compilerOptions": {+ "outDir": "./lib",+ "rootDir": "src"+ },+ "include": [+ "./src"+ ],+ "references": [+ { "path": "../core" },+ { "path": "../rest" },+ { "path": "../model" }+ ]+}diff --git a/ui/component/or-dashboard-builder/webpack.config.js b/ui/component/or-dashboard-builder/webpack.config.jsnew file mode 100644index 000000000..2a1cf705d--- /dev/null+++ b/ui/component/or-dashboard-builder/webpack.config.js@@ -0,0 +1,10 @@+const util = require("@openremote/util");++var bundles = {+ "index": {+ excludeOr: true+ },+ "index.orbundle": undefined+};++module.exports = util.generateExports(__dirname);diff --git a/ui/component/or-gauge/.npmignore b/ui/component/or-gauge/.npmignorenew file mode 100644index 000000000..17e64b1ad--- /dev/null+++ b/ui/component/or-gauge/.npmignore@@ -0,0 +1,8 @@+build/+build.gradle+test/+src/+webpack.config.js+tsconfig.json+dist/*.map+.tsbuildinfo\ No newline at end of filediff --git a/ui/component/or-gauge/@types/gaugeJS.d.ts b/ui/component/or-gauge/@types/gaugeJS.d.tsnew file mode 100644index 000000000..2ff38b12c--- /dev/null+++ b/ui/component/or-gauge/@types/gaugeJS.d.ts@@ -0,0 +1,121 @@+declare module 'gaugeJS' {++ interface PointerOptions {+ length: number;+ strokeWidth: number;+ color: string;+ }+ interface BaseOptions {+ angle: number;+ lineWidth: number;+ radiusScale: number;+ pointer: PointerOptions;+ limitMax: boolean;+ limitMin: boolean;+ colorStart: string;+ colorStop: string;+ strokeColor: string;+ generateGradient: boolean;+ highDpiSupport: boolean;+ }++ interface StaticZoneOptions {+ strokeStyle: string;+ min: number;+ max: number;+ }++ export interface GaugeOptions extends BaseOptions {+ percentColors?: Array<[number, string]> | undefined;+ staticLabels?: {+ font: string;+ labels: number[];+ color?: string | undefined;+ fractionDigits?: number | undefined;+ } | undefined;+ staticZones?: StaticZoneOptions[] | Array<StaticZoneOptions & { height: number; }> | undefined;+ renderTicks?: {+ divisions: number;+ divWidth: number;+ divLength: number;+ divColor: string;+ subDivisions: number;+ subWidth: number;+ subLength: number;+ subColor: string;+ } | undefined;+ pointer: PointerOptions & {+ iconPath?: string | undefined;+ iconScale?: number | undefined;+ iconAngle?: number | undefined;+ };+ }+ export interface TextRendererElement {+ innerHTML: string;+ style: {+ fontSize: string;+ };+ }++ export class TextRenderer {+ constructor(element: TextRendererElement, fractionalDigits: number);++ private render(gauge: Gauge): string;+ }++ export class ValueUpdater {+ /**+ * The animation speed of the gauge pointer (default is 32)+ */+ animationSpeed: number;++ constructor(addToAnimationQueue?: boolean | null, clear?: boolean | null);++ update(force?: boolean | null): boolean;+ }++ export class BaseGauge extends ValueUpdater {+ /**+ * ?+ * @param textField+ */+ setTextField(textField: TextRenderer | TextRendererElement): TextRenderer;++ /**+ * Sets the minimum gauge value (prefer over gauge.minValue)+ * @param minValue+ */+ setMinValue(minValue: number): number[] | undefined;++ /**+ * Configure the gauge renderer with the given options.+ * @param options The configuration options for the gauge.+ */+ setOptions(options?: GaugeOptions | null): this;+ }++ export class Gauge extends BaseGauge {+ /**+ * The max gauge value.+ */+ maxValue: number;++ /**+ * Creates a new gauge renderer for the given canvas element.+ * @param canvas The canvas element to render to.+ */+ constructor(canvas: HTMLCanvasElement);++ /**+ * Configure the gauge renderer with the given options.+ * @param options The configuration options for the gauge.+ */+ setOptions(options?: GaugeOptions | null): this;++ /**+ * Sets the current value of the gauge pointer.+ * @param value+ */+ set(value: number): boolean;+ }+}diff --git a/ui/component/or-gauge/README.md b/ui/component/or-gauge/README.mdnew file mode 100644index 000000000..cfb5c937a--- /dev/null+++ b/ui/component/or-gauge/README.md@@ -0,0 +1,4 @@+or-gauge is a component that is currently in development.<br />+The basics are implemented, but no data support yet.++Documentation coming soon.diff --git a/ui/component/or-gauge/build.gradle b/ui/component/or-gauge/build.gradlenew file mode 100644index 000000000..98cdcb8e2--- /dev/null+++ b/ui/component/or-gauge/build.gradle@@ -0,0 +1,15 @@+buildDir = "dist"++task clean() {+ doLast {+ delete "dist"+ }+}++task prepareUi() {+ dependsOn clean, npmPrepare+}++task publishUi() {+ dependsOn clean, npmPublish+}\ No newline at end of filediff --git a/ui/component/or-gauge/package.json b/ui/component/or-gauge/package.jsonnew file mode 100644index 000000000..bdb7953a1--- /dev/null+++ b/ui/component/or-gauge/package.json@@ -0,0 +1,33 @@+{+ "name": "@openremote/or-gauge",+ "version": "1.1.0",+ "description": "OpenRemote gauge",+ "main": "dist/umd/index.bundle.js",+ "module": "lib/index.js",+ "exports": {+ ".": "./lib/index.js",+ "./*": "./lib/*.js"+ },+ "types": "lib/index.d.ts",+ "scripts": {+ "test": "echo \"No tests\" && exit 0",+ "prepublishOnly": "npx webpack"+ },+ "author": "OpenRemote",+ "license": "AGPL-3.0-or-later",+ "dependencies": {+ "@openremote/core": "workspace:*",+ "@openremote/or-components": "^1.1.0",+ "@openremote/or-icon": "^1.1.0",+ "@openremote/or-mwc-components": "^1.1.0",+ "@openremote/or-translate": "^1.1.0",+ "gaugeJS": "^1.3.7",+ "lit": "^2.0.2"+ },+ "devDependencies": {+ "@openremote/util": "workspace:*"+ },+ "publishConfig": {+ "access": "public"+ }+}diff --git a/ui/component/or-gauge/src/index.ts b/ui/component/or-gauge/src/index.tsnew file mode 100644index 000000000..f77782278--- /dev/null+++ b/ui/component/or-gauge/src/index.ts@@ -0,0 +1,295 @@+import {css, html, LitElement} from "lit";+import {customElement, property, query, state} from "lit/decorators.js";+import {Asset, AssetModelUtil, Attribute, AttributeRef} from "@openremote/model";+import { Gauge, GaugeOptions } from "gaugeJS";+import manager, { Util } from "@openremote/core";+import {i18next} from "@openremote/or-translate";+import {debounce} from "lodash";+import { getAssetDescriptorIconTemplate } from "@openremote/or-icon";++//language=css+const styling = css`+ :host {+ display: flex;+ align-items: center;+ flex-direction: column;+ }++ .chart-wrapper {+ position: relative;+ /*flex: 1;*/+ width: 100%;+ }++ #chart {+ width: 100%;+ }++ .chart-description {+ margin: 0 20px;+ font-size: 16px;+ z-index: 3;+ }+ .mainvalue-wrapper {+ width: 100%;+ display: flex;+ flex: 0 0 60px;+ align-items: center;+ justify-content: center;+ }+ .main-number {+ color: var(--internal-or-asset-viewer-title-text-color);+ font-size: 42px;+ }++ .main-number-icon {+ font-size: 24px;+ margin-right: 10px;+ display: flex;+ }++ .main-number-unit {+ font-size: 42px;+ color: var(--internal-or-asset-viewer-title-text-color);+ font-weight: 200;+ margin-left: 5px;+ }++ .main-number.xs, .main-number-unit.xs {+ font-size: 18px;+ }+ .main-number.s, .main-number-unit.s {+ font-size: 24px;+ }+ .main-number.m, .main-number-unit.m {+ font-size: 30px;+ }+ .main-number.l, .main-number-unit.l {+ font-size: 36px;+ }+ .main-number.xl, .main-number-unit.xl {+ font-size: 42px;+ }+`+export interface OrGaugeConfig {+ attributeRef?: AttributeRef;+ thresholds?: [number, string][]+ options?: GaugeOptions;+}++@customElement("or-gauge")+export class OrGauge extends LitElement {++ static get styles() {+ return [styling]+ }++ @property({type: Object})+ public attrRef?: AttributeRef;++ @property({type: Object})+ public asset?: Asset;++ @property({type: Object})+ public assetAttribute?: [number, Attribute<any>];++ @property()+ public value?: number;++ @property()+ public unit?: string;++ @property()+ public min?: number;++ @property()+ public max?: number;++ @property()+ public thresholds?: [number, string][];++ @property()+ public readonly config?: OrGaugeConfig;++ @property({type: String})+ public realm?: string;++ @property()+ private mainValueSize: "xs" | "s" | "m" | "l" | "xl" = "m";+++ @state()+ protected loading: boolean = false;++ @state()+ private gauge?: Gauge;++ @query("#chart")+ private _gaugeElem!: HTMLCanvasElement;++ private resizeObserver?: ResizeObserver;+++ constructor() {+ super();+ if(!this.config) {+ this.config = this.getDefaultConfig();+ }+ this.updateComplete.then(() => {+ this.resizeObserver = new ResizeObserver(debounce((entries: ResizeObserverEntry[]) => {+ this.setupGauge(); // recreate gauge since the library is not 100% responsive.+ const gaugeSize = entries[0].devicePixelContentBoxSize[0].blockSize; // since gauge elem width == value elem width+ this.setLabelSize(gaugeSize);+ }, 200))+ this.resizeObserver.observe(this.shadowRoot!.getElementById('chart')!);+ })+ }++ updated(changedProperties: Map<string, any>) {+ if(changedProperties.has('value')) {+ this.gauge?.set(this.value ? this.value : NaN);+ }+ if(changedProperties.has('assetAttribute')) {+ const attr = this.assetAttribute![1];+ const attributeDescriptor = AssetModelUtil.getAttributeDescriptor(attr.name!, this.asset!.type!);+ this.unit = Util.resolveUnits(Util.getAttributeUnits(attr, attributeDescriptor, this.asset!.type));+ this.value = attr.value ? attr.value : NaN;+ }+ if(changedProperties.has('attrRef')) {+ if(this.attrRef) {+ this.loadData(this.attrRef);+ } else {+ this.assetAttribute = undefined;+ this.value = undefined;+ }+ }++ // Render gauge again if..+ if(changedProperties.has('min') && this.min) {+ this.gauge?.setMinValue(this.min);+ this.gauge?.set(this.value ? this.value : NaN);+ }+ if(changedProperties.has('max') && this.max && this.gauge) {+ this.gauge.maxValue = this.max;+ this.gauge?.set(this.value ? this.value : NaN);+ }+ if(changedProperties.has('thresholds') && this.thresholds) {++ // Make staticZones out of the thresholds.+ // If below the minimum or above the maximum, set the value according to it.+ this.config!.options!.staticZones = [];+ this.thresholds.sort((x, y) => (x[0] < y[0]) ? -1 : 1).forEach(((threshold, index) => {+ const min = threshold[0];+ const max = (this.thresholds![index + 1] ? this.thresholds![index + 1][0] : this.max);+ const zone = {+ strokeStyle: threshold[1],+ min: ((this.min && min && this.min > min) ? this.min : ((this.max && min && this.max < min) ? this.max : min)),+ max: ((this.max && max && this.max < max) ? this.max : ((this.min && max && this.min > max) ? this.min : max))+ };+ this.config?.options?.staticZones?.push(zone as any);+ }));++ // The lowest staticZone should ALWAYS have the minimum value, to prevent the graphic displaying incorrectly.+ if(this.min && this.config?.options?.staticZones) {+ this.config.options.staticZones[0].min = this.min;+ }++ // Applying the options we changed.+ if(this.gauge) {+ this.gauge.setOptions(this.config?.options);+ }+ }+ }++ setupGauge() {+ this.gauge = new Gauge(this._gaugeElem);+ this.gauge.setOptions(this.config?.options);+ this.gauge.maxValue = (this.max ? this.max : 100)+ this.gauge.setMinValue(this.min ? this.min : 0);+ this.gauge.animationSpeed = 1;+ this.gauge.set(this.value ? this.value : NaN);+ if(!this.value && this.attrRef) {+ this.loadData(this.attrRef);+ }+ }++ setLabelSize(blockSize: number) {+ if(blockSize < 60) {+ this.mainValueSize = "s";+ } else if(blockSize < 100) {+ this.mainValueSize = "m";+ } else if(blockSize < 200) {+ this.mainValueSize = "l"+ } else {+ this.mainValueSize = "xl"+ }+ }++ render() {+ return html`+ <div style="position: relative; height: 100%; width: 100%;">+ <div class="chart-wrapper" style="display: ${this.loading ? 'none' : 'flex'}; flex-direction: column; justify-content: center; height: 100%;">+ <div style="flex: 0 0 0;">+ <canvas id="chart"></canvas>+ </div>+ <div>+ <div class="mainvalue-wrapper">+ <span class="main-number-icon">${this.asset ? getAssetDescriptorIconTemplate(AssetModelUtil.getAssetDescriptor(this.asset.type)) : ""}</span>+ <span class="main-number ${this.mainValueSize}">${this.value ? this.value : NaN}</span>+ <span class="main-number-unit ${this.mainValueSize}">${this.unit ? this.unit : ""}</span>+ </div>+ </div>+ </div>+ </div>+ ${this.loading ? html`+ <span>${i18next.t('loading')}</span>+ ` : undefined}+ `+ }++ async loadData(attrRef: AttributeRef) {+ const response = await manager.rest.api.AssetResource.queryAssets({ ids: [attrRef.id!] });+ const assets = response.data;+ const assetAttributes = [attrRef].map((attrRef) => {+ const assetIndex = assets.findIndex((asset) => asset.id === attrRef.id);+ const asset = assetIndex >= 0 ? assets[assetIndex] : undefined;+ return asset && asset.attributes ? [assetIndex, asset.attributes[attrRef.name!]] : undefined;+ }).filter((indexAndAttr) => !!indexAndAttr) as [number, Attribute<any>][];++ this.asset = assets[0];+ this.assetAttribute = assetAttributes[0];+ }++ getDefaultConfig(): OrGaugeConfig {+ return {+ attributeRef: undefined,+ options: {+ angle: 0,+ lineWidth: 0.4,+ radiusScale: 1,+ pointer: {+ length: 0.5,+ strokeWidth: 0.035,+ color: "#000000",+ },+ staticZones: [],+ limitMax: true,+ limitMin: true,+ colorStart: "#000000",+ colorStop: "#707070",+ strokeColor: "#ABCDEF",+ generateGradient: false,+ highDpiSupport: true+ }+ }+ }++ // Wait until function that waits until a boolean returns differently+ waitUntil(conditionFunction: any) {+ const poll = (resolve: any) => {+ if(conditionFunction()) resolve();+ else setTimeout((_: any) => poll(resolve), 400);+ }+ return new Promise(poll);+ }+}diff --git a/ui/component/or-gauge/tsconfig.json b/ui/component/or-gauge/tsconfig.jsonnew file mode 100644index 000000000..1a4c94179--- /dev/null+++ b/ui/component/or-gauge/tsconfig.json@@ -0,0 +1,19 @@+{+ "extends": "../../tsconfig",+ "compilerOptions": {+ "outDir": "./lib",+ "rootDir": "src",+ "typeRoots": ["./@types"]+ },+ "include": [+ "./src",+ "./@types"+ ],+ "references": [+ { "path": "../core" },+ { "path": "../or-components" },+ { "path": "../or-icon" },+ { "path": "../or-mwc-components" },+ { "path": "../or-translate" }+ ]+}diff --git a/ui/component/or-gauge/webpack.config.js b/ui/component/or-gauge/webpack.config.jsnew file mode 100644index 000000000..cd4bc1144--- /dev/null+++ b/ui/component/or-gauge/webpack.config.js@@ -0,0 +1,13 @@+const util = require("@openremote/util");++bundles = {+ "index": {+ excludeOr: true+ },+ "index.bundle": {+ excludeOr: true,+ },+ "index.orbundle": undefined+};++module.exports = util.generateExports(__dirname);diff --git a/ui/component/or-mwc-components/src/or-mwc-input.ts b/ui/component/or-mwc-components/src/or-mwc-input.tsindex c8fd3d69f..4e55c4457 100644--- a/ui/component/or-mwc-components/src/or-mwc-input.ts+++ b/ui/component/or-mwc-components/src/or-mwc-input.ts@@ -1196,6 +1196,16 @@ export class OrMwcInput extends LitElement {<label class="mdc-checkbox-circle" for="elem">${this.label}</label></div>`;+ case InputType.COLOUR:+ return html`+ <div id="component" style="width: 100%; height: 100%;">+ <input type="color" id="elem" style="border: none; height: 100%; width: 100%; padding: 1px 3px; min-height: 22px; min-width: 30px;" value="${this.value}"+ ?disabled="${this.disabled || this.readonly}"+ ?required="${this.required}"+ @change="${(e: any) => this.onValueChange((e.target as HTMLInputElement), (e.target as HTMLInputElement).value)}"+ />+ </div>+ `case InputType.NUMBER:case InputType.RANGE:case InputType.DATE:@@ -1203,7 +1213,6 @@ export class OrMwcInput extends LitElement {case InputType.TIME:case InputType.MONTH:case InputType.WEEK:- case InputType.COLOUR:case InputType.EMAIL:case InputType.PASSWORD:case InputType.TELEPHONE:@@ -1468,6 +1477,7 @@ export class OrMwcInput extends LitElement {break;case InputType.RADIO:case InputType.CHECKBOX_LIST:+ case InputType.COLOUR:break;case InputType.BUTTON:case InputType.BUTTON_MOMENTARY:diff --git a/ui/component/or-mwc-components/src/or-mwc-tabs.ts b/ui/component/or-mwc-components/src/or-mwc-tabs.tsindex 40731ff4f..3705575c1 100644--- a/ui/component/or-mwc-components/src/or-mwc-tabs.ts+++ b/ui/component/or-mwc-components/src/or-mwc-tabs.ts@@ -63,6 +63,9 @@ export class OrMwcTabs extends LitElement {@property({type: String})protected iconPosition?: "left" | "top";+ @property({type: Boolean})+ protected noScroll?: boolean;+@property({type: String})protected bgColor?: string;@@ -83,6 +86,7 @@ export class OrMwcTabs extends LitElement {if (this.index == null) { this.index = 0; }if (this.items == null) { this.items = []; }if (this.iconPosition == null) { this.iconPosition = "left"; }+ if (this.noScroll == null) { this.noScroll = false; }this.updateComplete.then(() => {const tabBarElement = this.shadowRoot?.querySelector('.mdc-tab-bar');@@ -141,7 +145,7 @@ export class OrMwcTabs extends LitElement {<div><div class="mdc-tab-bar" role="tablist" id="tab-bar"><div class="mdc-tab-scroller">- <div class="mdc-tab-scroller__scroll-area">+ <div class="mdc-tab-scroller__scroll-area" style="overflow-x: ${this.noScroll ? 'hidden' : undefined}"><div class="mdc-tab-scroller__scroll-content">${this.items?.map((menuItem => { return html`<button class="mdc-tab" role="tab" aria-selected="false" tabindex="${this.items?.indexOf(menuItem)}">diff --git a/ui/util/webpack.util.js b/ui/util/webpack.util.jsindex de9c068c3..c96e2f3f6 100644--- a/ui/util/webpack.util.js+++ b/ui/util/webpack.util.js@@ -10,12 +10,12 @@ function getStandardModuleRules() {return {rules: [{- test: /(maplibre|mapbox|@material|@mdi).*\.css$/, //output css as strings+ test: /(maplibre|mapbox|@material|gridstack|@mdi).*\.css$/, //output css as stringstype: "asset/source"},{test: /\.css$/, //- exclude: /(maplibre|mapbox|@material|@mdi).*\.css$/,+ exclude: /(maplibre|mapbox|@material|gridstack|@mdi).*\.css$/,use: [{ loader: "css-loader" }]diff --git a/yarn.lock b/yarn.lockindex 292f7e670..bd96c2e9d 100644--- a/yarn.lock+++ b/yarn.lock@@ -2148,6 +2148,15 @@ __metadata:languageName: unknownlinkType: soft+"@openremote/dashboard@workspace:ui/app/dashboard":+ version: 0.0.0-use.local+ resolution: "@openremote/dashboard@workspace:ui/app/dashboard"+ dependencies:+ "@openremote/or-app": ^1.1.0+ "@openremote/util": "workspace:*"+ languageName: unknown+ linkType: soft+"@openremote/demo-core@^1.0.4, @openremote/demo-core@workspace:ui/demo/demo-core":version: 0.0.0-use.localresolution: "@openremote/demo-core@workspace:ui/demo/demo-core"@@ -2248,6 +2257,8 @@ __metadata:"@openremote/or-attribute-input": ^1.1.0"@openremote/or-attribute-picker": ^1.1.0"@openremote/or-chart": ^1.1.0+ "@openremote/or-dashboard-builder": ^1.0.0+ "@openremote/or-gauge": ^1.0.0"@openremote/or-map": ^1.1.0"@openremote/or-mwc-components": ^1.1.0"@openremote/or-rules": ^1.1.0@@ -2408,6 +2419,19 @@ __metadata:languageName: unknownlinkType: soft+"@openremote/or-dashboard-builder@^1.0.0, @openremote/or-dashboard-builder@workspace:ui/component/or-dashboard-builder":+ version: 0.0.0-use.local+ resolution: "@openremote/or-dashboard-builder@workspace:ui/component/or-dashboard-builder"+ dependencies:+ "@openremote/core": "workspace:*"+ "@openremote/model": "workspace:*"+ "@openremote/rest": "workspace:*"+ "@openremote/util": "workspace:*"+ gridstack: ^6.0.2+ lit: ^2.0.2+ languageName: unknown+ linkType: soft+"@openremote/or-data-viewer@workspace:ui/component/or-data-viewer":version: 0.0.0-use.localresolution: "@openremote/or-data-viewer@workspace:ui/component/or-data-viewer"@@ -2429,6 +2453,21 @@ __metadata:languageName: unknownlinkType: soft+"@openremote/or-gauge@^1.0.0, @openremote/or-gauge@workspace:ui/component/or-gauge":+ version: 0.0.0-use.local+ resolution: "@openremote/or-gauge@workspace:ui/component/or-gauge"+ dependencies:+ "@openremote/core": "workspace:*"+ "@openremote/or-components": ^1.1.0+ "@openremote/or-icon": ^1.1.0+ "@openremote/or-mwc-components": ^1.1.0+ "@openremote/or-translate": ^1.1.0+ "@openremote/util": "workspace:*"+ gaugeJS: ^1.3.7+ lit: ^2.0.2+ languageName: unknown+ linkType: soft+"@openremote/or-icon@^1.1.0, @openremote/or-icon@workspace:ui/component/or-icon":version: 0.0.0-use.localresolution: "@openremote/or-icon@workspace:ui/component/or-icon"@@ -5327,6 +5366,13 @@ __metadata:languageName: nodelinkType: hard+"gaugeJS@npm:^1.3.7":+ version: 1.3.7+ resolution: "gaugeJS@npm:1.3.7"+ checksum: cf7d5a58816c9fab3fb071e36b9339eea89da01264fed32c284243c9de6813b09ec16ca76e04ccaabfb8adfd6c9e6a07abfecd140a7bc443fbc5461a5be55d2f+ languageName: node+ linkType: hard+"gensync@npm:^1.0.0-beta.2":version: 1.0.0-beta.2resolution: "gensync@npm:1.0.0-beta.2"@@ -5487,6 +5533,13 @@ __metadata:languageName: nodelinkType: hard+"gridstack@npm:^6.0.2":+ version: 6.0.2+ resolution: "gridstack@npm:6.0.2"+ checksum: 6ed7b323d549e7e7a4a09617994de61a8a22ec7949c1f3042eab274f4e931a0e9df49e9797bfc13cad1f7f6f06ed680137c1356c0b9e075f6bf05447b9a4eec9+ languageName: node+ linkType: hard+"growly@npm:^1.3.0":version: 1.3.0resolution: "growly@npm:1.3.0"