100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
UI updates: Asset viewer enhancements (#751)
Rich Turner1e6f0873f634
diff --git a/ui/app/manager/src/pages/page-assets.ts b/ui/app/manager/src/pages/page-assets.tsindex b3891b7b9..ced48a368 100644--- a/ui/app/manager/src/pages/page-assets.ts+++ b/ui/app/manager/src/pages/page-assets.ts@@ -178,13 +178,18 @@ export class PageAssets extends Page<AppStateKeyed> {this._confirmContinue(() => {const nodes = event.detail.detail.newNodes;+ const assetId = nodes.length === 1 ? nodes[0].asset!.id : undefined;- if (Util.objectsEqual(nodes, event.detail.detail.oldNodes)) {+ if (!Util.objectsEqual(nodes, event.detail.detail.oldNodes)) {+ this._assetIds = nodes.map((node) => node.asset.id!);+ }++ if (assetId === this._viewer.assetId) {// User has clicked the same node so let's force reload it- this._viewer.reloadAsset();+ this._viewer.assetId = undefined;+ this._viewer.assetId = assetId;} else {- this._assetIds = nodes.map((node) => node.asset.id!);- this._viewer.assetId = nodes.length === 1 ? nodes[0].asset!.id : undefined;+ this._viewer.assetId = assetId;this._updateRoute(true);}});diff --git a/ui/component/or-app/src/or-header.ts b/ui/component/or-app/src/or-header.tsindex fb19d4a33..af237f997 100644--- a/ui/component/or-app/src/or-header.ts+++ b/ui/component/or-app/src/or-header.ts@@ -17,7 +17,6 @@ import {ListItem} from "@openremote/or-mwc-components/or-mwc-list";import {Realm} from "@openremote/model";import {AppStateKeyed, router, updateRealm} from "./index";import {AnyAction, Store} from "@reduxjs/toolkit";-import {ThunkMiddleware} from "redux-thunk";export interface HeaderConfig {mainMenu: HeaderItem[];diff --git a/ui/component/or-asset-viewer/src/index.ts b/ui/component/or-asset-viewer/src/index.tsindex 13d9502ce..dfb87a602 100644--- a/ui/component/or-asset-viewer/src/index.ts+++ b/ui/component/or-asset-viewer/src/index.ts@@ -11,14 +11,14 @@ import "@openremote/or-chart";import "@openremote/or-mwc-components/or-mwc-table";import "@openremote/or-components/or-panel";import "@openremote/or-mwc-components/or-mwc-dialog";-import {showOkCancelDialog} from "@openremote/or-mwc-components/or-mwc-dialog";+import {showOkCancelDialog, showOkDialog} from "@openremote/or-mwc-components/or-mwc-dialog";import "@openremote/or-mwc-components/or-mwc-list";-import {OrTranslate, translate} from "@openremote/or-translate";+import {translate} from "@openremote/or-translate";import {InputType, OrInputChangedEvent, OrMwcInput} from "@openremote/or-mwc-components/or-mwc-input";import manager, {subscribe, Util} from "@openremote/core";import {OrMwcTable} from "@openremote/or-mwc-components/or-mwc-table";-import {OrChartConfig, OrChartEvent} from "@openremote/or-chart";-import {HistoryConfig, OrAttributeHistory, OrAttributeHistoryEvent} from "@openremote/or-attribute-history";+import {OrChartConfig} from "@openremote/or-chart";+import {HistoryConfig, OrAttributeHistory} from "@openremote/or-attribute-history";import {AgentDescriptor,Asset,@@ -39,16 +39,18 @@ import i18next, {InitOptions, TOptions} from "i18next";import {styleMap} from "lit/directives/style-map.js";import {classMap} from "lit/directives/class-map.js";import {GenericAxiosResponse} from "axios";-import {OrIcon} from "@openremote/or-icon";import "./or-edit-asset-panel";import {OrEditAssetModifiedEvent, OrEditAssetPanel, ValidatorResult} from "./or-edit-asset-panel";import "@openremote/or-mwc-components/or-mwc-snackbar";import {showSnackbar} from "@openremote/or-mwc-components/or-mwc-snackbar";+import {getContentWithMenuTemplate} from "@openremote/or-mwc-components/or-mwc-menu";+import {ListItem} from "@openremote/or-mwc-components/or-mwc-list";export interface PanelConfig {- type?: "info" | "setup" | "history" | "group" | "survey" | "survey-results" | "linkedUsers";+ type: "info" | "setup" | "history" | "group" | "survey" | "survey-results" | "linkedUsers";title?: string;hide?: boolean;+ column?: number;hideOnMobile?: boolean;panelStyles?: { [style: string]: string };}@@ -104,13 +106,8 @@ export interface GroupPanelConfig extends PanelConfig {};}-export type PanelConfigUnion = InfoPanelConfig | SetupPanelConfig | GroupPanelConfig | PanelConfig;-export type PanelViewProvider = (asset: Asset, attributes: { [index: string]: Attribute<any> }, panelName: string, hostElement: LitElement, viewerConfig: AssetViewerConfig, panelConfig: PanelConfigUnion) => TemplateResult | undefined;-export type PropertyViewProvider = (asset: Asset, property: string, value: any, hostElement: LitElement, viewerConfig: AssetViewerConfig, panelConfig: PanelConfigUnion) => TemplateResult | undefined;-export type AttributeViewProvider = (asset: Asset, attribute: Attribute<any>, hostElement: LitElement, viewerConfig: AssetViewerConfig, panelConfig: PanelConfigUnion) => TemplateResult | undefined;-export interface AssetViewerConfig {- panels?: {[name: string]: PanelConfigUnion};+ panels?: PanelConfigUnion[];viewerStyles?: { [style: string]: string };propertyViewProvider?: PropertyViewProvider;attributeViewProvider?: AttributeViewProvider;@@ -119,19 +116,32 @@ export interface AssetViewerConfig {chartConfig?: OrChartConfig;}+export type PanelConfigUnion = InfoPanelConfig | SetupPanelConfig | GroupPanelConfig | HistoryPanelConfig | PanelConfig;+export interface ViewerConfig {default?: AssetViewerConfig;assetTypes?: { [assetType: string]: AssetViewerConfig };historyConfig?: HistoryConfig;}-export const DEFAULT_ASSET_PROPERTIES = [- "name",- "createdOn",- "type",- "parentId",- "accessPublicRead"-];+interface UserAssetLinkInfo {+ usernameAndId: string;+ roles: string[];+ restrictedUser: boolean;+}++interface AssetInfo {+ asset: Asset;+ userAssetLinks?: UserAssetLinkInfo[];+ childAssets?: Asset[];+ viewerConfig: AssetViewerConfig;+ modified: boolean;+ attributeTemplateMap: {[attrName: string]: TemplateResult};+}++export type PanelViewProvider = (asset: Asset, attributes: { [index: string]: Attribute<any> }, panelName: string, hostElement: LitElement, viewerConfig: AssetViewerConfig, panelConfig: PanelConfigUnion) => TemplateResult | undefined;+export type PropertyViewProvider = (asset: Asset, property: string, value: any, hostElement: LitElement, viewerConfig: AssetViewerConfig, panelConfig: PanelConfigUnion) => TemplateResult | undefined;+export type AttributeViewProvider = (asset: Asset, attribute: Attribute<any>, hostElement: LitElement, viewerConfig: AssetViewerConfig, panelConfig: PanelConfigUnion) => TemplateResult | undefined;export function getIncludedProperties(config?: InfoPanelConfig): string[] {const includedProperties = config && config.properties && config.properties.include ? config.properties.include : DEFAULT_ASSET_PROPERTIES;@@ -151,28 +161,6 @@ export function getIncludedAttributes(attributes: { [index: string]: Attribute<areturn Object.values(attributes);}-class EventHandler {- _callbacks: Function[];-- constructor() {- this._callbacks = [];- }-- startCallbacks() {- return new Promise<void>((resolve, reject) => {- if (this._callbacks && this._callbacks.length > 0) {- this._callbacks.forEach(cb => cb());- }- resolve();- })-- }-- addCallback(callback: Function) {- this._callbacks.push(callback);- }-}-export class OrAssetViewerComputeGridEvent extends CustomEvent<void> {public static readonly NAME = "or-asset-viewer-compute-grid-event";@@ -260,19 +248,17 @@ declare global {}}-const onRenderComplete = new EventHandler();--export function getPanel(name: string, panelConfig: PanelConfig, content: TemplateResult | undefined) {+export function getPanel(id: string, panelConfig: PanelConfig, content: TemplateResult | undefined) {if (!content) {return;}return html`- <div class=${classMap({panel: true, mobileHidden: panelConfig.hideOnMobile === true})} id="${name}-panel" style="${panelConfig && panelConfig.panelStyles ? styleMap(panelConfig.panelStyles) : ""}">+ <div class=${classMap({panel: true, mobileHidden: panelConfig.hideOnMobile === true})} style="${panelConfig && panelConfig.panelStyles ? styleMap(panelConfig.panelStyles) : ""}" id="${id}-panel"><div class="panel-content-wrapper"><div class="panel-title">- <or-translate value="${panelConfig.title ? panelConfig.title : name}"></or-translate>+ <or-translate value="${panelConfig.title || panelConfig.type}"></or-translate></div><div class="panel-content">${content}@@ -282,11 +268,13 @@ export function getPanel(name: string, panelConfig: PanelConfig, content: Templa`;}-export function getPanelContent(panelName: string, asset: Asset, attributes: { [index: string]: Attribute<any> }, hostElement: LitElement, viewerConfig: AssetViewerConfig, panelConfig: PanelConfig): TemplateResult | undefined {+function getPanelContent(id: string, assetInfo: AssetInfo, hostElement: LitElement, viewerConfig: AssetViewerConfig, panelConfig: PanelConfigUnion): TemplateResult | undefined {++ const asset = assetInfo.asset;// See if config has a custom way for rendering this panelif (viewerConfig.panelViewProvider) {- const template = viewerConfig.panelViewProvider(asset, attributes, panelName, hostElement, viewerConfig, panelConfig);+ const template = viewerConfig.panelViewProvider(asset, asset.attributes!, id, hostElement, viewerConfig, panelConfig);if (template) {return template;}@@ -299,7 +287,7 @@ export function getPanelContent(panelName: string, asset: Asset, attributes: { [// This type of panel shows attributes and/or properties of the assetconst infoConfig = panelConfig as InfoPanelConfig;const includedProperties = getIncludedProperties(infoConfig);- const includedAttributes = getIncludedAttributes(attributes, infoConfig);+ const includedAttributes = getIncludedAttributes(asset.attributes!, infoConfig);if (includedProperties.length === 0 && includedAttributes.length === 0) {return undefined;@@ -356,8 +344,15 @@ export function getPanelContent(panelName: string, asset: Asset, attributes: { [// This is a propertyreturn getField(item.item, item.itemConfig, getPropertyTemplate(asset, item.item, hostElement, viewerConfig, panelConfig, item.itemConfig));} else {- // This is an attribute- return getField(item.item.name!, item.itemConfig, getAttributeTemplate(asset, item.item, hostElement, viewerConfig, panelConfig, item.itemConfig));+ // This is an attribute look for a cached template+ if (assetInfo.attributeTemplateMap[item.item.name!]) {+ return getField(item.item.name!, item.itemConfig, assetInfo.attributeTemplateMap[item.item.name!]);+ }++ const template = getAttributeTemplate(asset, item.item, hostElement, viewerConfig, panelConfig, item.itemConfig);+ assetInfo.attributeTemplateMap[item.item.name!] = template;++ return getField(item.item.name!, item.itemConfig, template);}})}`;}@@ -366,7 +361,7 @@ export function getPanelContent(panelName: string, asset: Asset, attributes: { [const descriptor = AssetModelUtil.getAssetDescriptor(asset.type) as AgentDescriptor;- if (!descriptor || !asset.id || descriptor.descriptorType !== "agent" || !descriptor.assetDiscovery && !descriptor.assetImport) {+ if (!descriptor || !asset.id || descriptor.descriptorType !== "agent" || (!descriptor.assetDiscovery && !descriptor.assetImport)) {return;}@@ -520,28 +515,13 @@ export function getPanelContent(panelName: string, asset: Asset, attributes: { [}- // This is not something that should be part of the standard asset-viewer- if (panelConfig.type === "survey") {- return html``;- // return html`- // <or-survey id="survey" .surveyId="${asset.id}"></or-survey>- // `;- }-- // This is not something that should be part of the standard asset-viewer- if (panelConfig.type === "survey-results") {- return html``;- // return html`- // <or-survey-results id="survey-results" .survey="${asset}"></or-survey-results>- // `;- }-+ // Special handling for history panel which shows an attribute selector and a graph/data table of historical valuesif (panelConfig.type === "history") {- // Special handling for history panel which shows an attribute selector and a graph/data table of historical values+const historyConfig = panelConfig as HistoryPanelConfig;const includedAttributes = historyConfig.include ? historyConfig.include : undefined;const excludedAttributes = historyConfig.exclude ? historyConfig.exclude : [];- const historyAttrs = Object.values(attributes).filter((attr) =>+ const historyAttrs = Object.values(assetInfo?.asset?.attributes!).filter((attr) =>(!includedAttributes || includedAttributes.indexOf(attr.name!) >= 0)&& (!excludedAttributes || excludedAttributes.indexOf(attr.name!) < 0)&& (attr.meta && (attr.meta.hasOwnProperty(WellknownMetaItems.STOREDATAPOINTS) ? attr.meta[WellknownMetaItems.STOREDATAPOINTS] : attr.meta.hasOwnProperty(WellknownMetaItems.AGENTLINK))));@@ -550,19 +530,17 @@ export function getPanelContent(panelName: string, asset: Asset, attributes: { [return undefined;}+ let selectedAttribute: Attribute<any> | undefined;+const attributeChanged = (attributeName: string) => {if (hostElement.shadowRoot) {const attributeHistory = hostElement.shadowRoot.getElementById("attribute-history") as OrAttributeHistory;-- if (attributeHistory) {-- let attribute: Attribute<any> | undefined;-- if (attributeName) {- attribute = asset.attributes && asset.attributes![attributeName];- }-+ if (attributeName && attributeHistory) {+ let attribute = asset.attributes && asset.attributes![attributeName];+ const descriptors = AssetModelUtil.getAttributeAndValueDescriptors(asset.type, attribute!.name, attribute);+ const label = Util.getAttributeLabel(attribute, descriptors[0], asset.type, true);attributeHistory.attribute = attribute;+ selectedAttribute = attribute!;}}};@@ -573,60 +551,55 @@ export function getPanelContent(panelName: string, asset: Asset, attributes: { [return [attr.name, label];});- let attrName: string = historyAttrs[0].name!;- onRenderComplete.addCallback(() => {- if (hostElement.shadowRoot && historyAttrs.length > 1 && panelConfig.type === "history") {- const historyAttributePicker = hostElement.shadowRoot.getElementById("history-attribute-picker") as OrMwcInput;- // as callback's are not reset on asset select in asset tree, need to check if history select dom elem exists- if (historyAttributePicker) {- attrName = historyAttributePicker.value;- }- }- attributeChanged(attrName);- });+ let attrTemplate = html`+ <div id="attribute-picker">+ <or-mwc-input .checkAssetWrite="${false}" .label="${i18next.t("attribute")}" @or-mwc-input-changed="${(evt: OrInputChangedEvent) => attributeChanged(evt.detail.value)}" .type="${InputType.SELECT}" .options="${options}"></or-mwc-input>+ </div>`;+return html`<style>- or-attribute-history{- min-height: 70px;- width: 100%;+ #attribute-picker {+ flex: 0;+ margin: 10px 0;+ position: unset;+ }++ #attribute-picker > or-mwc-input {+ width: 250px;}- #history-controls {- flex: 0;- margin-bottom: 10px;- position: absolute;- }-- #history-attribute-picker {- flex: 0;- width: 200px;- }or-attribute-history {- --or-attribute-history-controls-margin: 0 0 20px 204px;- }-- @media screen and (max-width: 2028px) {- #history-controls {- position: unset;- margin: 0 0 10px 0;- }-- or-attribute-history {- --or-attribute-history-controls-margin: 10px 0 0 0;- --or-attribute-history-controls-margin-children: 0 20px 20px 0;- }+ width: 100%;+ --or-attribute-history-controls-margin: 10px 0 10px -5px;+ --or-attribute-history-controls-justify-content: flex-start;}++ @media screen and (min-width: 1900px) {+ #attribute-picker {+ position: absolute;+ }++ or-attribute-history {+ --or-attribute-history-controls-margin: 10px 0;+ --or-attribute-history-controls-justify-content: flex-end;+ min-height: 70px;+ }+ }</style>- <div id="history-controls">- <or-mwc-input id="history-attribute-picker" .checkAssetWrite="${false}" .value="${historyAttrs[0].name}" .label="${i18next.t("attribute")}" @or-mwc-input-changed="${(evt: OrInputChangedEvent) => attributeChanged(evt.detail.value)}" .type="${InputType.SELECT}" .options="${options}"></or-mwc-input>- </div>+ ${attrTemplate}<or-attribute-history id="attribute-history" .config="${viewerConfig.historyConfig}" .assetType="${asset.type}" .assetId="${asset.id}"></or-attribute-history>`;}if (panelConfig.type === "group") {- if (asset.type !== "GroupAsset") {+ if (!asset.id || asset.type !== "GroupAsset") {+ return;+ }++ const childAssets = assetInfo.childAssets;++ if (!childAssets || childAssets.length === 0) {return;}@@ -637,8 +610,8 @@ export function getPanelContent(panelName: string, asset: Asset, attributes: { [if (!childAssetTypeAttribute || typeof childAssetTypeAttribute.value !== "string") {return;}+const childAssetType = childAssetTypeAttribute.value as string;- let childAssets: Asset[] = [];// Determine available and selected attributes for the child asset typelet availableAttributes: string[] = [];@@ -649,15 +622,41 @@ export function getPanelContent(panelName: string, asset: Asset, attributes: { [availableAttributes = groupConfig.childAssetTypes[childAssetType].availableAttributes ? groupConfig.childAssetTypes[childAssetType].availableAttributes! : [];selectedAttributes = groupConfig.childAssetTypes[childAssetType].selectedAttributes ? groupConfig.childAssetTypes[childAssetType].selectedAttributes! : [];}- const config: any = manager.console.retrieveData("OrAssetConfig");- const viewSelector = asset.id ? asset.id : window.location.hash;- if (config && config.views) {- const view = config.views[viewSelector];- if (view) {- selectedAttributes = [...view]- }- }+ const updateSelectedAttributes = (newSelection: string[]) => {+ selectedAttributes.length = 0;+ selectedAttributes.push(...newSelection);+ const attributeTable: OrMwcTable = hostElement.shadowRoot!.getElementById(id + "-attribute-table") as OrMwcTable;+ const headersAndRows = getHeadersAndRows();+ attributeTable!.headers = headersAndRows[0];+ attributeTable!.rows = headersAndRows[1];+ config.views[asset.id!] = [...selectedAttributes];+ manager.console.storeData("OrAssetConfig", config);+ };++ let config: {views: {[assetId: string]: string[]}};++ manager.console.retrieveData("OrAssetConfig")+ .then(conf => {++ config = (conf as any);++ if (!config) {+ config = {+ views: {}+ };+ }+ if (!config.views) {+ config.views = {};+ }++ const view = config.views[asset.id!];++ if (view) {+ updateSelectedAttributes([...view]);+ }+ });+// Get available and selected attributes from asset descriptor if not defined in configif (availableAttributes.length === 0) {const descriptor = AssetModelUtil.getAssetTypeInfo(childAssetType);@@ -666,7 +665,31 @@ export function getPanelContent(panelName: string, asset: Asset, attributes: { [}}if ((!selectedAttributes || selectedAttributes.length === 0) && availableAttributes) {- selectedAttributes = [...availableAttributes];+ selectedAttributes = [...new Set(childAssets.map(childAsset => Object.keys(childAsset.attributes!)).flat())];+ }++ const getHeadersAndRows: () => [string[], string[][]] = () => {++ const attrNames = [...selectedAttributes].sort();++ const headers = attrNames.map((attrName) => {+ const attributeDescriptor = AssetModelUtil.getAttributeDescriptor(attrName, childAssetType);+ return Util.getAttributeLabel(undefined, attributeDescriptor, asset.type, false);+ });++ const rows = childAssets.map((childAsset) => {+ // todo: it's only processing including selected headers here...+ // move this to the columnFilter option of the table+ const arr = attrNames.map((attributeName) => {+ return childAsset.attributes![attributeName] ? childAsset.attributes![attributeName].value! as string : "";+ });+ arr.unshift(childAsset.name!);+ return arr;+ });++ headers.unshift(i18next.t("groupAssetName"));++ return [headers, rows];}const attributePickerModalOpen = () => {@@ -686,136 +709,58 @@ export function getPanelContent(panelName: string, asset: Asset, attributes: { [`).then((ok) => {if (ok) {- selectedAttributes.length = 0;- selectedAttributes.push(...newlySelectedAttributes);- updateTable();+ updateSelectedAttributes(newlySelectedAttributes);}});};- // Function to update the table and message when assets or config changes- const updateTable = () => {-- const loadingMsg: OrTranslate = hostElement.shadowRoot!.getElementById(panelName + "-attribute-table-msg") as OrTranslate;- const attributeTable: OrMwcTable = hostElement.shadowRoot!.getElementById(panelName + "-attribute-table") as OrMwcTable;- const addRemoveButton: OrIcon = hostElement.shadowRoot!.getElementById(panelName + "-add-remove-columns") as OrIcon;-- if (!loadingMsg || !attributeTable || !addRemoveButton) {- return;- }-- if (selectedAttributes.length === 0 || !childAssets || childAssets.length === 0) {- loadingMsg.value = "noChildAssets";- loadingMsg.hidden = false;- attributeTable.hidden = true;- addRemoveButton.classList.remove("active");- return;- }-- // Update table properties which will cause a re-render- addRemoveButton.classList.add("active");- loadingMsg.hidden = true;- attributeTable.hidden = false;- const headers = [...selectedAttributes].sort();- attributeTable.headers = headers.map((attrName) => {- const attributeDescriptor = AssetModelUtil.getAttributeDescriptor(attrName, childAssetType);- return Util.getAttributeLabel(undefined, attributeDescriptor, asset.type, false);- });- attributeTable.headers.unshift(i18next.t("groupAssetName"));- attributeTable.rows = childAssets.map((childAsset) => {- // todo: it's only processing including selected headers here...- // move this to the columnFilter option of the table- const arr = headers.map((attributeName) => {- return childAsset.attributes![attributeName] ? childAsset.attributes![attributeName].value! as string : "";- });- arr.unshift(childAsset.name!);- return arr;- });-- let config: any = manager.console.retrieveData("OrAssetConfig");-- if (config) {- if (asset.id) {- config.views[asset.id] = selectedAttributes;- }- } else {- config = {- views: {- [asset.id!]: selectedAttributes- }- }- }-- manager.console.storeData("OrAssetConfig", config);- window.setTimeout(() => OrAssetViewer.generateGrid(hostElement.shadowRoot), 0);- };-- // Load child assets async then update the table- getAssetChildren(asset.id!, asset.attributes!.childAssetType.value).then((assetChildren) => {- childAssets = assetChildren;- updateTable();- });+ const headersAndRows = getHeadersAndRows();// Define the DOM content for this panelreturn html`<style>.asset-group-add-remove-button {position: absolute;- top: 20px;- right: var(--internal-or-asset-viewer-panel-padding);- opacity: 0.5;+ --or-mwc-input-color: currentColor;+ top: calc(var(--internal-or-asset-viewer-panel-padding) - 15px);+ right: calc(var(--internal-or-asset-viewer-panel-padding) - 15px);}.asset-group-add-remove-button.active {cursor: pointer;opacity: 1;}</style>- <or-icon class="asset-group-add-remove-button" .id="${panelName}-add-remove-columns" icon="pencil" @click="${() => attributePickerModalOpen()}"></or-icon>- <or-mwc-table hidden .id="${panelName}-attribute-table" .options="{stickyFirstColumn:true}"></or-mwc-table>- <span><or-translate id="${panelName}-attribute-table-msg" value="loading"></or-translate></span>+ <or-mwc-input .type="${InputType.BUTTON}" class="asset-group-add-remove-button" icon="pencil" @click="${() => attributePickerModalOpen()}"></or-mwc-input>+ <or-mwc-table .headers="${headersAndRows[0]}" .rows="${headersAndRows[1]}" .id="${id}-attribute-table" .options="{stickyFirstColumn:true}"></or-mwc-table>`;}if (panelConfig.type === "linkedUsers") {const hasReadAdminRole = manager.hasRole(ClientRole.READ_ADMIN);-- // Hide the panel if user doesn't have permission- const panelElem = hostElement.shadowRoot!.getElementById('linkedUsers-panel');- if (panelElem) {- panelElem.hidden = !hasReadAdminRole;- }+ const assetLinkInfos = assetInfo.userAssetLinks;if (!hasReadAdminRole) {return;}- getLinkedUsers(asset).then((assetLinkInfos) => {- const panelElem = hostElement.shadowRoot!.getElementById('linkedUsers-panel');- const userTable: OrMwcTable = hostElement.shadowRoot!.getElementById(panelName + "-user-table") as OrMwcTable;- userTable.options = {stickyFirstColumn:false};- userTable.headers = ["Username", "Roles", "Restricted user"];- userTable.rows = assetLinkInfos.sort(Util.sortByString(u => u.usernameAndId)).map(assetLinkInfo => {- return [- assetLinkInfo.usernameAndId,- assetLinkInfo.roles.join(", "),- assetLinkInfo.restrictedUser ? i18next.t("yes") : i18next.t("no")- ];- });+ if (!assetLinkInfos || assetLinkInfos.length === 0) {+ return;+ }- if (panelElem) {- panelElem.hidden = assetLinkInfos.length === 0;- onRenderComplete.startCallbacks().then(() => {- OrAssetViewer.generateGrid(hostElement.shadowRoot);- });- }+ const rows = assetLinkInfos.sort(Util.sortByString(u => u.usernameAndId)).map(assetLinkInfo => {+ return [+ assetLinkInfo.usernameAndId,+ assetLinkInfo.roles.join(", "),+ assetLinkInfo.restrictedUser ? i18next.t("yes") : i18next.t("no")+ ];});- return html`<or-mwc-table .id="${panelName}-user-table"></or-mwc-table>`;+ return html`<or-mwc-table .rows="${rows}" .options="${{stickyFirstColumn:false}}" .headers="${["Username", "Roles", "Restricted user"]}"></or-mwc-table>`;}}-export function getAttributeTemplate(asset: Asset, attribute: Attribute<any>, hostElement: LitElement, viewerConfig: AssetViewerConfig, panelConfig: PanelConfig, itemConfig: InfoPanelItemConfig) {+export function getAttributeTemplate(asset: Asset, attribute: Attribute<any>, hostElement: LitElement, viewerConfig: AssetViewerConfig, panelConfig: PanelConfig, itemConfig: InfoPanelItemConfig): TemplateResult {if (viewerConfig.attributeViewProvider) {const result = viewerConfig.attributeViewProvider(asset, attribute, hostElement, viewerConfig, panelConfig);if (result) {@@ -863,7 +808,8 @@ export function getPropertyTemplate(asset: Asset, property: string, hostElement:// Populate value when we get the responseconst ancestors = [...value];- ancestors.splice(0,1);+ // Remove this asset from the path+ ancestors.pop();value = "";if (ancestors.length > 0) {getAssetNames(ancestors).then(@@ -871,7 +817,7 @@ export function getPropertyTemplate(asset: Asset, property: string, hostElement:if (hostElement && hostElement.shadowRoot) {const pathField = hostElement.shadowRoot.getElementById("property-parentId") as OrMwcInput;if (pathField) {- pathField.value = names.reverse().join(" > ");+ pathField.value = names.join(" > ");}}}@@ -917,14 +863,14 @@ async function getAssetNames(ids: string[]): Promise<string[]> {return ids.map((id) => response.data.find((asset) => asset.id === id)!.name!);}-async function getAssetChildren(id: string, childAssetType: string): Promise<Asset[]> {+async function getAssetChildren(parentId: string, childAssetType: string): Promise<Asset[]> {let response: GenericAxiosResponse<Asset[]>;try {response = await manager.rest.api.AssetResource.queryAssets({parents: [{- id: id+ id: parentId}]});@@ -940,12 +886,6 @@ async function getAssetChildren(id: string, childAssetType: string): Promise<Assreturn response.data.filter((asset) => asset.type === childAssetType);}-interface UserAssetLinkInfo {- usernameAndId: string;- roles: string[];- restrictedUser: boolean;-}-async function getLinkedUserInfo(userAssetLink: UserAssetLink): Promise<UserAssetLinkInfo> {const userId = userAssetLink.id!.userId!;const username = userAssetLink.userFullName!;@@ -1030,16 +970,22 @@ export async function saveAsset(asset: Asset): Promise<SaveResult> {// TODO: Add webpack/rollup to build so consumers aren't forced to use the same toolingconst tableStyle = require("@material/data-table/dist/mdc.data-table.css");-export const DEFAULT_VIEWER_CONFIG: AssetViewerConfig = {- viewerStyles: {+export const DEFAULT_ASSET_PROPERTIES = [+ "name",+ "createdOn",+ "type",+ "parentId",+ "accessPublicRead"+];- },- panels: {- group: {+export const DEFAULT_VIEWER_CONFIG: AssetViewerConfig = {+ viewerStyles: {},+ panels: [+ {type: "group",title: "underlyingAssets"},- info: {+ {type: "info",hideOnMobile: true,properties: {@@ -1049,13 +995,24 @@ export const DEFAULT_VIEWER_CONFIG: AssetViewerConfig = {include: ["notes", "manufacturer", "model"]}},- setup: {+ {+ title: "attributes",+ type: "info",+ properties: {+ include:[]+ },+ attributes: {+ exclude: ["location", "notes", "manufacturer", "model"]+ }+ },+ {type: "setup",- title: "setup",hideOnMobile: false},- location: {+ {+ title: "location",type: "info",+ column: 1,properties: {include:[]},@@ -1069,23 +1026,15 @@ export const DEFAULT_VIEWER_CONFIG: AssetViewerConfig = {}}},- attributes: {- type: "info",- properties: {- include:[]- },- attributes: {- exclude: ["location", "notes", "manufacturer", "model"]- }+ {+ type: "history",+ column: 1},- history: {- type: "history"- },- linkedUsers: {+ {type: "linkedUsers",- title: "linkedUsers",+ column: 1}- }+ ]};@customElement("or-asset-viewer")@@ -1114,17 +1063,11 @@ export class OrAssetViewer extends subscribe(manager)(translate(i18next)(LitElem@property({type: Boolean})public readonly?: boolean;- @property()- protected _loading: boolean = false;-@state()- protected _assetModified = false;+ protected _assetInfo?: AssetInfo;@state()protected _validationResults: ValidatorResult[] = [];- protected _viewerConfig?: AssetViewerConfig;- protected _attributes?: { [index: string]: Attribute<any> };- protected resizeHandler = () => OrAssetViewer.generateGrid(this.shadowRoot);@query("#wrapper")protected wrapperElem!: HTMLDivElement;@@ -1140,25 +1083,11 @@ export class OrAssetViewer extends subscribe(manager)(translate(i18next)(LitElemconstructor() {super();- this.addEventListener(OrAssetViewerComputeGridEvent.NAME, () => OrAssetViewer.generateGrid(this.shadowRoot));- this.addEventListener(OrChartEvent.NAME, () => OrAssetViewer.generateGrid(this.shadowRoot));- this.addEventListener(OrAttributeHistoryEvent.NAME, () => OrAssetViewer.generateGrid(this.shadowRoot));this.addEventListener(OrEditAssetModifiedEvent.NAME, (ev: OrEditAssetModifiedEvent) => this._onAssetModified(ev.detail));- this.addEventListener('keyup', () => this._assetModified = true)}public isModified() {- return !!this.editMode && this._assetModified;- }-- connectedCallback() {- super.connectedCallback();- window.addEventListener("resize", this.resizeHandler);- }-- disconnectedCallback() {- super.disconnectedCallback();- window.removeEventListener("resize", this.resizeHandler);+ return !!this.editMode && this._assetInfo && this._assetInfo.modified;}shouldUpdate(changedProperties: PropertyValues): boolean {@@ -1167,38 +1096,31 @@ export class OrAssetViewer extends subscribe(manager)(translate(i18next)(LitElemthis.editMode = false;}- if (changedProperties.has("asset")) {- this._viewerConfig = undefined;- this._attributes = undefined;-- if (this.asset) {- if (!this.asset.attributes) {- this.asset.attributes = {};- }- this._viewerConfig = this._getPanelConfig(this.asset);- this._attributes = this.asset.attributes;- this._assetModified = !this.asset.id;- }- }-if (changedProperties.has("assetId")) {+ this._assetInfo = undefined;this.asset = undefined;++ // Set asset ID on mixin which will go and load the assetif (this.assetId) {- this._loading = true;super.assetIds = [this.assetId];} else {- this._loading = false;super.assetIds = undefined;}- } else if (changedProperties.has("editMode") && !this.editMode) {- this.reloadAsset();}- this.onCompleted().then(() => {- onRenderComplete.startCallbacks().then(() => {- OrAssetViewer.generateGrid(this.shadowRoot);- });- });+ if (changedProperties.has("asset")) {+ this._assetInfo = undefined;+ this.assetId = undefined;+ super.assetIds = undefined;++ if (this.asset) {+ this.loadAssetInfo(this.asset)+ .then(assetInfo => this._assetInfo = assetInfo)+ .catch(reason => {+ // We can ignore this as it should indicate that the asset has changed+ });+ }+ }return super.shouldUpdate(changedProperties);}@@ -1209,6 +1131,58 @@ export class OrAssetViewer extends subscribe(manager)(translate(i18next)(LitElem}}+ async loadAssetInfo(asset: Asset): Promise<AssetInfo> {++ if (!asset) {+ throw new Error("Asset has changed");+ }++ if (!asset.attributes) {+ asset.attributes = {};+ }++ const exists = !!asset.id;+ const modified = !exists;+ const viewerConfig = this._getPanelConfig(asset);++ if (!exists) {+ // Newly created asset not yet saved+ return {+ asset: asset,+ modified: modified,+ viewerConfig: viewerConfig,+ attributeTemplateMap: {}+ };+ }++ const links = await getLinkedUsers(asset);++ // Check this asset is still the correct one+ if (this.assetId && this.assetId !== asset.id) {+ throw new Error("Asset has changed");+ }++ // Load child assets for group asset+ let childAssets: Asset[] | undefined = undefined;+ if (asset.type === WellknownAssets.GROUPASSET) {+ childAssets = await getAssetChildren(asset.id!, asset.attributes![WellknownAttributes.CHILDASSETTYPE].value);+ }++ // Check this asset is still the correct one+ if (this.assetId && this.assetId !== asset.id) {+ throw new Error("Asset has changed");+ }++ return {+ asset: asset,+ modified: modified,+ viewerConfig: viewerConfig,+ childAssets: childAssets,+ userAssetLinks: links,+ attributeTemplateMap: {}+ };+ }+protected _doValidation() {if (this.editMode && this.editor) {this._validationResults = this.editor.validate();@@ -1217,56 +1191,40 @@ export class OrAssetViewer extends subscribe(manager)(translate(i18next)(LitElemprotected render(): TemplateResult | void {- if (this._loading) {+ const noSelection = !this.asset && !this.assetId;++ if (noSelection) {return html`- <div class="msg"><or-translate value="loading"></or-translate></div>+ <div class="msg"><or-translate value="noAssetSelected"></or-translate></div>`;}- if (!this.asset && !this.assetId) {+ if (!this._assetInfo) {return html`- <div class="msg"><or-translate value="noAssetSelected"></or-translate></div>+ <div class="msg"><or-translate value="loading"></or-translate></div>`;}- if (!this.asset) {+ if (!this._assetInfo.asset) {return html`<div><or-translate value="notFound"></or-translate></div>`;}- if (!this._attributes || !this._viewerConfig) {- return html``;- }-- const descriptor = AssetModelUtil.getAssetDescriptor(this.asset!.type!);+ const asset = this._assetInfo.asset;+ const descriptor = AssetModelUtil.getAssetDescriptor(asset.type!);const editMode = !!this.editMode;-let content: TemplateResult | string = ``;+ let validationErrors: string[] = [];if (editMode) {content = html`<div id="edit-container">- <or-edit-asset-panel id="editor" .asset="${this.asset}"></or-edit-asset-panel>+ <or-edit-asset-panel id="editor" .asset="${asset}"></or-edit-asset-panel></div>`;- } else {- if (this._viewerConfig.panels) {- content = html`- <div id="view-container" style="${this._viewerConfig.viewerStyles ? styleMap(this._viewerConfig.viewerStyles) : ""}">- ${Object.entries(this._viewerConfig.panels).map(([name, panelConfig]) => {- if (panelConfig.hide) {- return ``;- }-- return getPanel(name, panelConfig, getPanelContent(name, this.asset!, this._attributes!, this, this._viewerConfig!, panelConfig)) || ``;- })}- </div>`;- }- }- const validationErrors: string[] = this.editMode- ? this._validationResults+ validationErrors = this._validationResults.filter((validationResult) => !validationResult.valid || validationResult.metaResults && validationResult.metaResults.some((r) => !r.valid)).flatMap((validationResult) => {const errors: string[] = [];@@ -1279,8 +1237,41 @@ export class OrAssetViewer extends subscribe(manager)(translate(i18next)(LitElem});}return errors;- })- : [];+ });+ } else {+ const viewerConfig = this._assetInfo.viewerConfig;++ if (viewerConfig.panels) {++ const leftColumn: (TemplateResult | string)[] = [];+ const rightColumn: (TemplateResult | string)[] = [];++ viewerConfig.panels.forEach((panelConfig, index) => {+ if (!panelConfig.hide) {+ const id = index+"";+ const column = panelConfig.column || 0;+ const template = getPanel(id, panelConfig, getPanelContent(id, this._assetInfo!, this, viewerConfig, panelConfig)) || ``;++ if (template) {+ if (column == 0) {+ leftColumn.push(template);+ } else {+ rightColumn.push(template);+ }+ }+ }});++ content = html`+ <div id="view-container" style="${viewerConfig.viewerStyles ? styleMap(viewerConfig.viewerStyles) : ""}">+ <div id="left-column" class="panelContainer">+ ${leftColumn}+ </div>+ <div id="right-column" class="panelContainer">+ ${rightColumn}+ </div>+ </div>`;+ }+ }return html`<div id="wrapper">@@ -1292,12 +1283,12 @@ export class OrAssetViewer extends subscribe(manager)(translate(i18next)(LitElem<or-icon title="${descriptor && descriptor.name ? descriptor.name : "unset"}" style="--or-icon-fill: ${descriptor && descriptor.colour ? "#" + descriptor.colour : "unset"}" icon="${descriptor && descriptor.icon ? descriptor.icon : AssetModelUtil.getAssetDescriptorIcon(WellknownAssets.THINGASSET)}"></or-icon>${editMode? html`- <or-mwc-input id="name-input" .type="${InputType.TEXT}" min="1" max="1023" comfortable required outlined .label="${i18next.t("name")}" .value="${this.asset.name}" @or-mwc-input-changed="${(e: OrInputChangedEvent) => {this.asset!.name = e.detail.value; this._assetModified = true; this._doValidation();}}"></or-mwc-input>+ <or-mwc-input id="name-input" .type="${InputType.TEXT}" min="1" max="1023" comfortable required outlined .label="${i18next.t("name")}" .value="${asset.name}" @or-mwc-input-changed="${(e: OrInputChangedEvent) => {asset!.name = e.detail.value; this._assetInfo!.modified = true; this._doValidation();}}"></or-mwc-input>`- : html`<span>${this.asset.name}</span>`}+ : html`<span>${asset.name}</span>`}</div><div id="right-wrapper" class="mobileHidden">- ${validationErrors.length === 0 ? (this.asset!.createdOn ? html`<or-translate id="created-time" class="tabletHidden" value="createdOnWithDate" .options="${{ date: new Date(this.asset!.createdOn!) } as TOptions<InitOptions>}"></or-translate>` : ``) : html`<span id="error-wrapper" .title="${validationErrors.join("\n")}"><or-icon icon="alert"></or-icon><or-translate class="tabletHidden" value="validation.invalidAsset"></or-translate></span>`}+ ${validationErrors.length === 0 ? (asset!.createdOn ? html`<or-translate id="created-time" class="tabletHidden" value="createdOnWithDate" .options="${{ date: new Date(asset!.createdOn!) } as TOptions<InitOptions>}"></or-translate>` : ``) : html`<span id="error-wrapper" .title="${validationErrors.join("\n")}"><or-icon icon="alert"></or-icon><or-translate class="tabletHidden" value="validation.invalidAsset"></or-translate></span>`}${editMode ? html`<or-mwc-input id="save-btn" .disabled="${!this.isModified()}" raised .type="${InputType.BUTTON}" .label="${i18next.t("save")}" @or-mwc-input-changed="${() => this._onSaveClicked()}"></or-mwc-input>` : ``}${!this._isReadonly() ? html`<or-mwc-input id="edit-btn" outlined .type="${InputType.BUTTON}" .value="${this.editMode}" .label="${this.editMode ? i18next.t("viewAsset") : i18next.t("editAsset")}" icon="${this.editMode ? "eye" : "pencil"}" @or-mwc-input-changed="${() => this._onEditToggleClicked(!this.editMode!)}"></or-mwc-input>`: ``}@@ -1308,23 +1299,10 @@ export class OrAssetViewer extends subscribe(manager)(translate(i18next)(LitElem`;}- public reloadAsset() {- this.asset = undefined;- this._assetModified = false;- if (this.assetId) {- this._loading = true;- super._refreshEventSubscriptions();- }- }-protected _isReadonly() {return this.readonly || !manager.hasRole(ClientRole.WRITE_ASSETS);}- async onCompleted() {- await this.updateComplete;- }-protected _onEditToggleClicked(edit: boolean) {Util.dispatchCancellableEvent(this,@@ -1344,11 +1322,11 @@ export class OrAssetViewer extends subscribe(manager)(translate(i18next)(LitElem}protected _onSaveClicked() {- if (!this.asset) {+ if (!this._assetInfo || !this._assetInfo.asset) {return;}- Util.dispatchCancellableEvent(this, new OrAssetViewerRequestSaveEvent(this.asset))+ Util.dispatchCancellableEvent(this, new OrAssetViewerRequestSaveEvent(this._assetInfo.asset)).then((detail) => {if (detail.allow) {this._doSave();@@ -1357,12 +1335,11 @@ export class OrAssetViewer extends subscribe(manager)(translate(i18next)(LitElem}protected async _doSave() {- const asset = this.asset;-- if (!asset) {+ if (!this._assetInfo) {return;}+ const asset = this._assetInfo.asset;this.saveBtnElem.disabled = true;this.wrapperElem.classList.add("saving");@@ -1371,78 +1348,113 @@ export class OrAssetViewer extends subscribe(manager)(translate(i18next)(LitElemthis.wrapperElem.classList.remove("saving");this.saveBtnElem.disabled = false;+ if (!this._assetInfo || this._assetInfo.asset !== asset) {+ // Asset has changed during save so ignore save result+ return;+ }+if (result.success) {- this._assetModified = false;+ this._assetInfo.modified = false;+ this.asset = undefined;this.assetId = result.assetId;- this.reloadAsset();}this.dispatchEvent(new OrAssetViewerSaveEvent(result));}protected _onAssetModified(validationResults: ValidatorResult[]) {- this._assetModified = true;- this._validationResults = validationResults;+ if (this._assetInfo) {+ this._assetInfo.modified = true;+ this._validationResults = validationResults;+ }}- public static generateGrid(shadowRoot: ShadowRoot | null) {- if (shadowRoot) {- const grid = shadowRoot.querySelector('#view-container');- if (grid) {- const rowHeight = parseInt(window.getComputedStyle(grid).getPropertyValue('grid-auto-rows'), 10);- const rowGap = parseInt(window.getComputedStyle(grid).getPropertyValue('grid-row-gap'), 10);- const items = shadowRoot.querySelectorAll('.panel');- if (items) {- items.forEach((item) => {- const content = item.querySelector('.panel-content-wrapper');- if (content) {- const rowSpan = Math.ceil((content.getBoundingClientRect().height + rowGap) / (rowHeight + rowGap));- (item as HTMLElement).style.gridRowEnd = "span " + rowSpan;- }- });- }+ _onEvent(event: SharedEvent) {- grid.addEventListener('scroll', (event: any) => {- const header = shadowRoot.querySelector('#asset-header');- if (header) {- if (event.target.scrollTop > 0) {- header.classList.add('scrolled')- } else {- header.classList.remove('scrolled')- }- }- });- }+ const processEvent = (event.eventType === "asset" && (event as AssetEvent).asset!.id === this.assetId) || (event.eventType === "attribute" && (event as AttributeEvent).attributeState!.ref!.id == this.assetId);++ if (!processEvent) {+ return;}- }- // TODO: Add debounce in here to minimise render calls- _onEvent(event: SharedEvent) {if (event.eventType === "asset") {+const asset = (event as AssetEvent).asset!;- if (asset.id !== this.assetId) {++ if (!this._assetInfo) {+ this.loadAssetInfo(asset)+ .then(assetInfo => this._assetInfo = assetInfo)+ .catch(reason => {+ // We can ignore this as it should indicate that the asset has changed+ });return;}- this.asset = asset;- this._loading = false;- return;++ if (this.editMode) {+ // Asset hasn't been modified yet so just re-render with new version of asset+ if (!this._assetInfo.modified) {+ this._assetInfo = undefined;+ this.loadAssetInfo(asset)+ .then(assetInfo => this._assetInfo = assetInfo)+ .catch(reason => {+ // We can ignore this as it should indicate that the asset has changed+ });+ return;+ }++ // Asset has changed whilst we're editing it so inform the user and reload+ showOkDialog("assetModified", i18next.t("assetModifiedMustRefresh")).then(() => {+ this._assetInfo = undefined;+ this.loadAssetInfo(asset)+ .then(assetInfo => this._assetInfo = assetInfo)+ .catch(reason => {+ // We can ignore this as it should indicate that the asset has changed+ });+ });+ } else {+ // Just reload the whole view+ this._assetInfo = undefined;+ this.loadAssetInfo(asset)+ .then(assetInfo => this._assetInfo = assetInfo)+ .catch(reason => {+ // We can ignore this as it should indicate that the asset has changed+ });+ }}if (event.eventType === "attribute") {+ if (!this._assetInfo) {+ return;+ }++ const asset = this._assetInfo.asset;+// Inject the attribute as we don't subscribe to events from individual attribute inputsconst attributeEvent = event as AttributeEvent;const attrName = attributeEvent.attributeState!.ref!.name!;- if (attributeEvent.attributeState!.deleted && this.asset && this.asset.attributes) {- delete this.asset.attributes[attrName];- this.asset = {...this.asset};- } else if (this.asset && this.asset.attributes && this.asset.attributes[attrName]) {- const attr = {...this.asset.attributes[attrName]};+ if (asset && asset.attributes && asset.attributes[attrName]) {++ // Remove any cached template+ delete this._assetInfo.attributeTemplateMap[attrName];++ // Update attribute within the asset+ const attr = {...asset.attributes[attrName]};attr.value = attributeEvent.attributeState!.value;attr.timestamp = attributeEvent.timestamp;- this.asset.attributes[attrName] = attr;- this.asset = {...this.asset};+ asset.attributes[attrName] = attr;++ if (this.editMode) {+ // Notify editor that attribute has changed+ const editor = this.shadowRoot!.getElementById("editor") as OrEditAssetPanel;++ if (editor) {+ editor.attributeUpdated(attrName);+ }+ } else {+ this.requestUpdate();+ }}}}@@ -1453,7 +1465,7 @@ export class OrAssetViewer extends subscribe(manager)(translate(i18next)(LitElemif (this.config) {config.viewerStyles = {...config.viewerStyles};- config.panels = {...config.panels};+ config.panels = config.panels ? [...config.panels] : [];const assetConfig = this.config.assetTypes && this.config.assetTypes.hasOwnProperty(asset.type!) ? this.config.assetTypes[asset.type!] : this.config.default;if (assetConfig) {@@ -1463,15 +1475,7 @@ export class OrAssetViewer extends subscribe(manager)(translate(i18next)(LitElem}if (assetConfig.panels) {- Object.entries(assetConfig.panels).forEach(([name, assetPanelConfig]) => {- if (config.panels!.hasOwnProperty(name)) {- const panelStyles = {...config.panels![name].panelStyles};- config.panels![name] = Object.assign(config.panels![name], {...assetPanelConfig});- config.panels![name].panelStyles = Object.assign(panelStyles, assetPanelConfig.panelStyles);- } else {- config.panels![name] = {...assetPanelConfig};- }- });+ config.panels = assetConfig.panels;}config.attributeViewProvider = assetConfig.attributeViewProvider || (this.config.default ? this.config.default.attributeViewProvider : undefined);diff --git a/ui/component/or-asset-viewer/src/or-edit-asset-panel.ts b/ui/component/or-asset-viewer/src/or-edit-asset-panel.tsindex 4a9e261ba..2d308fa36 100644--- a/ui/component/or-asset-viewer/src/or-edit-asset-panel.ts+++ b/ui/component/or-asset-viewer/src/or-edit-asset-panel.ts@@ -174,6 +174,7 @@ export class OrEditAssetPanel extends LitElement {protected asset!: Asset;protected attributeTemplatesAndValidators: TemplateAndValidator[] = [];+ protected changedAttributes: string[] = [];public static get styles() {return [@@ -183,6 +184,23 @@ export class OrEditAssetPanel extends LitElement {];}+ public attributeUpdated(attributeName: string) {+ if (!this.asset) {+ return;+ }+ this.changedAttributes.push(attributeName);++ // Request re-render+ this.requestUpdate();+ }++ shouldUpdate(changedProperties: PropertyValues): boolean {+ if (changedProperties.has("asset")) {+ this.changedAttributes = [];+ }+ return super.shouldUpdate(changedProperties);+ }+protected render() {const updatePublicRead = (publicRead: boolean) => {@@ -261,8 +279,8 @@ export class OrEditAssetPanel extends LitElement {return html`<div id="edit-wrapper">- ${getPanel("properties", {}, html`${properties}`) || ``}- ${getPanel("attribute_plural", {}, html`${attributes}`) || ``}+ ${getPanel("0", {type: "info", title: "properties"}, html`${properties}`) || ``}+ ${getPanel("1", {type: "info", title: "attribute_plural"}, html`${attributes}`) || ``}</div>`;}@@ -338,6 +356,14 @@ export class OrEditAssetPanel extends LitElement {}protected _onAttributeModified(attribute: Attribute<any>, newValue: any) {++ // Check if modification came from external change+ const index = this.changedAttributes.indexOf(attribute.name!);+ if (index > -1) {+ this.changedAttributes.splice(index, 1);+ return;+ }+attribute.value = newValue;attribute.timestamp = undefined; // Clear timestamp so server will set thisthis._onModified();diff --git a/ui/component/or-asset-viewer/src/style.ts b/ui/component/or-asset-viewer/src/style.tsindex 3d30e2f79..a544ab60c 100644--- a/ui/component/or-asset-viewer/src/style.ts+++ b/ui/component/or-asset-viewer/src/style.ts@@ -3,12 +3,18 @@ import {DefaultColor1, DefaultColor2, DefaultColor3, DefaultColor5, DefaultColor// language=CSSexport const panelStyles = css`+ .panelContainer {+ flex: 1 1 100%;+ box-sizing: border-box;+ min-width: 400px;+ }+.panel {background-color: var(--internal-or-asset-viewer-panel-color);border: 1px solid #e5e5e5;border-radius: 5px;- max-width: 100%;position: relative;+ margin: 10px 0;}.panel-content-wrapper {@@ -54,6 +60,7 @@ export const panelStyles = css`border-radius: 0;border-right: none;border-left: none;+ flex-basis: 100%;}}@@ -101,17 +108,17 @@ export const style = css`#view-container, #edit-container {flex: 0 1 auto;overflow: auto;- min-height: calc(100vh - 88px - var(--internal-or-header-height));}#view-container {+ flex: 1;margin-top: 0;box-sizing: border-box;- display: grid;- padding: 0 20px 20px;- grid-gap: 10px;- grid-template-columns: repeat(auto-fill, minmax(calc(50% - 5px),1fr));- grid-auto-rows: 5px;+ display: flex;+ flex-direction: row;+ flex-wrap: wrap;+ width: 100%;+ padding: 0 15px 15px;-webkit-animation: fadein 0.3s; /* Safari, Chrome and Opera > 12.1 */-moz-animation: fadein 0.3s; /* Firefox < 16 */@@ -158,7 +165,7 @@ export const style = css`}#asset-header {- padding: 20px 30px;+ padding: 20px 30px 15px;display: flex;flex: 0 0 auto;align-items: center;@@ -270,12 +277,6 @@ export const style = css`.tabletHidden {display: none;}-- #view-container {- grid-auto-rows: auto;- grid-template-columns: 100% !important;- min-height: unset;- }}@media screen and (max-width: 767px) {@@ -310,4 +311,14 @@ export const style = css`padding: 10px 0;}}++ @media (min-width: 767px) {+ .view-container {+ flex-wrap: nowrap;+ }+ .panelContainer {+ flex: 1 1 50%;+ padding: 0 5px;+ }+ }`;diff --git a/ui/component/or-attribute-history/src/index.ts b/ui/component/or-attribute-history/src/index.tsindex a0fccb522..1372edaaf 100644--- a/ui/component/or-attribute-history/src/index.ts+++ b/ui/component/or-attribute-history/src/index.ts@@ -104,8 +104,8 @@ const style = css`:host {--internal-or-attribute-history-background-color: var(--or-attribute-history-background-color, var(--or-app-color2, ${unsafeCSS(DefaultColor2)}));--internal-or-attribute-history-text-color: var(--or-attribute-history-text-color, var(--or-app-color3, ${unsafeCSS(DefaultColor3)}));- --internal-or-attribute-history-controls-margin: var(--or-attribute-history-controls-margin, 0 0 20px 0);- --internal-or-attribute-history-controls-margin-children: var(--or-attribute-history-controls-margin-children, 0 auto 20px auto);+ --internal-or-attribute-history-controls-margin: var(--or-attribute-history-controls-margin, 10px 0);+ --internal-or-attribute-history-controls-justify-content: var(--or-attribute-history-controls-justify-content, flex-end);--internal-or-attribute-history-graph-fill-color: var(--or-attribute-history-graph-fill-color, var(--or-app-color4, ${unsafeCSS(DefaultColor4)}));--internal-or-attribute-history-graph-fill-opacity: var(--or-attribute-history-graph-fill-opacity, 1);--internal-or-attribute-history-graph-line-color: var(--or-attribute-history-graph-line-color, var(--or-app-color4, ${unsafeCSS(DefaultColor4)}));@@ -118,7 +118,6 @@ const style = css`--internal-or-attribute-history-graph-point-hover-border-color: var(--or-attribute-history-graph-point-hover-border-color, var(--or-app-color4, ${unsafeCSS(DefaultColor4)}));--internal-or-attribute-history-graph-point-hover-radius: var(--or-attribute-history-graph-point-hover-radius, 4);--internal-or-attribute-history-graph-point-hover-border-width: var(--or-attribute-history-graph-point-hover-border-width, 2);-display: block;}@@ -156,16 +155,16 @@ const style = css`#controls {display: flex;flex-wrap: wrap;- justify-content: space-between;- margin: var(--internal-or-attribute-history-controls-margin);-+ justify-content: var(--internal-or-attribute-history-controls-justify-content);+ margin: var(--internal-or-attribute-history-controls-margin);flex-direction: row;}- #controls > * {- margin: var(--internal-or-attribute-history-controls-margin-children);+ #time-picker {+ width: 150px;+ padding: 0 5px;}-+#ending-controls {max-width: 100%;display: flex;@@ -178,7 +177,7 @@ const style = css`}#ending-date {- min-width: 0;+ width: 200px;}#chart-container {@@ -292,6 +291,7 @@ export class OrAttributeHistory extends translate(i18next)(LitElement) {}if (reloadData) {+ this._type = undefined;this._data = undefined;this._loadData();}@@ -307,7 +307,7 @@ export class OrAttributeHistory extends translate(i18next)(LitElement) {return html`<div id="container"><div id="controls">- <or-mwc-input .type="${InputType.SELECT}" ?disabled="${disabled}" .label="${i18next.t("timeframe")}" @or-mwc-input-changed="${(evt: OrInputChangedEvent) => this.period = evt.detail.value}" .value="${this.period}" .options="${this._getPeriodOptions()}"></or-mwc-input>+ <or-mwc-input id="time-picker" .type="${InputType.SELECT}" ?disabled="${disabled}" .label="${i18next.t("timeframe")}" @or-mwc-input-changed="${(evt: OrInputChangedEvent) => this.period = evt.detail.value}" .value="${this.period}" .options="${this._getPeriodOptions()}"></or-mwc-input><div id="ending-controls"><or-mwc-input id="ending-date" .type="${InputType.DATETIME}" ?disabled="${disabled}" label="${i18next.t("ending")}" .value="${this.toTimestamp}" @or-mwc-input-changed="${(evt: OrInputChangedEvent) => this._updateTimestamp(moment(evt.detail.value as string).toDate())}"></or-mwc-input><or-icon class="button button-icon" ?disabled="${disabled}" icon="chevron-left" @click="${() => this._updateTimestamp(this.toTimestamp!, false, 0)}"></or-icon>diff --git a/ui/component/or-mwc-components/src/or-mwc-dialog.ts b/ui/component/or-mwc-components/src/or-mwc-dialog.tsindex dbb763f0f..18fb3ad82 100644--- a/ui/component/or-mwc-components/src/or-mwc-dialog.ts+++ b/ui/component/or-mwc-components/src/or-mwc-dialog.ts@@ -54,12 +54,8 @@ declare global {}export async function showErrorDialog(errorMessage: string, hostElement?: HTMLElement) {- const deferred = new Util.Deferred<void>();-- showDialog(new OrMwcDialog()- .setHeading("error")- .setContent(- html`+ const title = "error";+ const content = html`<div><p><or-translate value="errorOccurred"></or-translate>${errorMessage ? html`@@ -70,18 +66,9 @@ export async function showErrorDialog(errorMessage: string, hostElement?: HTMLEl<or-translate .value="${errorMessage}"></or-translate>` : ``}</p>- </div>`- )- .setActions(- [{- actionName: "ok",- content: i18next.t("ok"),- default: true,- action: (dialog) => deferred.resolve()- }]- ), hostElement);-- await deferred.promise;+ </div>`;++ return showOkDialog(title, content, undefined, hostElement);}export async function showOkCancelDialog(title: string, content: string | TemplateResult, okText?: string, hostElement?: HTMLElement) {@@ -112,6 +99,29 @@ export async function showOkCancelDialog(title: string, content: string | Templareturn await deferred.promise;}+export async function showOkDialog(title: string, content: string | TemplateResult, okText?: string, hostElement?: HTMLElement) {++ const deferred = new Util.Deferred<boolean>();++ showDialog(+ new OrMwcDialog()+ .setContent(typeof(content) === "string" ? html`<p>${content}</p>` : content)+ .setActions(+ [+ {+ actionName: "ok",+ default: true,+ content: okText ? okText : i18next.t("ok"),+ action: () => deferred.resolve(true)+ }+ ]+ )+ .setHeading(title),+ hostElement);++ return await deferred.promise;+}+export function showDialog<T extends OrMwcDialog>(dialog: T, hostElement?: HTMLElement): T {if (!hostElement) {hostElement = OrMwcDialog.DialogHostElement || document.body;