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
Fix stale attribute panel (#2721)
Wouter Voorberg4311a2f3f91f
diff --git a/ui/app/manager/test/fixtures/data/assets.ts b/ui/app/manager/test/fixtures/data/assets.tsindex 593ca1cb9..3972bdac7 100644--- a/ui/app/manager/test/fixtures/data/assets.ts+++ b/ui/app/manager/test/fixtures/data/assets.ts@@ -98,6 +98,21 @@ export const preparedAssetsForInsights: Asset[] = [},];+/**+ * Asset with one predicted-datapoint attribute and one stored-datapoint+ * attribute, for tests that need to distinguish the two datapoint types.+ */+export const assetWithPredictedAndStoredDatapoints: Asset = {+ name: "Import Asset",+ type: "ThingAsset",+ realm: "smartcity",+ attributes: {+ ...commonAttrs,+ energyImportTotal: { name: "energyImportTotal", type: "number", meta: { hasPredictedDataPoints: true } },+ energyExportTotal: { name: "energyExportTotal", type: "number", meta: { storeDataPoints: true } },+ },+};+type AssetNames = (typeof assets)[number]["name"];export const assetPatches: Record<diff --git a/ui/app/manager/test/fixtures/pages/insights.ts b/ui/app/manager/test/fixtures/pages/insights.tsindex 0d74d9d93..d35d2ca27 100644--- a/ui/app/manager/test/fixtures/pages/insights.ts+++ b/ui/app/manager/test/fixtures/pages/insights.ts@@ -44,6 +44,15 @@ export class InsightsPage implements BasePage {return this.getDashboardGrid().evaluate((el: any) => [el.gridstack.cellWidth(), el.gridstack.getCellHeight()]);}+ /**+ * Gets the parent Gridstack item container for a given widget.+ * @param widget The `or-dashboard-widget-container` locator+ * @returns The locator for the Gridstack item container+ */+ getWidgetGSContainer(widget: Locator): Locator {+ return widget.locator("..").locator("..");+ }+/*** Gets the x and y coordinates for the specified widget* @requires the locator to reference a `or-dashboard-widget-container` to be able to get the Gridstack node@@ -51,7 +60,7 @@ export class InsightsPage implements BasePage {* @returns The x and y grid cell coordinates*/getWidgetLocation(widget: Locator): Promise<[number, number]> {- return widget.locator("..").locator("..").evaluate((el: any) => [el.gridstackNode.x, el.gridstackNode.y]);+ return this.getWidgetGSContainer(widget).evaluate((el: any) => [el.gridstackNode.x, el.gridstackNode.y]);}/**@@ -91,13 +100,16 @@ export class InsightsPage implements BasePage {* Resize a widget from its bottom right corner to the specified grid cell coordinates* @param widget The locator of the widget* @param to The grid cell coordinates to resize the widget to+ * @param options The resize options (e.g. force will skip dimension assertions)*/- async resizeWidgetTo(widget: Locator, [cellsWidth, cellsHeight] = [8, 8]) {+ async resizeWidgetTo(widget: Locator, [cellsWidth, cellsHeight] = [8, 8], { force } = { force: false }) {const [gridX, gridY] = await this.getWidgetLocation(widget);const [cellWidth, cellHeight] = await this.getGridCellDimensions();const [width, height] = [cellsWidth * cellWidth, cellsHeight * cellHeight];- await this.page.dragAndDrop(`.ui-resizable-handle.ui-resizable-se`, ".maingrid", {+ const grid = this.page.locator(".maingrid");+ await this.getWidgetGSContainer(widget).locator(".ui-resizable-handle.ui-resizable-se").dragTo(grid, {+ force,// We apply -cellWidth/Height / 2 as the handle causes the source position to be offsettargetPosition: {x: gridX * cellWidth + width - cellWidth / 2,@@ -106,6 +118,8 @@ export class InsightsPage implements BasePage {steps: 10,});+ if (force) return;+const bbox = await widget.boundingBox();// The dashboard dimensions should be equal to the specified cells,// or between the specified cells and the specified cells - 1 cell,@@ -127,4 +141,83 @@ export class InsightsPage implements BasePage {}await dialog.getByRole("button", { name: "Add" }).click();}++ /**+ * Selects a widget (opens its settings).+ * @param widget The `or-dashboard-widget-container` locator+ */+ async selectWidget(widget: Locator) {+ await widget.scrollIntoViewIfNeeded();+ await widget.locator(".panel-title").click();+ }++ /**+ * "Broken Reference" entries, both in chart widget legends and in the widget+ * settings attribute list.+ * @param options Optional locator options (e.g. scope via `has`)+ */+ getBrokenReferences(options?: any) {+ return this.page.locator('or-translate[value="brokenReference"]', options);+ }++ /**+ * Broken attribute rows shown in the widget settings attribute list.+ */+ getBrokenAttributeRows(options?: any) {+ return this.getWidgetSettings().locator(".attribute-list-item.broken", options);+ }++ /**+ * Opens the attribute picker for the replace ("swap-horizontal") action on a+ * given attribute row and returns the picker dialog locator.+ * @param row The attribute row locator (broken or healthy)+ */+ async openReplacePicker(row: Locator): Promise<Locator> {+ const button = row.locator('button[title="Replace attribute"]');+ await expect(button).toBeVisible();+ await button.dispatchEvent("click");+ const dialog = this.page.locator("#dialog");+ await expect(dialog).toBeVisible();+ return dialog;+ }++ /**+ * Sets the custom line/bar colour of the (single) attribute in the open widget+ * settings.+ * @param hex The colour to set, e.g. `#ff0000`+ */+ async setAttributeColor(hex: string) {+ const settings = this.getWidgetSettings();+ // Action buttons on a healthy row are only visible while the row is hovered+ await settings.locator(".attribute-list-item").first().hover();+ await settings.locator('button:has(or-icon[icon="palette"])').click();+ const colorInput = settings.locator('input[id^="chart-color-"]');+ await colorInput.evaluate((el, value) => {+ (el as HTMLInputElement).value = value;+ el.dispatchEvent(new Event("input", { bubbles: true }));+ }, hex);+ // The colour change is written to the config behind a debounce; wait for it+ // to flush so the colour persists when the dashboard is saved.+ await expect+ .poll(async () => (await this.getAttributeColors()).some(([, c]) => c?.toLowerCase() === hex.toLowerCase()))+ .toBe(true);+ }++ /**+ * Reads the current value of the (single) custom colour input in the open+ * widget settings.+ */+ getAttributeColorInput(): Locator {+ return this.getWidgetSettings().locator('input[id^="chart-color-"]');+ }++ /**+ * Reads the `attributeColors` config (`[AttributeRef, hex]` entries) off the+ * open chart/barchart settings element.+ */+ getAttributeColors(): Promise<[{ id?: string; name?: string }, string][]> {+ return this.getWidgetSettings()+ .locator("chart-settings, barchart-settings")+ .evaluate((el: any) => el?.widgetConfig?.attributeColors ?? []);+ }}diff --git a/ui/app/manager/test/insights.test.ts b/ui/app/manager/test/insights.test.tsindex ce8f6b9d5..4fafe73a0 100644--- a/ui/app/manager/test/insights.test.ts+++ b/ui/app/manager/test/insights.test.ts@@ -6,7 +6,9 @@ import {commonAttrs,getRGBColor,rgbToHex,+ assetWithPredictedAndStoredDatapoints,} from "./fixtures/data/assets.js";+import { users } from "./fixtures/data/users";import { expect } from "@openremote/test";test.use({ storageState: userStatePath });@@ -154,6 +156,124 @@ test("Create a Map widget with text thresholds", async ({ manager, shared, page,.toBe("000000");});+test("Replace broken chart references while preserving custom colors", async ({ manager, shared, page, insightsPage }) => {+ await shared.interceptResponse<Dashboard>("**/dashboard", (dashboard) => {+ if (dashboard) manager.dashboards.push(dashboard.id!);+ });++ // Provision the asset that the charts will reference (and that we later delete).+ // Reuse an existing insights asset; it has a "power" attribute with stored datapoints.+ const referencedAsset = assets[0];+ await manager.setup("smartcity", { assets: [referencedAsset] });+ await manager.goToRealmStartPage("smartcity");+ await manager.navigateToTab("Insights");++ // Build a Line Chart and a Bar Chart referencing "Power", colour them, and save+ await expect(insightsPage.getDashboardListItems()).toHaveCount(0);+ await page.click(".mdi-plus >> nth=0");+ await expect(insightsPage.getDashboardListItems()).toHaveCount(1);++ // Drop both widgets while the widget palette is available (no widget selected yet)+ await insightsPage.dragAndDropWidget("Line Chart", [0, 0]);+ await expect(insightsPage.getWidgets()).toHaveCount(1);+ await insightsPage.dragAndDropWidget("Bar Chart", [6, 0]);+ await expect(insightsPage.getWidgets()).toHaveCount(2);+ const lineWidget = insightsPage.getWidgets({ hasText: "Line Chart" }).first();+ const barWidget = insightsPage.getWidgets({ hasText: "Bar Chart" }).first();++ // Line chart: add the Power attribute and give it a custom red colour+ await insightsPage.selectWidget(lineWidget);+ await expect(insightsPage.getWidgetSettings({ hasText: "Line Chart" })).toBeVisible();+ await insightsPage.resizeWidgetTo(lineWidget, [6, 6]);+ await insightsPage.addAttributes(referencedAsset.name!, ["Power"]);+ await expect(insightsPage.getWidgetAttributes()).toHaveCount(1);+ await insightsPage.setAttributeColor("#ff0000");+ await expect(insightsPage.getAttributeColorInput()).toHaveValue("#ff0000");+ // Change the custom colour a second time; to make sure that works.+ await insightsPage.setAttributeColor("#0000ff");+ await expect(insightsPage.getAttributeColorInput()).toHaveValue("#0000ff");++ // Bar chart: add the Power attribute and give it a custom green colour+ await insightsPage.selectWidget(barWidget);+ await expect(insightsPage.getWidgetSettings({ hasText: "Bar Chart" })).toBeVisible();+ await insightsPage.resizeWidgetTo(barWidget, [12, 6], { force: true });+ await insightsPage.addAttributes(referencedAsset.name!, ["Power"]);+ await expect(insightsPage.getWidgetAttributes()).toHaveCount(1);+ await insightsPage.setAttributeColor("#00ff00");+ await expect(insightsPage.getAttributeColorInput()).toHaveValue("#00ff00");+ // Change the custom colour a second time; to make sure that works.+ await insightsPage.setAttributeColor("#ffc400");+ await expect(insightsPage.getAttributeColorInput()).toHaveValue("#ffc400");++ // Save the dashboard+ await page.getByRole("button", { name: "Save" }).click();+ await expect(page.getByRole("button", { name: "Save" })).toBeDisabled();++ // Delete the referenced asset, then reload to force the charts to re-resolve+ const adminToken = await manager.getAccessToken("master", "admin", users.admin.password!);+ await manager.deleteAssets({ headers: { Authorization: `Bearer ${adminToken}` } });+ await page.reload();+ await expect(insightsPage.getBuilder()).toBeVisible();+ await expect(insightsPage.getPreview()).toBeVisible();+ await expect(insightsPage.getPreview()).toHaveJSProperty("isLoading", false);+ await expect(insightsPage.getWidgets()).toHaveCount(2);++ // Both widget legends should show "Broken Reference" instead of dropping the attribute+ await expect(insightsPage.getBrokenReferences()).toHaveCount(2);++ // Both settings panels should show a broken attribute row with the replace action+ await insightsPage.selectWidget(lineWidget);+ await expect(insightsPage.getBrokenAttributeRows()).toHaveCount(1);+ await insightsPage.selectWidget(barWidget);+ await expect(insightsPage.getBrokenAttributeRows()).toHaveCount(1);++ // Create the replacement asset and replace the broken references+ await manager.createAsset(assetWithPredictedAndStoredDatapoints);++ // Line chart: the replace picker enables predicted attributes, so BOTH are offered.+ // Replace with the predicted-only "energyImportTotal".+ await insightsPage.selectWidget(lineWidget);+ const linePicker = await insightsPage.openReplacePicker(insightsPage.getBrokenAttributeRows().first());+ await linePicker.getByText("Import Asset").click();+ await expect(linePicker.getByText("Energy export total")).toBeVisible();+ await expect(linePicker.getByText("Energy import total")).toBeVisible();+ await linePicker.getByText("Energy import total").click();+ await linePicker.getByRole("button", { name: "Add" }).click();+ await expect(linePicker).toBeHidden();++ // Line chart broken row should now be replaced and the custom colour migrated to the new ref+ await expect(insightsPage.getBrokenAttributeRows()).toHaveCount(0);+ await expect(insightsPage.getWidgetAttributes()).toHaveCount(1);+ await expect(insightsPage.getWidgetAttributes().first()).toContainText("Import Asset");+ await expect(insightsPage.getAttributeColorInput()).toHaveValue("#0000ff");+ const lineColors = await insightsPage.getAttributeColors();+ expect(lineColors).toHaveLength(1);+ expect(lineColors[0][0].name).toBe("energyImportTotal");+ expect(lineColors[0][1]).toBe("#0000ff");++ // Bar chart: the replace picker does NOT enable predicted attributes, so the+ // predicted-only "energyImportTotal" must be absent; only the stored+ // "energyExportTotal" is offered.+ await insightsPage.selectWidget(barWidget);+ const barPicker = await insightsPage.openReplacePicker(insightsPage.getBrokenAttributeRows().first());+ await barPicker.getByText("Import Asset").click();+ await expect(barPicker.getByText("Energy export total")).toBeVisible();+ await expect(barPicker.getByText("Energy import total")).toHaveCount(0);+ await barPicker.getByText("Energy export total").click();+ await barPicker.getByRole("button", { name: "Add" }).click();+ await expect(barPicker).toBeHidden();++ // Bar chart: broken row should be replaced and the custom colour migrated to the new ref+ await expect(insightsPage.getBrokenAttributeRows()).toHaveCount(0);+ await expect(insightsPage.getWidgetAttributes()).toHaveCount(1);+ await expect(insightsPage.getWidgetAttributes().first()).toContainText("Import Asset");+ await expect(insightsPage.getAttributeColorInput()).toHaveValue("#ffc400");+ const barColors = await insightsPage.getAttributeColors();+ expect(barColors).toHaveLength(1);+ expect(barColors[0][0].name).toBe("energyExportTotal");+ expect(barColors[0][1]).toBe("#ffc400");+});+test.afterEach(async ({ manager }) => {await manager.cleanUp();});diff --git a/ui/app/shared/locales/en/or.json b/ui/app/shared/locales/en/or.jsonindex 801f4d34a..62ae5493f 100644--- a/ui/app/shared/locales/en/or.json+++ b/ui/app/shared/locales/en/or.json@@ -160,6 +160,7 @@"loading": "Loading...","noResults": "No results found.","noAssetsFound": "No assets found",+ "brokenReference": "Broken Reference","filterInvite": "Filter with at least 3 characters","location": "Location","longPressSetLoc": "Long press to set location",@@ -934,7 +935,9 @@"fill": "Fill","extendData": "Extend latest datapoint","lineColor": "Line color",- "barColor": "Bar color"+ "barColor": "Bar color",+ "replaceAttribute": "Replace attribute",+ "attributeAlreadyAdded": "This attribute is already added."},"south": "South","east": "East",diff --git a/ui/app/shared/locales/nl/or.json b/ui/app/shared/locales/nl/or.jsonindex 896fd7aec..b8d9d7bca 100644--- a/ui/app/shared/locales/nl/or.json+++ b/ui/app/shared/locales/nl/or.json@@ -155,6 +155,7 @@"loading": "Aan het laden...","noResults": "Geen resultaten gevonden.","noAssetsFound": "Geen assets gevonden",+ "brokenReference": "Gebroken verwijzing","filterInvite": "Filter met minsters 3 karakters","location": "Locatie","longPressSetLoc": "Druk lang op de kaart om locatie in te stellen",@@ -926,7 +927,9 @@"fill": "Vullen","extendData": "Verleng laatste datapunt","lineColor": "Lijnkleur",- "barColor": "Kleur van de balk"+ "barColor": "Kleur van de balk",+ "replaceAttribute": "Vervang atribuut",+ "attributeAlreadyAdded": "Dit atribuut is al toegevoegd."},"south": "Zuid","east": "Oost",diff --git a/ui/component/or-attribute-barchart/src/index.ts b/ui/component/or-attribute-barchart/src/index.tsindex c9161ab16..31eb503ac 100644--- a/ui/component/or-attribute-barchart/src/index.ts+++ b/ui/component/or-attribute-barchart/src/index.ts@@ -688,7 +688,16 @@ export class OrAttributeBarChart extends LitElement {${this.assetAttributes && this.assetAttributes.map(([assetIndex, attr], index) => {const asset: Asset | undefined = this.assets[assetIndex];if (!asset) {- return html`Error`;+ // Broken reference: kept in the legend to indicate the config is broken+ return html`+ <div class="attribute-list-item ${this.denseLegend ? "attribute-list-item-dense" : undefined}">+ <span style="margin-right: 10px; --or-icon-width: 20px;"><or-icon icon="link-variant-off"></or-icon></span>+ <div class="attribute-list-item-label ${this.denseLegend ? "attribute-list-item-label-dense" : undefined}">+ <or-translate style="font-size:12px; color:grey; font-style: italic;" value="brokenReference"></or-translate>+ <span style="font-size:12px; color:grey;">${Util.camelCaseToSentenceCase(attr.name) ?? ''}</span>+ </div>+ </div>+ `;}const colourIndex = index % this.colors.length;const color = this.attributeColors.find(x => x[0].id === asset.id && x[0].name === attr.name)?.[1];@@ -991,6 +1000,9 @@ export class OrAttributeBarChart extends LitElement {promises = this.assetAttributes.map(async ([assetIndex, attribute], index) => {const asset = this.assets[assetIndex];+ if (!asset) {+ return;+ }const shownOnRightAxis = !!this.attributeConfig?.rightAxisAttributes?.find(ar => ar.id === asset.id && ar.name === attribute.name);const color = this.attributeColors.find(x => x[0].id === asset.id && x[0].name === attribute.name)?.[1];const descriptors = AssetModelUtil.getAttributeAndValueDescriptors(asset.type, attribute.name, attribute);diff --git a/ui/component/or-chart/src/index.ts b/ui/component/or-chart/src/index.tsindex 4079ed8ff..c79db90e7 100644--- a/ui/component/or-chart/src/index.ts+++ b/ui/component/or-chart/src/index.ts@@ -779,24 +779,36 @@ export class OrChart extends translate(i18next)(LitElement) {${map(this.assetAttributes?.map(([assetIndex, attr], index) => {const asset: Asset | undefined = this.assets[assetIndex];const colourIndex = index % this.colors.length;+ if (!asset) {+ // Broken reference: kept in the legend to indicate the config is broken.+ return {broken: true, assetIndex, attr, axisNote: undefined, bgColor: "", label: attr.name ?? ""};+ }const color = this.attributeColors.find(x => x[0].id === asset.id && x[0].name === attr.name)?.[1];- const descriptors = AssetModelUtil.getAttributeAndValueDescriptors(asset!.type, attr.name, attr);- const label = Util.getAttributeLabel(attr, descriptors[0], asset!.type, true);- const axisNote = (this.attributeConfig.rightAxisAttributes?.find(ar => asset!.id === ar.id && attr.name === ar.name)) ? i18next.t('right') : undefined;+ const descriptors = AssetModelUtil.getAttributeAndValueDescriptors(asset.type, attr.name, attr);+ const label = Util.getAttributeLabel(attr, descriptors[0], asset.type, true);+ const axisNote = (this.attributeConfig.rightAxisAttributes?.find(ar => asset.id === ar.id && attr.name === ar.name)) ? i18next.t('right') : undefined;const bgColor = (color ?? this.colors[colourIndex]) || "";- return {assetIndex, attr, axisNote, bgColor, label};-- }).sort(Util.sortByString(x => x.label)), ({assetIndex, attr, axisNote, bgColor, label}) => html`+ return {broken: false, assetIndex, attr, axisNote, bgColor, label};++ }).sort(Util.sortByString(x => x.label)), (item) => item.broken ? html`+ <div class="attribute-list-item ${this.denseLegend ? 'attribute-list-item-dense' : undefined}">+ <span style="margin-right: 10px; --or-icon-width: 20px;"><or-icon icon="link-variant-off"></or-icon></span>+ <div class="attribute-list-item-label ${this.denseLegend ? 'attribute-list-item-label-dense' : undefined}">+ <or-translate style="font-size:12px; color:grey; font-style: italic;" value="brokenReference"></or-translate>+ <span style="font-size:12px; color:grey;">${Util.camelCaseToSentenceCase(item.attr.name) ?? ''}</span>+ </div>+ </div>+ ` : html`<div class="attribute-list-item ${this.denseLegend ? 'attribute-list-item-dense' : undefined}"- @mouseenter="${() => this._addDatasetHighlight({id: this.assets[assetIndex]!.id, name: attr.name})}"+ @mouseenter="${() => this._addDatasetHighlight({id: this.assets[item.assetIndex]!.id, name: item.attr.name})}"@mouseleave="${()=> this._removeDatasetHighlights()}">- <span style="margin-right: 10px; --or-icon-width: 20px;">${getAssetDescriptorIconTemplate(AssetModelUtil.getAssetDescriptor(this.assets[assetIndex]!.type!), undefined, undefined, bgColor.split('#')[1])}</span>+ <span style="margin-right: 10px; --or-icon-width: 20px;">${getAssetDescriptorIconTemplate(AssetModelUtil.getAssetDescriptor(this.assets[item.assetIndex]!.type!), undefined, undefined, item.bgColor.split('#')[1])}</span><div class="attribute-list-item-label ${this.denseLegend ? 'attribute-list-item-label-dense' : undefined}"><div style="display: flex; gap: 4px;">- <span style="font-size:12px; ${this.denseLegend ? 'margin-right: 8px' : undefined}">${this.assets[assetIndex].name}</span>- ${when(axisNote, () => html`<span style="font-size:12px; color:grey">(${axisNote})</span>`)}+ <span style="font-size:12px; ${this.denseLegend ? 'margin-right: 8px' : undefined}">${this.assets[item.assetIndex].name}</span>+ ${when(item.axisNote, () => html`<span style="font-size:12px; color:grey">(${item.axisNote})</span>`)}</div>- <span style="font-size:12px; color:grey;">${label}</span>+ <span style="font-size:12px; color:grey;">${item.label}</span></div></div>`)}@@ -1107,9 +1119,11 @@ export class OrChart extends translate(i18next)(LitElement) {}protected _getSelectedAttributes() {- return this.assetAttributes.map(([assetIndex, attr]) => {- return {id: this.assets[assetIndex].id, name: attr.name};- });+ return this.assetAttributes+ .filter(([assetIndex]) => !!this.assets[assetIndex])+ .map(([assetIndex, attr]) => {+ return {id: this.assets[assetIndex].id, name: attr.name};+ });}protected _cleanup() {@@ -1272,6 +1286,9 @@ export class OrChart extends translate(i18next)(LitElement) {const lineData: LineChartData[] = [];const asset = this.assets[assetIndex];+ if (!asset) {+ return;+ }const shownOnRightAxis = !!this.attributeConfig?.rightAxisAttributes?.find(ar => ar.id === asset.id && ar.name === attribute.name);const smooth = !!this.attributeConfig?.smoothAttributes?.find(ar => ar.id === asset.id && ar.name === attribute.name);const stacked = this.stacked;diff --git a/ui/component/or-dashboard-builder/src/panels/attributes-chart-panel.ts b/ui/component/or-dashboard-builder/src/panels/attributes-chart-panel.tsindex 90c9032cc..ff073a302 100644--- a/ui/component/or-dashboard-builder/src/panels/attributes-chart-panel.ts+++ b/ui/component/or-dashboard-builder/src/panels/attributes-chart-panel.ts@@ -38,6 +38,10 @@ export class AttributesChartPanel extends AttributesPanel {protected _getAttributeActionsTemplate(asset: Asset, attributeRef: AttributeRef): TemplateResult {return html`<div class="attribute-list-item-actions">+ <!-- Replace attribute button -->+ <button class="button-action" title="${i18next.t('dashboard.replaceAttribute')}" @click="${() => this.replaceWidgetAttribute(attributeRef)}">+ <or-icon icon="swap-horizontal"></or-icon>+ </button><!-- Remove attribute button --><button class="button-action" title="${i18next.t('delete')}" @click="${() => this.removeWidgetAttribute(attributeRef)}"><or-icon icon="close-circle"></or-icon>diff --git a/ui/component/or-dashboard-builder/src/panels/attributes-panel.ts b/ui/component/or-dashboard-builder/src/panels/attributes-panel.tsindex 6417c5a41..0ab29d31d 100644--- a/ui/component/or-dashboard-builder/src/panels/attributes-panel.ts+++ b/ui/component/or-dashboard-builder/src/panels/attributes-panel.ts@@ -74,6 +74,22 @@ export class AttributesSelectEvent extends CustomEvent<{ assets: Asset[], attrib}}+export class AttributeReplaceEvent extends CustomEvent<{ oldRef: AttributeRef, newRef: AttributeRef }> {++ public static readonly NAME = "attribute-replace";++ constructor(oldRef: AttributeRef, newRef: AttributeRef) {+ super(AttributeReplaceEvent.NAME, {+ bubbles: true,+ composed: true,+ detail: {+ oldRef: oldRef,+ newRef: newRef+ }+ });+ }+}+const styling = css`#attribute-list {overflow: auto;@@ -171,6 +187,21 @@ const styling = css`.button-action:hover {--or-icon-fill: var(--or-icon-fill--hover, var(--or-app-color4));}++ .attribute-list-item.broken {+ opacity: 0.7;+ }++ .attribute-list-item.broken .attribute-list-item-label > .broken-label {+ color: var(--or-app-color5, ${unsafeCSS(DefaultColor5)});+ font-style: italic;+ }++ .attribute-list-item.broken .attribute-list-item-actions,+ .attribute-list-item.broken .button-action {+ visibility: visible;+ position: unset;+ }`;@customElement("attributes-panel")@@ -203,6 +234,9 @@ export class AttributesPanel extends LitElement {@state()protected loadedAssets: Asset[] = [];+ @state()+ protected _assetsLoading = false;+static get styles(): CSSResult[] {return [styling, style];}@@ -215,6 +249,7 @@ export class AttributesPanel extends LitElement {this.attributeRefs = [];}if (changedProps.has("attributeRefs") && this.attributeRefs) {+ this._assetsLoading = true;this.loadAssets().then(assets => {// Only dispatch event when it CHANGED, so not from 'undefined' to [];@@ -222,6 +257,8 @@ export class AttributesPanel extends LitElement {this.dispatchEvent(new AttributesSelectEvent(assets, this.attributeRefs));}+ }).finally(() => {+ this._assetsLoading = false;});}}@@ -236,6 +273,35 @@ export class AttributesPanel extends LitElement {}}+ protected replaceWidgetAttribute(oldRef: AttributeRef) {+ const dialog = showDialog(new OrAssetAttributePicker()+ .setMultiSelect(false)+ .setShowOnlyDatapointAttrs(this.onlyDataAttrs)+ .setShowPredictedDataAttrs(this.includePredictedDataAttrs)+ .setAttributeFilter(this.attributeFilter));+ dialog.addEventListener(OrAssetAttributePickerPickedEvent.NAME, (event: CustomEvent) => {+ const newRef: AttributeRef | undefined = (event.detail as AttributeRef[])?.[0];+ if (!newRef) {+ return;+ }+ const index = this.attributeRefs.findIndex(ar => ar.id === oldRef.id && ar.name === oldRef.name);+ if (index < 0) {+ return;+ }+ // Guard against creating a duplicate reference.+ if (this.attributeRefs.some(ar => ar.id === newRef.id && ar.name === newRef.name)) {+ showSnackbar(undefined, "dashboard.attributeAlreadyAdded");+ return;+ }+ // Notify listeners first so they can migrate per-attribute config (colors, axis, ...) before+ // the list change propagates as a regular attribute-select event.+ this.dispatchEvent(new AttributeReplaceEvent(oldRef, newRef));+ const updated = [...this.attributeRefs];+ updated[index] = newRef;+ this.attributeRefs = updated;+ });+ }+protected async loadAssets(): Promise<Asset[]> {if(this.attributeRefs.filter(ar => !this.getLoadedAsset(ar)).length > 0) {const assets = await this.fetchAssets(this.attributeRefs);@@ -287,15 +353,15 @@ export class AttributesPanel extends LitElement {${when(this.attributeRefs.length > 0, () => html`<div id="attribute-list">- ${guard([this.attributeRefs, this.loadedAssets, this.attributeActionCallback, this.attributeLabelCallback], () => html`+ ${guard([this.attributeRefs, this.loadedAssets, this.attributeActionCallback, this.attributeLabelCallback, this._assetsLoading], () => html`${map(this.attributeRefs.map(attributeRef => {const asset = this.getLoadedAsset(attributeRef);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 { asset, attribute, attributeRef, label };-- }).sort(Util.sortByString(x => x.label)), ({asset, attribute, attributeRef, label}) => {++ }).sort(Util.sortByString(x => x.label || x.attributeRef.name || "")), ({asset, attribute, attributeRef, label}) => {if (asset && attribute && attributeRef && label) {return html`<div class="attribute-list-item">@@ -317,9 +383,23 @@ export class AttributesPanel extends LitElement {${this._getAttributeActionsTemplate(asset, attributeRef)}</div>`;- } else {- return undefined;}+ // Reference points to an attribute that no longer resolves.+ if (!this._assetsLoading && attributeRef) {+ return html`+ <div class="attribute-list-item broken">+ <div class="attribute-list-item-icon">+ <or-icon icon="link-variant-off"></or-icon>+ </div>+ <div class="attribute-list-item-label">+ <or-translate class="broken-label" value="brokenReference"></or-translate>+ <span style="color:grey;">${Util.camelCaseToSentenceCase(attributeRef.name) ?? ""}</span>+ </div>+ ${this._getBrokenAttributeActionsTemplate(attributeRef)}+ </div>+ `;+ }+ return undefined;})}`)}</div>@@ -352,6 +432,19 @@ export class AttributesPanel extends LitElement {`;}+ protected _getBrokenAttributeActionsTemplate(attributeRef: AttributeRef): TemplateResult {+ return html`+ <div class="attribute-list-item-actions">+ <button class="button-action" title="${i18next.t("dashboard.replaceAttribute")}" @click="${() => this.replaceWidgetAttribute(attributeRef)}">+ <or-icon icon="swap-horizontal"></or-icon>+ </button>+ <button class="button-action" title="${i18next.t("delete")}" @click="${() => this.removeWidgetAttribute(attributeRef)}">+ <or-icon icon="close-circle"></or-icon>+ </button>+ </div>+ `;+ }+protected _getAttributeActionTemplate(action: AttributeAction, asset: Asset, attributeRef: AttributeRef): TemplateResult {const styles = styleMap({"--or-icon-fill": action.active ? action?.color ?? "inherit" : "inherit",diff --git a/ui/component/or-dashboard-builder/src/settings/barchart-settings.ts b/ui/component/or-dashboard-builder/src/settings/barchart-settings.tsindex 9129a7668..12eb90262 100644--- a/ui/component/or-dashboard-builder/src/settings/barchart-settings.ts+++ b/ui/component/or-dashboard-builder/src/settings/barchart-settings.ts@@ -23,7 +23,7 @@ import {WidgetSettings} from "../util/widget-settings";import "../panels/attributes-chart-panel";import "../util/settings-panel";import {i18next} from "@openremote/or-translate";-import {AttributeAction, AttributeActionEvent, AttributesSelectEvent} from "../panels/attributes-panel";+import {AttributeAction, AttributeActionEvent, AttributeReplaceEvent, AttributesSelectEvent} from "../panels/attributes-panel";import {Asset, AssetDescriptor, Attribute, AttributeRef} from "@openremote/model";import {BarChartWidgetConfig} from "../widgets/barchart-widget";import {InputType, OrInputChangedEvent} from "@openremote/or-mwc-components/or-mwc-input";@@ -90,7 +90,7 @@ export class BarChartSettings extends WidgetSettings {let color = this.widgetConfig.attributeColors?.find(a => a[0].id === asset.id && a[0].name === attribute.name)?.[1]?.replace("#", "");if(!color) {const index = this.widgetConfig.attributeRefs?.findIndex(ref => ref.id === asset.id && ref.name === attribute.name);- if(index >= 0) color = OrChart.DEFAULT_COLORS?.[index]?.replace("#", "");+ if(index >= 0) color = OrChart.DEFAULT_COLORS?.[index % OrChart.DEFAULT_COLORS.length]?.replace("#", "");}return html`<span>${getAssetDescriptorIconTemplate(descriptor, undefined, undefined, color)}</span>`;};@@ -101,7 +101,7 @@ export class BarChartSettings extends WidgetSettings {let customColor = false;if (!color) {const index = this.widgetConfig?.attributeRefs?.findIndex(ref => ref.id === attributeRef.id && ref.name === attributeRef.name);- if (index >= 0) color = OrAttributeBarChart.DEFAULT_COLORS[index];+ if (index >= 0) color = OrAttributeBarChart.DEFAULT_COLORS[index % OrAttributeBarChart.DEFAULT_COLORS.length];} else {customColor = true;}@@ -158,6 +158,7 @@ export class BarChartSettings extends WidgetSettings {<attributes-chart-panel .attributeRefs="${this.widgetConfig.attributeRefs}" multi onlyDataAttrs .attributeFilter="${attributeFilter}" style="padding-bottom: 12px;".attributeIconCallback=${attributeIconCallback} .attributeActionCallback="${attributeActionCallback}"@attribute-action="${(ev: AttributeActionEvent) => this.onAttributeAction(ev)}"+ @attribute-replace="${(ev: AttributeReplaceEvent) => this.onAttributeReplace(ev)}"@attribute-select="${(ev: AttributesSelectEvent) => this.onAttributesSelect(ev)}"></attributes-chart-panel></settings-panel>@@ -376,7 +377,7 @@ export class BarChartSettings extends WidgetSettings {// Add colorsthis.widgetConfig.attributeColors ??= [];ev.detail.attributeRefs.forEach(((attrRef, index) => {- const color = this.widgetConfig.attributeColors.find(x => x[0].id === attrRef.id && x[0].name === ref.name);+ const color = this.widgetConfig.attributeColors.find(x => x[0].id === attrRef.id && x[0].name === attrRef.name);if(!color) {const newColor = OrAttributeBarChart.DEFAULT_COLORS[index] ?? "#000000";this.widgetConfig.attributeColors.push([attrRef, newColor]);@@ -398,6 +399,33 @@ export class BarChartSettings extends WidgetSettings {this.notifyConfigUpdate();}+ /**+ * Handles an in-place replacement of an {@link AttributeRef}. All per-attribute configuration+ * (aggregation method, alignment, custom color, ...) is migrated from the old reference to the+ * new one, so the new attribute inherits the full configuration of the one it replaces.+ */+ protected onAttributeReplace(ev: AttributeReplaceEvent) {+ const {oldRef, newRef} = ev.detail;+ const matches = (ar: AttributeRef) => ar.id === oldRef.id && ar.name === oldRef.name;++ // Migrate the attribute settings categories (aggregation methods, alignment, ...)+ const settings = this.widgetConfig.attributeSettings;+ (Object.keys(settings) as (keyof typeof settings)[]).forEach(key => {+ settings[key] = settings[key]!.map((ar: AttributeRef) => matches(ar) ? {id: newRef.id, name: newRef.name} : ar);+ });++ // Migrate the custom color, if any+ this.widgetConfig.attributeColors = (this.widgetConfig.attributeColors ?? [])+ .map(entry => matches(entry[0]) ? [{id: newRef.id, name: newRef.name}, entry[1]] : entry);++ // Swap the reference in place, keeping its position in the list+ const index = this.widgetConfig.attributeRefs.findIndex(matches);+ if (index >= 0) {+ this.widgetConfig.attributeRefs[index] = {id: newRef.id, name: newRef.name};+ }+ this.notifyConfigUpdate();+ }+protected removeFromAttributeSettings(attributeRef: AttributeRef) {const settings = this.widgetConfig.attributeSettings;(Object.keys(settings) as (keyof typeof settings)[]).forEach(key => {@@ -457,7 +485,7 @@ export class BarChartSettings extends WidgetSettings {protected removeFromAttributeColors(attributeRef: AttributeRef) {- this.widgetConfig.attributeColors = this.widgetConfig.attributeColors.filter(+ this.widgetConfig.attributeColors = (this.widgetConfig.attributeColors ?? []).filter(([ref, _]) => ref.id !== attributeRef.id || ref.name !== attributeRef.name);}diff --git a/ui/component/or-dashboard-builder/src/settings/chart-settings.ts b/ui/component/or-dashboard-builder/src/settings/chart-settings.tsindex 1eb687abb..5d71640fb 100644--- a/ui/component/or-dashboard-builder/src/settings/chart-settings.ts+++ b/ui/component/or-dashboard-builder/src/settings/chart-settings.ts@@ -25,7 +25,7 @@ import "../util/settings-panel";import {i18next} from "@openremote/or-translate";import debounce from "lodash.debounce";import {AttributesChartPanel} from "../panels/attributes-chart-panel";-import {AttributeAction, AttributeActionEvent, AttributesSelectEvent} from "../panels/attributes-panel";+import {AttributeAction, AttributeActionEvent, AttributeReplaceEvent, AttributesSelectEvent} from "../panels/attributes-panel";import {Asset, AssetDatapointIntervalQuery, AssetDatapointIntervalQueryFormula, AssetDescriptor, Attribute, AttributeRef} from "@openremote/model";import {ChartWidgetConfig} from "../widgets/chart-widget";import {InputType, OrInputChangedEvent} from "@openremote/or-mwc-components/or-mwc-input";@@ -85,7 +85,7 @@ export class ChartSettings extends WidgetSettings {let color = this.widgetConfig.attributeColors?.find(a => a[0].id === asset.id && a[0].name === attribute.name)?.[1]?.replace('#', '');if(!color) {const index = this.widgetConfig.attributeRefs?.findIndex(ref => ref.id === asset.id && ref.name === attribute.name);- if(index >= 0) color = OrChart.DEFAULT_COLORS?.[index]?.replace('#', '');+ if(index >= 0) color = OrChart.DEFAULT_COLORS?.[index % OrChart.DEFAULT_COLORS.length]?.replace('#', '');}return html`<span>${getAssetDescriptorIconTemplate(descriptor, undefined, undefined, color)}</span>`;};@@ -100,7 +100,7 @@ export class ChartSettings extends WidgetSettings {let customColor = false;if (!color) {const index = this.widgetConfig?.attributeRefs?.findIndex(ref => ref.id === attributeRef.id && ref.name === attributeRef.name);- if (index >= 0) color = OrChart.DEFAULT_COLORS?.[index];+ if (index >= 0) color = OrChart.DEFAULT_COLORS?.[index % OrChart.DEFAULT_COLORS.length];} else {customColor = true;}@@ -171,6 +171,7 @@ export class ChartSettings extends WidgetSettings {<attributes-chart-panel .attributeRefs="${this.widgetConfig.attributeRefs}" multi onlyDataAttrs includePredictedDataAttrs .attributeFilter="${attributeFilter}" style="padding-bottom: 12px;".attributeIconCallback="${attributeIconCallback}" .attributeActionCallback="${attributeActionCallback}"@attribute-action="${(ev: AttributeActionEvent) => this.onAttributeAction(ev)}"+ @attribute-replace="${(ev: AttributeReplaceEvent) => this.onAttributeReplace(ev)}"@attribute-select="${(ev: AttributesSelectEvent) => this.onAttributesSelect(ev)}"></attributes-chart-panel></settings-panel>@@ -393,6 +394,36 @@ export class ChartSettings extends WidgetSettings {this.notifyConfigUpdate();}+ /**+ * Handles an in-place replacement of an {@link AttributeRef}. All per-attribute configuration+ * (axis assignment, smooth/stepped/area/faint/extended flags and custom color) is migrated from+ * the old reference to the new one, so the new attribute inherits the full configuration of the+ * one it replaces.+ */+ protected onAttributeReplace(ev: AttributeReplaceEvent) {+ const {oldRef, newRef} = ev.detail;+ const matches = (ar: AttributeRef) => ar.id === oldRef.id && ar.name === oldRef.name;++ // Migrate the attribute config categories (rightAxis, smooth, stepped, area, faint, extended, ...)+ const config = this.widgetConfig.attributeConfig;+ if (config) {+ (Object.keys(config) as (keyof typeof config)[]).forEach(key => {+ config[key] = config[key]?.map((ar: AttributeRef) => matches(ar) ? {id: newRef.id, name: newRef.name} : ar);+ });+ }++ // Migrate the custom color, if any+ this.widgetConfig.attributeColors = (this.widgetConfig.attributeColors ?? [])+ .map(entry => matches(entry[0]) ? [{id: newRef.id, name: newRef.name}, entry[1]] : entry);++ // Swap the reference in place, keeping its position in the list+ const index = this.widgetConfig.attributeRefs.findIndex(matches);+ if (index >= 0) {+ this.widgetConfig.attributeRefs[index] = {id: newRef.id, name: newRef.name};+ }+ this.notifyConfigUpdate();+ }+protected removeFromAttributeConfig(attributeRef: AttributeRef) {const config = this.widgetConfig.attributeConfig;if(config) {diff --git a/ui/component/or-dashboard-builder/src/widgets/barchart-widget.ts b/ui/component/or-dashboard-builder/src/widgets/barchart-widget.tsindex 622aa2c2b..cec4ac5d7 100644--- a/ui/component/or-dashboard-builder/src/widgets/barchart-widget.ts+++ b/ui/component/or-dashboard-builder/src/widgets/barchart-widget.ts@@ -175,8 +175,9 @@ export class BarChartWidget extends OrAssetWidget {this.assetAttributes = attributeRefs?.map((attrRef: AttributeRef) => {const assetIndex = assets.findIndex(asset => asset.id === attrRef.id);const foundAsset = assetIndex >= 0 ? assets[assetIndex] : undefined;- return foundAsset && foundAsset.attributes ? [assetIndex, foundAsset.attributes[attrRef.name!]] : undefined;- }).filter((indexAndAttr: any) => !!indexAndAttr) as [number, Attribute<any>][];+ const attribute = foundAsset?.attributes?.[attrRef.name!];+ return attribute ? [assetIndex, attribute] : [-1, { name: attrRef.name } as Attribute<any>];+ }) as [number, Attribute<any>][];}).catch(e => {this._error = e.message;}).finally(() => {diff --git a/ui/component/or-dashboard-builder/src/widgets/chart-widget.ts b/ui/component/or-dashboard-builder/src/widgets/chart-widget.tsindex 9ea1a6b93..8b0ddde5c 100644--- a/ui/component/or-dashboard-builder/src/widgets/chart-widget.ts+++ b/ui/component/or-dashboard-builder/src/widgets/chart-widget.ts@@ -196,8 +196,9 @@ export class ChartWidget extends OrAssetWidget {this.assetAttributes = attributeRefs?.map((attrRef: AttributeRef) => {const assetIndex = assets.findIndex((asset) => asset.id === attrRef.id);const foundAsset = assetIndex >= 0 ? assets[assetIndex] : undefined;- return foundAsset && foundAsset.attributes ? [assetIndex, foundAsset.attributes[attrRef.name!]] : undefined;- }).filter((indexAndAttr: any) => !!indexAndAttr) as [number, Attribute<any>][];+ const attribute = foundAsset?.attributes?.[attrRef.name!];+ return attribute ? [assetIndex, attribute] : [-1, { name: attrRef.name } as Attribute<any>];+ }) as [number, Attribute<any>][];}).catch(e => {this._error = e.message;}).finally(() => {