Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

UI: Add pagination support to asset tree (#2161)

Martin Peeters4c0d6a1560d8
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
index 1ca9597a6..b6988927a 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
@@ -1307,9 +1307,6 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
if (query.userIds != null && query.userIds.length == 0) {
return Collections.emptyList();
}
- if (query.parents != null && query.parents.length == 0) {
- return Collections.emptyList();
- }
// Default to order by creation date if the query may return multiple results
if (query.orderBy == null && query.ids == null)
@@ -1715,27 +1712,32 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
if (query.parents != null) {
sb.append(" and (");
- boolean isFirst = true;
- for (ParentPredicate pred : query.parents) {
- if (!isFirst) {
- sb.append(" or (");
- } else {
- sb.append("(");
- }
- isFirst = false;
+ if(query.parents.length == 0) {
+ sb.append("A.PARENT_ID is null");
+ } else {
+ boolean isFirst = true;
- if (level == 1 && pred.id != null) {
- final int pos = binders.size() + 1;
- sb.append("A.PARENT_ID = ?").append(pos);
- binders.add((em, st) -> st.setParameter(pos, pred.id));
- } else if (level == 1) {
- sb.append("A.PARENT_ID is null");
- } else {
- sb.append("true");
- }
+ for (ParentPredicate pred : query.parents) {
+ if (!isFirst) {
+ sb.append(" or (");
+ } else {
+ sb.append("(");
+ }
+ isFirst = false;
+
+ if (level == 1 && pred.id != null) {
+ final int pos = binders.size() + 1;
+ sb.append("A.PARENT_ID = ?").append(pos);
+ binders.add((em, st) -> st.setParameter(pos, pred.id));
+ } else if (level == 1) {
+ sb.append("A.PARENT_ID is null");
+ } else {
+ sb.append("true");
+ }
- sb.append(")");
+ sb.append(")");
+ }
}
sb.append(")");
diff --git a/model/src/main/java/org/openremote/model/asset/AssetTreeAsset.java b/model/src/main/java/org/openremote/model/asset/AssetTreeAsset.java
index d8cf577cf..293a6229e 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetTreeAsset.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetTreeAsset.java
@@ -31,14 +31,18 @@ public class AssetTreeAsset {
String id;
String name;
String type;
+ String parentId;
+ String[] path;
boolean hasChildren;
Date createdOn;
- public AssetTreeAsset(String id, String name, String type, boolean hasChildren, Date createdOn) {
+ public AssetTreeAsset(String id, String name, String type, String parentId, String[] path, boolean hasChildren, Date createdOn) {
this.id = id;
this.name = name;
this.type = type;
+ this.parentId = parentId;
+ this.path = path;
this.hasChildren = hasChildren;
this.createdOn = createdOn;
}
@@ -67,6 +71,22 @@ public class AssetTreeAsset {
this.type = type;
}
+ public String getParentId() {
+ return parentId;
+ }
+
+ public void setParentId(String parentId) {
+ this.parentId = parentId;
+ }
+
+ public String[] getPath() {
+ return path;
+ }
+
+ public void setPath(String[] path) {
+ this.path = path;
+ }
+
public boolean hasChildren() {
return hasChildren;
}
@@ -92,7 +112,7 @@ public class AssetTreeAsset {
* @return The optimized asset tree asset.
*/
public static AssetTreeAsset fromAsset(Asset<?> asset, Boolean hasChildren) {
- return new AssetTreeAsset(asset.getId(), asset.getName(), asset.getType(), hasChildren, asset.getCreatedOn());
+ return new AssetTreeAsset(asset.getId(), asset.getName(), asset.getType(), asset.getParentId(), asset.getPath(), hasChildren, asset.getCreatedOn());
}
@Override
diff --git a/ui/app/manager/src/pages/page-assets.ts b/ui/app/manager/src/pages/page-assets.ts
index 3502c1e9f..87ded9d5e 100644
--- a/ui/app/manager/src/pages/page-assets.ts
+++ b/ui/app/manager/src/pages/page-assets.ts
@@ -367,7 +367,7 @@ export class PageAssets extends Page<AssetsStateKeyed> {
event.detail.allow = false;
this._confirmContinue(() => {
- this._onAssetSelectionChanged(true, event.detail.detail.newNodes.map((node) => node.asset.id!));
+ this._onAssetSelectionChanged(true, event.detail.detail.newNodes?.map((node) => node.asset.id!));
});
}
@@ -393,6 +393,7 @@ export class PageAssets extends Page<AssetsStateKeyed> {
} else {
this._assetIds = assetIds;
if (this._viewer) {
+ console.debug(`Asset viewer is now showing asset ${assetIds && assetIds.length === 1 ? assetIds[0] : 'undefined'}`);
this._viewer.assetId = assetIds && assetIds.length === 1 ? assetIds[0] : undefined;
}
this._updateRoute(false);
diff --git a/ui/app/manager/test/assets.test.ts b/ui/app/manager/test/assets.test.ts
index a60a40fa5..646c3bf54 100644
--- a/ui/app/manager/test/assets.test.ts
+++ b/ui/app/manager/test/assets.test.ts
@@ -34,63 +34,6 @@ assets.forEach(({ type, name, attributes }) => {
await expect(page.locator(`text=${name}`)).toHaveCount(1);
});
- /**
- * @given Assets are set up in the "smartcity" realm
- * @when Logging in to the OpenRemote "smartcity" realm
- * @and Navigating to the "asset" tab
- * @and Searching for the asset by name
- * @and Selecting the asset from the list
- * @then The asset detail page is displayed
- */
- test(`Search for and select a ${name} asset`, async ({ page, manager, assetTree }) => {
- await manager.setup("smartcity", { assets });
- await manager.goToRealmStartPage("smartcity");
- await manager.navigateToTab("asset");
- await assetTree.fillFilterInput(name);
- await expect(assetTree.getAssetNodes()).toHaveCount(1);
- await page.click(`text=${name}`);
- await expect(page.locator(`#asset-header`, { hasText: name })).toBeVisible();
- });
-
- /**
- * @given Assets are set up in the "smartcity" realm
- * @when Logging in to the OpenRemote "smartcity" realm
- * @and Navigating to the "asset" tab
- * @and Searching for the asset by ID
- * @and Selecting the asset from the list
- * @then The asset detail page is displayed
- */
- test(`Search by Asset ID and select the ${name} asset`, async ({ page, manager, assetTree }) => {
- await manager.setup("smartcity", { assets });
- const id = manager.assets.find(asset => asset.name === name)?.id;
- expect(id).toBeDefined();
- await manager.goToRealmStartPage("smartcity");
- await manager.navigateToTab("asset");
- await assetTree.fillFilterInput(id!);
- await expect(assetTree.getAssetNodes()).toHaveCount(1);
- await page.click(`text=${name}`);
- await expect(page.locator(`#asset-header`, { hasText: name })).toBeVisible();
- })
-
- /**
- * @given Assets are set up in the "smartcity" realm
- * @when Logging in to the OpenRemote "smartcity" realm
- * @and Navigating to the "/assets/false/{id}" page directly
- * @then The filter should contain the ID as input
- * @and The asset list should contain the asset with the given ID
- * @and The asset detail page is displayed
- */
- test(`Open browser tab directly to the ${name} asset`, async ({ page, manager, assetsPage, assetTree }) => {
- await manager.setup("smartcity", { assets });
- const id = manager.assets.find(asset => asset.name === name)?.id;
- expect(id).toBeDefined();
- await assetsPage.gotoAssetId("smartcity", id!);
- await expect(assetTree.getFilterInput()).toHaveValue(id!);
- await expect(assetTree.getAssetNodes()).toHaveCount(1);
- await expect(assetTree.getSelectedNodes()).toHaveCount(1);
- await expect(page.locator(`#asset-header`, { hasText: name })).toBeVisible();
- })
-
/**
* @given Assets are set up in the "smartcity" realm
* @when Logging in to the OpenRemote "smartcity" realm
@@ -242,6 +185,8 @@ test("Add all primitive configuration items", async ({ page, manager, assetViewe
}
});
+// TODO: Add test for the "Load more" button, by modifying the LIMIT variable in or-asset-tree
+
test.fixme("Add all complex configuration items", async ({ page, manager, shared }) => {});
/**
@@ -256,8 +201,8 @@ test("Delete specified assets and verify they are removed", async ({ page, manag
await manager.setup("smartcity", { assets });
await manager.goToRealmStartPage("smartcity");
await manager.navigateToTab("Assets");
- await assetsPage.deleteSelectedAsset("Battery");
- await assetsPage.deleteSelectedAsset("Solar Panel");
+ await assetsPage.deleteSelectedAsset(manager, "Battery");
+ await assetsPage.deleteSelectedAsset(manager, "Solar Panel");
await expect(page.locator("text=Console")).toHaveCount(1);
await expect(page.locator("text=Solar Panel")).toHaveCount(0);
await expect(page.locator("text=Battery")).toHaveCount(0);
diff --git a/ui/app/manager/test/assettree.test.ts b/ui/app/manager/test/assettree.test.ts
new file mode 100644
index 000000000..540d25864
--- /dev/null
+++ b/ui/app/manager/test/assettree.test.ts
@@ -0,0 +1,403 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+import { expect } from "@openremote/test";
+import {Manager, test, userStatePath} from "./fixtures/manager.js";
+import {batteryAsset, buildingAsset, electricityAsset, parentAssets} from "./fixtures/data/assettree.js";
+import {Asset} from "@openremote/model";
+import type {OrAssetTree} from "@openremote/or-asset-tree";
+
+test.use({ storageState: userStatePath });
+
+function createBatteryAssets(amount: number): Asset[] {
+ return Array.from({ length: amount }, (_, i) => ({
+ ...batteryAsset,
+ name: `Battery ${i + 1}`
+ }));
+}
+
+function createElectricityAssets(amount: number): Asset[] {
+ return Array.from({ length: amount }, (_, i) => ({
+ ...electricityAsset,
+ name: `Electricity meter ${i + 1}`
+ }));
+}
+
+function createBuildingAssets(amount: number): Asset[] {
+ return Array.from({ length: amount }, (_, i) => ({
+ ...buildingAsset,
+ name: `Building ${i + 1}`
+ }));
+}
+
+function createComplexTree(): Asset[] {
+ const [cityAsset1, cityAsset2] = parentAssets;
+ const buildingAssets = [cityAsset1, cityAsset2].flatMap(city =>
+ createBuildingAssets(3).map(building => ({
+ ...building, parentId: city.id
+ }))
+ );
+ const batteryAssets = buildingAssets.flatMap(building =>
+ createBatteryAssets(5).map(battery => ({
+ ...battery, parentId: building.id
+ }))
+ );
+ return [cityAsset1, cityAsset2, ...buildingAssets, ...batteryAssets];
+
+}
+
+// Utility function to create parent assets, and apply assets as children
+async function applyParentAssets(parentAssets: Asset[], manager: Manager) {
+ for (const p of parentAssets) {
+ await manager.createAsset(p);
+ }
+ const cityIds = manager.assets.filter(a => a.type === "CityAsset").sort((a, b) => a.name!.localeCompare(b.name!)).map(a => a.id);
+ const childAssets = manager.assets.filter(a => a.type !== "CityAsset");
+ childAssets.forEach(((ca, i) => ca.parentId = cityIds[Math.floor(i / (childAssets.length / cityIds.length))]));
+ for (const a of childAssets) {
+ await manager.updateAsset(a);
+ }
+}
+
+/**
+ * @given Assets are set up in the "smartcity" realm
+ * @when Logging in to OpenRemote "smartcity" realm as admin
+ * @and Navigating to the "Assets" tab
+ * @and Tries to navigate through the assets in the system using the asset tree
+ * @then The asset list should be complete and should not display any artifacts or visual errors.
+ */
+test(`Check if assets are visible in the tree`, async ({ assetTree, manager, assetsPage }) => {
+ const batteryAssets = createBatteryAssets(2);
+ const electricityAssets = createElectricityAssets(2)
+ await manager.setup("smartcity", { assets: [...batteryAssets, ...electricityAssets] });
+ await applyParentAssets(parentAssets, manager);
+ await manager.goToRealmStartPage("smartcity");
+ await assetsPage.goto();
+
+ // Check if City Asset 1, City Asset 2 and Consoles group asset are listed.
+ await expect(assetTree.getAssetNodes()).toHaveCount(3);
+ await expect(assetTree.getAssetNodes().nth(0)).toContainText(parentAssets[0].name!);
+ await expect(assetTree.getAssetNodes().nth(1)).toContainText(parentAssets[1].name!);
+ await expect(assetTree.getAssetNodes().nth(2)).toContainText('Consoles');
+ await expect(assetTree.getAssetNodes().locator('[data-expandable]')).toHaveCount(3);
+
+ // Check if expandable of City Asset 1 is correct.
+ const cityAsset1 = assetTree.getAssetNodes().filter({ hasText: parentAssets[0].name });
+ await cityAsset1.locator('[data-expandable]').click();
+ await expect(assetTree.getAssetNodes()).toHaveCount(3 + 2);
+ await expect(assetTree.getChildNodes(cityAsset1)).toHaveText(batteryAssets.map(a => a.name!));
+
+ // Check if expandable of City Asset 2 is correct.
+ const cityAsset2 = assetTree.getAssetNodes().filter({ hasText: parentAssets[1].name });
+ await cityAsset2.locator('[data-expandable]').click();
+ await expect(assetTree.getAssetNodes()).toHaveCount(3 + 2 + 2);
+ await expect(assetTree.getChildNodes(cityAsset2)).toHaveText(electricityAssets.map(a => a.name!));
+
+ // Check if expandable of Consoles group asset is correct.
+ const consoleAsset = assetTree.getAssetNodes().filter({ hasText: 'Consoles' });
+ await consoleAsset.locator('[data-expandable]').click();
+ await expect.poll(async () => await assetTree.getAssetNodes().count(), {
+ message: "Waiting for the Console assets to appear..."
+ }).toBeGreaterThanOrEqual(3 + 2 + 2 + 1); // (there is at least 1 console, but could be more with a larger test suite)
+});
+
+/**
+ * @given Assets are set up in the "smartcity" realm
+ * @when Logging in to the OpenRemote "smartcity" realm
+ * @and Navigating to the "asset" tab
+ * @and Searching for the asset by name
+ * @and Selecting the asset from the list
+ * @then The asset detail page is displayed
+ */
+test(`Search for and select the battery asset`, async ({ page, manager, assetTree, assetViewer, assetsPage }) => {
+ await manager.setup("smartcity", { assets: [batteryAsset, electricityAsset] });
+ await manager.goToRealmStartPage("smartcity");
+ await assetsPage.goto();
+ await assetTree.getFilterInput().fill(batteryAsset.name);
+ await expect(assetTree.getAssetNodes()).toHaveCount(1);
+ await page.click(`text=${batteryAsset.name}`);
+ await expect(assetViewer.getHeaderLocator(batteryAsset.name)).toBeVisible();
+});
+
+/**
+ * @given Assets are set up in the "smartcity" realm
+ * @when Logging in to the OpenRemote "smartcity" realm
+ * @and Navigating to the "asset" tab
+ * @and Searching for the asset by ID
+ * @and Selecting the asset from the list
+ * @then The asset detail page is displayed
+ */
+test(`Search by Asset ID and select the battery asset`, async ({ page, manager, assetTree, assetViewer, assetsPage }) => {
+ const assets = [batteryAsset, electricityAsset];
+ await manager.setup("smartcity", { assets: assets });
+ const id = manager.assets.find(asset => asset.name === batteryAsset.name)?.id;
+ expect(id).toBeDefined();
+ await manager.goToRealmStartPage("smartcity");
+ await manager.navigateToTab("asset");
+ await assetTree.getFilterInput().fill(id!);
+ await expect(assetTree.getAssetNodes()).toHaveCount(1);
+ await page.click(`text=${batteryAsset.name}`);
+ await expect(assetViewer.getHeaderLocator(batteryAsset.name)).toBeVisible();
+})
+
+/**
+ * @given Assets are set up in the "smartcity" realm
+ * @when Logging in to the OpenRemote "smartcity" realm
+ * @and Navigating to the "/assets/false/{id}" page directly
+ * @then The filter should contain the ID as input
+ * @and The asset list should contain the asset with the given ID
+ * @and The asset detail page is displayed
+ */
+test(`Open browser tab directly to the battery asset`, async ({ page, manager, assetsPage, assetTree, assetViewer }) => {
+ const batteryAssets = createBatteryAssets(10);
+ const electricityAssets = createElectricityAssets(10);
+ const assets = [...batteryAssets, ...electricityAssets];
+ await manager.setup("smartcity", { assets: assets });
+ await applyParentAssets(parentAssets, manager);
+ const id = manager.assets.find(asset => asset.name === batteryAssets[0].name)?.id;
+ expect(id).toBeDefined();
+ await manager.goToRealmStartPage("smartcity");
+ await assetsPage.gotoAssetId("smartcity", id!);
+ await expect(assetTree.getFilterInput()).toHaveValue(id!);
+ await expect(assetTree.getAssetNodes()).toHaveCount(2); // The parent city asset + selected battery asset
+ await expect(assetTree.getSelectedNodes()).toHaveCount(1);
+ await expect(assetViewer.getHeaderLocator(batteryAsset.name)).toBeVisible();
+ expect(page.url()).toContain(id!);
+})
+
+/**
+ * @given Assets are set up in the "smartcity" realm
+ * @when Logging in to the OpenRemote "smartcity" realm
+ * @and Navigating to the "asset" tab, while the QUERY_LIMIT is set to 2
+ * @then the other assets should not be visible
+ * @and a "Load More" button has to be displayed
+ * @when the "Load More" button is clicked
+ * @then the other assets should be visible
+ */
+test(`Load more buttons are shown when there are a lot of assets`, async ({ page, manager, assetsPage, assetTree }) => {
+ const assets = [batteryAsset, batteryAsset, electricityAsset, electricityAsset];
+ await manager.setup("smartcity", { assets: assets });
+ await manager.goToRealmStartPage("smartcity");
+ await assetsPage.goto();
+ await expect(assetTree.getAssetNodes()).toHaveCount(5); // 2 battery assets + 2 electricity assets + 1 console group
+ await page.locator('or-asset-tree').evaluate(tree => {(tree as OrAssetTree).setAttribute('queryLimit', '2')});
+ await expect(assetTree.getAssetNodes()).toHaveCount(2);
+ await page.getByRole('button', { name: "Load More" }).click();
+ await expect(assetTree.getAssetNodes()).toHaveCount(4);
+ await page.getByRole('button', { name: "Load More" }).click();
+ await expect(assetTree.getAssetNodes()).toHaveCount(5);
+})
+
+/**
+ * @given 50 assets are loaded in the "smartcity" realm
+ * @when Logging in to the OpenRemote "smartcity" realm
+ * @and Navigating to the "asset" tab
+ * @and Pressing "load more" buttons within each parent
+ * @then The correct amount of children should be displayed
+ * @and The scroll position should be kept consistent, without jumping back and forth.
+ */
+test(`Load more buttons are shown properly without any unexpected scroll behavior`, async ({page, manager, assetsPage, assetTree}) => {
+ const batteryAssets = createBatteryAssets(50);
+ await manager.setup("smartcity", { assets: batteryAssets });
+ await applyParentAssets(parentAssets, manager);
+ await manager.goToRealmStartPage("smartcity");
+ await assetsPage.goto();
+
+ // Test if expanding the node works correctly
+ let cityAsset1 = assetTree.getAssetNodes().filter({ hasText: parentAssets[0].name });
+ await cityAsset1.locator('[data-expandable]').click();
+ await expect(assetTree.getAssetNodes()).toHaveCount(3 + 25); // City 1, City 2, Consoles asset and 25 battery assets
+
+ // Limit the number of expanding nodes to 20, and check if the tree is still in tact
+ await page.locator('or-asset-tree').evaluate(tree => {(tree as OrAssetTree).setAttribute('queryLimit', '20')});
+ await expect(assetTree.getAssetNodes()).toHaveCount(3); // City 1, City 2 and Consoles asset
+ cityAsset1 = assetTree.getAssetNodes().filter({ hasText: parentAssets[0].name });
+ await cityAsset1.locator('[data-expandable]').click();
+ await expect(assetTree.getAssetNodes()).toHaveCount(3 + 20); // City 1, City 2, Consoles asset and 20 out of 25 battery assets
+
+ // Scroll down to the "load more" botton, and check if the scroll position is kept after pressing it.
+ const listContainer = page.locator('or-asset-tree #list-container');
+ await cityAsset1.getByRole('button', { name: "Load More" }).click();
+ const scrollPos1 = await listContainer.evaluate(el => el.scrollTop);
+ await expect(assetTree.getAssetNodes()).toHaveCount(3 + 25); // Now it's 25 out of 25 assets again
+ expect(await listContainer.evaluate(el => el.scrollTop)).toStrictEqual(scrollPos1);
+
+ // Now click the 2nd city, scroll down to their "load more" button, and do the same.
+ let cityAsset2 = assetTree.getAssetNodes().filter({ hasText: parentAssets[1].name });
+ await cityAsset2.locator('[data-expandable]').click();
+ await expect(assetTree.getAssetNodes()).toHaveCount(3 + 25 + 20); // City 2 now has 20 out of 25 assets
+ await cityAsset2.getByRole('button', { name: "Load More" }).click();
+ const scrollPos2 = await listContainer.evaluate(el => el.scrollTop);
+ await expect(assetTree.getAssetNodes()).toHaveCount(3 + 25 + 25); // Now it's 25 out of 25 assets again
+ expect(await listContainer.evaluate(el => el.scrollTop)).toStrictEqual(scrollPos2);
+})
+
+/**
+ * @given 50 assets are loaded in the "smartcity" realm
+ * @when Logging in to the OpenRemote "smartcity" realm
+ * @and Navigating to the "asset" tab
+ * @and Pressing "load more" buttons within each parent
+ * @then The correct children are displayed, and the correct asset is selected
+ */
+test(`Load more buttons are shown properly when there is a complex tree`, async ({page, manager, assetsPage, assetTree, assetViewer}) => {
+ await manager.setup("smartcity", { assets: parentAssets });
+ const cityAssets = manager.assets.filter(a => a.type === "CityAsset");
+ expect(cityAssets.length).toBe(2);
+ expect(cityAssets[0].id).toBeDefined();
+ expect(cityAssets[1].id).toBeDefined();
+
+ // Beforehand, create buildings for each city
+ let buildingAssets = cityAssets.flatMap(city =>
+ createBuildingAssets(3).map(building => ({
+ ...building, parentId: city.id
+ }))
+ ) as Asset[];
+ for(const building of buildingAssets) {
+ await manager.createAsset(building);
+ }
+ buildingAssets = manager.assets.filter(a => a.type === "BuildingAsset");
+ expect(buildingAssets.length).toBe(2 * 3);
+
+ // Beforehand, create batteries for each building
+ let batteryAssets = buildingAssets.flatMap(building =>
+ createBatteryAssets(5).map(battery => ({
+ ...battery, parentId: building.id
+ }))
+ ) as Asset[];
+ for(const battery of batteryAssets) {
+ await manager.createAsset(battery);
+ }
+ batteryAssets = manager.assets.filter(a => a.name?.includes("Battery"));
+ expect(batteryAssets.length).toBe(2 * 3 * 5);
+
+ // Navigate to the asset tree
+ await manager.goToRealmStartPage("smartcity");
+ await assetsPage.goto();
+ await page.locator('or-asset-tree').evaluate(tree => {(tree as OrAssetTree).setAttribute('queryLimit', '2')});
+ await expect(assetTree.getAssetNodes()).toHaveCount(2); // 2 parent assets (the other console group is hidden because of queryLimit=2)
+
+ // Navigate to the 1st building within the first city
+ let cityAsset1 = assetTree.getAssetNodes().filter({ hasText: parentAssets[0].name });
+ await cityAsset1.locator('[data-expandable]').click();
+ await expect(assetTree.getAssetNodes()).toHaveCount(2 + 2); // City 1, City 2, and 2 out of 3 building assets
+ await page.click(`text=${buildingAssets[0].name}`); // Clicking "Building 1" within the 1st city
+ await expect(assetTree.getSelectedNodes()).toHaveCount(1);
+ await expect(assetTree.getSelectedNodes()).toHaveText(buildingAssets[0].name!);
+ await expect(assetViewer.getHeaderLocator(buildingAssets[0].name)).toBeVisible();
+
+ // Select the 1st building of the city
+ await expect(page.getByRole('button', { name: 'Load More' })).toHaveCount(2);
+ await page.getByRole('button', { name: 'Load More' }).first().click();
+ await expect(assetTree.getSelectedNodes()).toHaveCount(1);
+ await expect(assetTree.getSelectedNodes()).toHaveText(buildingAssets[0].name!);
+ await expect(assetViewer.getHeaderLocator(buildingAssets[0].name)).toBeVisible();
+})
+
+/**
+ * @given 20 assets are loaded in the "smartcity" realm
+ * @when Logging in to the OpenRemote "smartcity" realm
+ * @and Selecting an asset from the list
+ * @and Attempting to delete the asset
+ * @then The asset should be deleted
+ * @and The asset list should be updated, but kept in the same state without visual artifacts
+ * @and The asset detail page should be closed
+ */
+test(`Deleting an asset properly keeps the tree and viewer in tact`, async ({ page, manager, assetsPage, assetTree }) => {
+ const batteryAssets = createBatteryAssets(10);
+ const electricityAssets = createElectricityAssets(10);
+ const assets = [...batteryAssets, ...electricityAssets];
+ await manager.setup("smartcity", { assets: assets });
+ await applyParentAssets(parentAssets, manager);
+ await manager.goToRealmStartPage("smartcity");
+ await assetsPage.goto();
+ await expect(assetTree.getAssetNodes()).toHaveCount(3); // 2 parent assets + 1 console group
+
+ // Expand both City Asset 1 and City Asset 2
+ const cityAsset1 = assetTree.getAssetNodes().filter({ hasText: parentAssets[0].name });
+ await cityAsset1.locator('[data-expandable]').click();
+ await expect(assetTree.getChildNodes(cityAsset1)).toHaveCount(assets.length / 2);
+ const cityAsset2 = assetTree.getAssetNodes().filter({ hasText: parentAssets[1].name });
+ await cityAsset2.locator('[data-expandable]').click();
+ await expect(assetTree.getChildNodes(cityAsset2)).toHaveCount(assets.length / 2);
+ await expect(assetTree.getAssetNodes()).toHaveCount(1 + 10 + 1 + 10 + 1);
+
+ // Delete battery asset 5 of the first city, and check if state is the same
+ await assetsPage.deleteSelectedAsset(manager, batteryAssets[4].name!);
+ await expect(assetTree.getSelectedNodes()).toHaveCount(0);
+ await expect(assetTree.getChildNodes(cityAsset1)).toHaveCount(assets.length / 2 - 1);
+ await expect(assetTree.getChildNodes(cityAsset2)).toHaveCount(assets.length / 2);
+ await expect(assetTree.getAssetNodes()).toHaveCount(1 + 9 + 1 + 10 + 1);
+ await expect(page.locator('or-asset-tree [data-expandable]')).toHaveCount(3);
+ await expect(page.locator('or-asset-tree [data-expanded] [data-expandable]')).toHaveCount(2);
+ await expect(page.locator('or-asset-viewer', { hasText: "Please select an asset on the left"})).toBeVisible();
+})
+
+/**
+ * @given 20 assets are loaded in the "smartcity" realm
+ * @when Logging in to the OpenRemote "smartcity" realm
+ * @and Searching for an asset using the filter
+ * @and The asset is appearing in the list as expected
+ * @and The asset is selected
+ * @then Attempting to remove the asset from the list succeeds
+ * @and the asset list should be updated, but kept in the same state without visual artifacts
+ */
+test(`Searching for an asset and removing it keeps the tree and viewer in tact`, async ({page, manager, assetsPage, assetTree, assetViewer}) => {
+ const batteryAssets = createBatteryAssets(10);
+ const electricityAssets = createElectricityAssets(10);
+ await manager.setup("smartcity", { assets: [...batteryAssets, ...electricityAssets] });
+ await applyParentAssets(parentAssets, manager);
+ await manager.goToRealmStartPage("smartcity");
+ await assetsPage.goto();
+
+ // Fill in "Battery 10", and expect that single asset + parent to show up
+ const battery10 = batteryAssets[batteryAssets.length - 1];
+ await expect(assetTree.getAssetNodes()).toHaveCount(3); // 2 parent assets + 1 console group
+ await assetTree.getFilterInput().fill(battery10.name!);
+ await expect(assetTree.getAssetNodes()).toContainText([parentAssets[0].name!, battery10.name!]);
+ await expect(assetTree.getAssetNodes()).toHaveCount(2); // Parent asset + child battery asset
+ await page.click(`text=${battery10.name}`);
+ await expect(assetTree.getSelectedNodes()).toHaveCount(1);
+ await expect(assetViewer.getHeaderLocator(battery10.name!)).toBeVisible();
+
+ // Fill in "Electricity meter 1", and expect that single asset + "Electricity meter 10", and their parent to show up"
+ const meter1 = electricityAssets[0];
+ const meter10 = electricityAssets[electricityAssets.length - 1];
+ await assetTree.getFilterInput().fill(meter1.name!);
+ await expect(assetTree.getAssetNodes()).toContainText([parentAssets[1].name!, meter1.name!]);
+ await expect(assetTree.getAssetNodes()).toHaveCount(2 + 1); // Parent asset + the two electricity meter assets
+
+ // Attempt to select and delete the "Electricity meter 1"
+ await assetsPage.deleteSelectedAsset(manager, meter1.name!);
+ await expect(assetTree.getSelectedNodes()).toHaveCount(1); // It automatically selects the other asset, "Electricity meter 10"
+ await expect(assetTree.getAssetNodes()).toContainText([parentAssets[1].name!, meter10.name!]);
+ await expect(assetTree.getAssetNodes()).toHaveCount(1 + 1); // Only parent + "Electricity meter 10" are visible now.
+
+ // We now clear the filter, and try to delete "Battery 10" from earlier as well
+ await assetTree.getFilterInput().fill(battery10.name!);
+ await expect(assetTree.getAssetNodes()).toContainText([parentAssets[0].name!, battery10.name!]);
+ await expect(assetTree.getAssetNodes()).toHaveCount(2); // Parent asset + child electricity asset
+ await assetsPage.deleteSelectedAsset(manager, battery10.name!, assetTree.getSelectedNodes());
+ await expect(assetTree.getSelectedNodes()).toHaveCount(0);
+ await expect(assetTree.getAssetNodes()).toHaveCount(0); // Nothing is visible anymore, since there is nothing matching the "Battery 10" text filter.
+})
+
+// After each test, clean up all data
+test.afterEach(async ({ manager }) => {
+ await manager.cleanUp();
+});
diff --git a/ui/app/manager/test/fixtures/data/assets.ts b/ui/app/manager/test/fixtures/data/assets.ts
index f52621ed2..70bc71122 100644
--- a/ui/app/manager/test/fixtures/data/assets.ts
+++ b/ui/app/manager/test/fixtures/data/assets.ts
@@ -3,7 +3,7 @@ import { Asset } from "@openremote/model";
export const assetMap = {
Battery: "ElectricityBatteryAsset",
- "Solar Panel": "ElectricityProducerSolarAsset",
+ "Solar Panel": "ElectricityProducerSolarAsset"
};
const assets = [
{
@@ -16,8 +16,8 @@ const assets = [
energyLevel: { name: "energyLevel", type: "positiveNumber", meta: { readOnly: true } },
power: { name: "power", type: "number", meta: { readOnly: false } },
powerSetpoint: { name: "powerSetpoint", type: "number" },
- energyCapacity: { name: "energyCapacity", type: "positiveNumber" },
- },
+ energyCapacity: { name: "energyCapacity", type: "positiveNumber" }
+ }
},
{
name: "Solar Panel",
@@ -28,9 +28,9 @@ const assets = [
location: { name: "location", type: "GEO_JSONPoint" },
panelPitch: { name: "panelPitch", type: "positiveInteger", meta: { readOnly: true } },
power: { name: "power", type: "number", meta: { readOnly: false } },
- powerForecast: { name: "powerForecast", type: "number", meta: { readOnly: true } },
- },
- },
+ powerForecast: { name: "powerForecast", type: "number", meta: { readOnly: true } }
+ }
+ }
] as const;
export const preparedAssetsWithLocation = Object.values(
@@ -38,7 +38,7 @@ export const preparedAssetsWithLocation = Object.values(
structuredClone(assets),
[
{ attributes: { location: { value: { type: "Point", coordinates: [4.482259693115793, 51.91756799273] } } } },
- { attributes: { location: { value: { type: "Point", coordinates: [4.4845127486877345, 51.917435642781214] } } } },
+ { attributes: { location: { value: { type: "Point", coordinates: [4.4845127486877345, 51.917435642781214] } } } }
],
true
)
@@ -51,15 +51,15 @@ export const preparedAssetsForRules = Object.values(
{
attributes: {
energyLevel: { meta: { ruleState: true, storeDataPoints: true } },
- power: { meta: { ruleState: true, storeDataPoints: true } },
- },
+ power: { meta: { ruleState: true, storeDataPoints: true } }
+ }
},
{
attributes: {
power: { meta: { ruleState: true, storeDataPoints: true } },
- powerForecast: { meta: { ruleState: true, storeDataPoints: true } },
- },
- },
+ powerForecast: { meta: { ruleState: true, storeDataPoints: true } }
+ }
+ }
],
true
)
@@ -98,8 +98,8 @@ export const assetPatches: Record<
value2: "70",
value3: "100",
x: 600,
- y: 200,
- },
+ y: 200
+ }
};
export type DefaultAssets = typeof assets;
@@ -123,6 +123,6 @@ export const agent: Asset = {
notes: { name: "notes", type: "text", meta: {} },
agentDisabled: { name: "agentDisabled", type: "boolean", meta: {} },
location: { name: "location", type: "GEO_JSONPoint", meta: {} },
- agentStatus: { name: "agentStatus", type: "connectionStatus", meta: { readOnly: true } },
- },
+ agentStatus: { name: "agentStatus", type: "connectionStatus", meta: { readOnly: true } }
+ }
};
diff --git a/ui/app/manager/test/fixtures/data/assettree.ts b/ui/app/manager/test/fixtures/data/assettree.ts
new file mode 100644
index 000000000..45aaa5b73
--- /dev/null
+++ b/ui/app/manager/test/fixtures/data/assettree.ts
@@ -0,0 +1,61 @@
+import type {Asset} from "@openremote/model";
+
+export const parentAssets: Asset[] = [
+ {
+ name: "City Asset 1",
+ type: "CityAsset",
+ realm: "smartcity",
+ attributes: {
+ notes: { name: "notes", type: "text" },
+ location: { name: "location", type: "GEO_JSONPoint" },
+ country: { name: "country", type: "text" }
+ }
+ },
+ {
+ name: "City Asset 2",
+ type: "CityAsset",
+ realm: "smartcity",
+ attributes: {
+ notes: { name: "notes", type: "text" },
+ location: { name: "location", type: "GEO_JSONPoint" },
+ country: { name: "country", type: "text" }
+ }
+ }
+];
+export const buildingAsset = {
+ name: "Building",
+ type: "BuildingAsset",
+ realm: "smartcity",
+ attributes: {
+ area: { name: "area", type: "positiveInteger" },
+ city: { name: "city", type: "text" },
+ country: { name: "country", type: "text" },
+ location: { name: "location", type: "GEO_JSONPoint" },
+ notes: { name: "notes", type: "text" },
+ postalCode: { name: "postalCode", type: "text" },
+ street: { name: "street", type: "text" }
+ }
+}
+export const batteryAsset = {
+ name: "Battery",
+ type: "ThingAsset",
+ realm: "smartcity",
+ attributes: {
+ notes: { name: "notes", type: "text" },
+ location: { name: "location", type: "GEO_JSONPoint" },
+ energyLevel: { name: "energyLevel", type: "positiveNumber", meta: { readOnly: true } },
+ power: { name: "power", type: "number", meta: { readOnly: false } },
+ powerSetpoint: { name: "powerSetpoint", type: "number" },
+ energyCapacity: { name: "energyCapacity", type: "positiveNumber" }
+ }
+};
+export const electricityAsset = {
+ name: "Electricity meter",
+ type: "ThingAsset",
+ realm: "smartcity",
+ attributes: {
+ notes: { name: "notes", type: "text" },
+ location: { name: "location", type: "GEO_JSONPoint" },
+ power: { name: "power", type: "number", meta: { readOnly: false } }
+ }
+};
diff --git a/ui/app/manager/test/fixtures/manager.ts b/ui/app/manager/test/fixtures/manager.ts
index 3154d17d5..ff1ebbb8f 100644
--- a/ui/app/manager/test/fixtures/manager.ts
+++ b/ui/app/manager/test/fixtures/manager.ts
@@ -13,6 +13,7 @@ import { AssetViewer } from "../../../../component/or-asset-viewer/test/fixtures
import { CollapsiblePanel } from "../../../../component/or-components/test/fixtures";
import { JsonForms } from "../../../../component/or-json-forms/test/fixtures";
import { AssetTree } from "../../../../component/or-asset-tree/test/fixtures";
+import { type AxiosRequestConfig } from "axios";
export const adminStatePath = path.join(__dirname, "data/.auth/admin.json");
export const userStatePath = path.join(__dirname, "data/.auth/user.json");
@@ -117,7 +118,7 @@ export class Manager {
* Expects a realm to be configured
* @param config The axios request config
*/
- async getClientRoles(config) {
+ async getClientRoles(config?: AxiosRequestConfig<any>) {
try {
const response = await rest.api.UserResource.getClientRoles(this.realm!, this.clientId, config);
expect(response.status).toBe(200);
@@ -137,7 +138,7 @@ export class Manager {
* @param roles The current stored roles to add the new role to
* @param config The axios request config
*/
- async createRole(newRole: Role, roles: Role[], config) {
+ async createRole(newRole: Role, roles: Role[], config?: AxiosRequestConfig<any>) {
if (newRole.compositeRoleIds) {
newRole.compositeRoleIds = newRole.compositeRoleIds
.map((name) => roles.find((r) => r.name === name)?.id)
@@ -160,7 +161,7 @@ export class Manager {
* @param user The user to create
* @param config The axios request config
*/
- async createUser(user: UserModel, config) {
+ async createUser(user: UserModel, config?: AxiosRequestConfig<any>) {
try {
const response = await rest.api.UserResource.create(this.realm!, user, config);
expect(response.status).toBe(200);
@@ -177,7 +178,7 @@ export class Manager {
* @param roles A list of roles to add to the user
* @param config The axios request config
*/
- async addUserRoles(roles: string[], config) {
+ async addUserRoles(roles: string[], config?: AxiosRequestConfig<any>) {
try {
const response = await rest.api.UserResource.updateUserClientRoles(
this.realm!,
@@ -198,7 +199,7 @@ export class Manager {
* Expects a realm and user to be configured
* @param config The axios request config
*/
- async resetUserPassword(config) {
+ async resetUserPassword(config?: AxiosRequestConfig<any>) {
try {
const response = await rest.api.UserResource.resetPassword(
this.realm!,
@@ -217,7 +218,11 @@ export class Manager {
* @param asset The asset to create
* @param config The axios request config
*/
- async createAsset(asset: Asset, config) {
+ async createAsset(asset: Asset, config?: AxiosRequestConfig<any>) {
+ if(!config) {
+ const access_token = await this.getAccessToken("master", "admin", users.admin.password!);
+ config = { headers: { Authorization: `Bearer ${access_token}` } };
+ }
await rest.api.AssetResource.create(asset, config)
.then((response) => {
expect(response.status).toBe(200);
@@ -228,6 +233,26 @@ export class Manager {
});
}
+ /**
+ * Updates an asset
+ * @param asset The asset to update
+ * @param config The axios request config
+ */
+ async updateAsset(asset: Asset, config?: AxiosRequestConfig<any>) {
+ if(!config) {
+ const access_token = await this.getAccessToken("master", "admin", users.admin.password!);
+ config = { ...(config || {}), headers: { Authorization: `Bearer ${access_token}` } };
+ }
+ await rest.api.AssetResource.update(asset.id!, asset, config)
+ .then((response) => {
+ expect(response.status).toBe(200);
+ this.assets = [...this.assets.filter(a => a.id !== response.data.id), response.data as Asset];
+ })
+ .catch((e) => {
+ expect(e.response.status, { message: "Failed to update asset" }).toBe(409);
+ });
+ }
+
/**
* Setup the testing environment by giving the realm name and additional parameters
* @param realm Realm to create
@@ -273,7 +298,7 @@ export class Manager {
* Deletes rules in the active realm
* @param config The axios request config
*/
- async deleteRealmRulesets(config) {
+ async deleteRealmRulesets(config?: AxiosRequestConfig<any>) {
for (const [i, id] of this.rules.entries()) {
try {
const response = await rest.api.RulesResource.deleteRealmRuleset(id!, config);
@@ -289,7 +314,7 @@ export class Manager {
* Deletes assets
* @param config The axios request config
*/
- async deleteAssets(config) {
+ async deleteAssets(config?: AxiosRequestConfig<any>) {
const assetIds = this.assets.map(({ id }) => id!);
try {
const response = await rest.api.AssetResource.delete({ assetId: assetIds }, config);
diff --git a/ui/app/manager/test/fixtures/pages/assets.ts b/ui/app/manager/test/fixtures/pages/assets.ts
index 3c58c8d6e..a2df4a535 100644
--- a/ui/app/manager/test/fixtures/pages/assets.ts
+++ b/ui/app/manager/test/fixtures/pages/assets.ts
@@ -33,14 +33,17 @@ export class AssetsPage implements BasePage {
/**
* Delete an asset by its name.
+ * @param manager The manager instance
* @param asset The asset name
+ * @param page The page or locator to search from
*/
- async deleteSelectedAsset(asset: string) {
- const assetLocator = this.page.locator(`text=${asset}`);
+ async deleteSelectedAsset(manager: Manager, asset: string, locator?: any) {
+ const assetLocator = locator ?? this.page.locator(`text="${asset}"`);
await expect(assetLocator).toHaveCount(1);
await assetLocator.click();
await this.page.click(".mdi-delete");
await this.page.getByRole("button", { name: "Delete" }).click();
await expect(assetLocator).toHaveCount(0);
+ manager.assets = manager.assets.filter(a => a.name !== asset); // Remove asset from cache as well
}
}
diff --git a/ui/app/shared/locales/en/or.json b/ui/app/shared/locales/en/or.json
index 76edd3793..e1622a9d1 100644
--- a/ui/app/shared/locales/en/or.json
+++ b/ui/app/shared/locales/en/or.json
@@ -629,6 +629,7 @@
"dismiss": "dismiss",
"createAssetFailed": "Failed to create asset",
"moveAssetFailed": "Failed to move asset",
+ "loadMore": "Load more",
"logCategory": {},
"readPermissions": "Read permissions",
"writePermissions": "Write permissions",
diff --git a/ui/app/shared/locales/nl/or.json b/ui/app/shared/locales/nl/or.json
index eec1604ae..8d164ab9c 100644
--- a/ui/app/shared/locales/nl/or.json
+++ b/ui/app/shared/locales/nl/or.json
@@ -628,6 +628,7 @@
"dismiss": "sluiten",
"createAssetFailed": "Asset aanmaken is niet gelukt",
"moveAssetFailed": "Failed to move asset",
+ "loadMore": "Meer laden",
"logCategory": {},
"readPermissions": "Leesrechten",
"writePermissions": "Schrijfrechten",
diff --git a/ui/component/or-asset-tree/src/index.ts b/ui/component/or-asset-tree/src/index.ts
index 46623f1b4..099734947 100644
--- a/ui/component/or-asset-tree/src/index.ts
+++ b/ui/component/or-asset-tree/src/index.ts
@@ -11,16 +11,17 @@ import {
AssetModelUtil,
AssetQuery,
AssetQueryMatch,
+ AssetQueryOrderBy$Property,
AssetsEvent,
- AssetTreeNode,
- AssetTypeInfo,
+ AssetTreeEvent, AssetTreeNode,
Attribute,
AttributePredicate,
ClientRole,
LogicGroup,
LogicGroupOperator,
SharedEvent,
- StringPredicate, WellknownAssets
+ StringPredicate,
+ WellknownAssets
} from "@openremote/model";
import "@openremote/or-translate";
import {style} from "./style";
@@ -33,17 +34,12 @@ import {ListItem} from "@openremote/or-mwc-components/or-mwc-list";
import "@openremote/or-mwc-components/or-mwc-list";
import {i18next} from "@openremote/or-translate";
import "@openremote/or-mwc-components/or-mwc-dialog";
-
-import {
- OrMwcDialog,
- showDialog,
- showErrorDialog,
- showOkCancelDialog
-} from "@openremote/or-mwc-components/or-mwc-dialog";
+import {OrMwcDialog, showDialog, showErrorDialog, showOkCancelDialog} from "@openremote/or-mwc-components/or-mwc-dialog";
import {OrAddAssetDialog, OrAddChangedEvent} from "./or-add-asset-dialog";
import "./or-add-asset-dialog";
import {showSnackbar} from "@openremote/or-mwc-components/or-mwc-snackbar";
-import { when } from "lit/directives/when.js";
+import {when} from "lit/directives/when.js";
+import {debounce} from "lodash";
export interface AssetTreeTypeConfig {
include?: string[];
@@ -246,19 +242,6 @@ declare global {
}
}
-export const getAssetTypes = async () => {
- const response = await manager.rest.api.AssetResource.queryAssets({
- select: {
- attributes: []
- },
- recursive: true
- });
-
- if(response && response.data) {
- return response.data.map(asset => asset.type!);
- }
-}
-
@customElement("or-asset-tree")
export class OrAssetTree extends subscribe(manager)(LitElement) {
@@ -272,31 +255,25 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
* Allows arbitrary assets to be displayed using a tree
*/
@property({type: Array, reflect: false})
- public assets?: Asset[];
-
- @property({type: Object})
- public assetInfos?: AssetTypeInfo[];
-
- @property({type: Array})
- public _assetIdsOverride?: string[];
+ public readonly assets?: Asset[];
@property({type: Array})
- public rootAssets?: Asset[];
+ public readonly rootAssets?: Asset[];
@property({type: Array})
- public rootAssetIds?: string[];
+ public readonly rootAssetIds?: string[];
@property({type: Object})
- public dataProvider?: () => Promise<Asset[]>;
+ public readonly dataProvider?: () => Promise<Asset[]>;
@property({type: Boolean})
- public readonly: boolean = false;
+ public readonly readonly: boolean = false;
@property({type: Boolean})
public disabled: boolean = false;
@property({type: Boolean})
- public disableSubscribe: boolean = false;
+ public readonly disableSubscribe: boolean = false;
@property({type: Array})
public selectedIds?: string[];
@@ -322,9 +299,12 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
@property({type: Boolean})
public checkboxes?: boolean = false;
+ @property({type: Number})
+ public readonly queryLimit = 100;
+
protected config?: AssetTreeConfig;
- @property({attribute: false})
+ @state()
protected _nodes?: UiAssetTreeNode[];
protected _loading: boolean = false;
@@ -335,7 +315,6 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
@state()
protected _filter: OrAssetTreeFilter = new OrAssetTreeFilter();
- protected _searchInputTimer?: number = undefined;
@query("#clearIconContainer")
protected _clearIconContainer!: HTMLElement;
@query("#filterInput")
@@ -351,6 +330,10 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
@state()
protected _assetTypeFilter!: string;
protected _uniqueAssetTypes: string[] = [];
+ @state()
+ protected _hasMoreParents = false;
+ @state()
+ protected _incompleteParentIds: string[] = [];
private _dragDropParentId: string | null = null;
protected _expandTimer?: number = undefined;
@@ -503,14 +486,10 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
placeholder="${i18next.t("filter.filter")}..."
compact="true"
outlined="true"
- @input="${(e: KeyboardEvent) => {
+ @input="${debounce(() => {
// Means some input is occurring so delay filter
- this._onFilterInputEvent(e);
- }}"
- @or-mwc-input-changed="${(e: OrInputChangedEvent) => {
- // Means field has lost focus so do filter immediately
- this._onFilterInput((e.detail.value as string) || undefined, true);
- }}">
+ this._onFilterInput(this._filterInput.nativeValue);
+ }, 200)}">
</or-mwc-input>
<or-icon id="filterSettingsIcon" icon="${this._filterSettingOpen ? "window-close" : "tune"}" title="${i18next.t(this._filterSettingOpen ? "filter.close" : "filter.open")}" @click="${() => {
if (this._filterSettingOpen) {
@@ -595,23 +574,34 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
</div>
</div>
`)}
-
- ${!this._nodes
- ? html`
- <span id="loading"><or-translate value="loading"></or-translate></span>`
- : ((this._nodes.length === 0 || !this.atLeastOneNodeToBeShown())
- ? html `<span id="noAssetsFound"><or-translate value="noAssetsFound"></or-translate></span>`
- : html`
- <div id="list-container">
- <ol id="list">
- ${this._nodes.map((treeNode) => this._treeNodeTemplate(treeNode, 0)).filter(t => !!t)}
- <li class="asset-list-element">
- <div class="end-element" node-asset-id="${''}" @dragleave=${(ev: DragEvent) => { this._onDragLeave(ev) }} @dragenter="${(ev: DragEvent) => this._onDragEnter(ev)}" @dragend="${(ev: DragEvent) => this._onDragEnd(ev)}" @dragover="${(ev: DragEvent) => this._onDragOver(ev)}"></div>
- </li>
- </ol>
- </div>
- `)
- }
+
+ ${when(!this._nodes, () => html`
+ <span id="loading"><or-translate value="loading"></or-translate></span>
+ `, () => html`
+ ${when(this._nodes!.length === 0 || !this.atLeastOneNodeToBeShown(),
+ () => html`<span id="noAssetsFound"><or-translate value="noAssetsFound"></or-translate></span>`,
+ () => html`
+ <div id="list-container">
+ <ol id="list">
+ ${this._nodes?.filter(n => n && !n.hidden).map(node => this._treeNodeTemplate(node, 0))}
+ ${when(this._hasMoreParents, () => html`
+ <li class="asset-list-element">
+ <div class="end-element loadmore-element" node-asset-id="${''}" @dragleave=${(ev: DragEvent) => { this._onDragLeave(ev) }}
+ @dragenter="${(ev: DragEvent) => this._onDragEnter(ev)}" @dragend="${(ev: DragEvent) => this._onDragEnd(ev)}"
+ @dragover="${(ev: DragEvent) => this._onDragOver(ev)}">
+ <or-mwc-input type=${InputType.BUTTON} label="loadMore" outlined compact @or-mwc-input-changed=${() => {
+ const cache: Asset[] = [];
+ OrAssetTree._forEachNodeRecursive(this._nodes ?? [], n => n.asset && cache.push(n.asset));
+ this._loadAssets(undefined, this._nodes?.length ?? 0, cache);
+ }}></or-mwc-input>
+ </div>
+ </li>
+ `)}
+ </ol>
+ </div>
+ `
+ )}
+ `)}
<div id="footer">
@@ -627,16 +617,18 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
const result = super.shouldUpdate(_changedProperties);
if (_changedProperties.has("assets")
|| _changedProperties.has("rootAssets")
- || _changedProperties.has("rootAssetIds")) {
- this._nodes = undefined;
+ || _changedProperties.has("rootAssetIds")
+ || _changedProperties.has("queryLimit")
+ ) {
+ this.refresh();
}
if (!this._nodes) {
- this._loadAssets();
+ this._loadAssets().catch(console.warn);
return true;
}
- if (_changedProperties.has("selectedIds")) {
+ if (_changedProperties.has("selectedIds") && this.selectedIds !== undefined) {
const previous: string[] | undefined = _changedProperties.get("selectedIds");
if (!Util.objectsEqual(previous, this.selectedIds)) {
this._updateSelectedNodes();
@@ -665,11 +657,13 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
}
protected _updateSelectedNodes() {
- const actuallySelectedIds: string[] = [];
- const selectedNodes: UiAssetTreeNode[] = [];
+ let actuallySelectedIds: string[] | undefined;
+ let selectedNodes: UiAssetTreeNode[] | undefined;
OrAssetTree._forEachNodeRecursive(this._nodes!, (node) => {
if (this.selectedIds && this.selectedIds.indexOf(node.asset!.id!) >= 0) {
+ actuallySelectedIds ??= [];
actuallySelectedIds.push(node.asset!.id!);
+ selectedNodes ??= [];
selectedNodes.push(node);
node.selected = true;
@@ -693,9 +687,9 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
parent.someChildrenSelected = false;
parent.allChildrenSelected = false;
- if (allChildren.every(c => actuallySelectedIds.includes(c.asset!.id!))) {
+ if (allChildren.every(c => actuallySelectedIds?.includes(c.asset!.id!))) {
parent.allChildrenSelected = true;
- } else if (allChildren.some(c => actuallySelectedIds.includes(c.asset!.id!))) {
+ } else if (allChildren.some(c => actuallySelectedIds?.includes(c.asset!.id!))) {
parent.someChildrenSelected = true;
}
@@ -704,13 +698,17 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
}
});
- this.selectedIds = actuallySelectedIds;
- const oldSelection = this._selectedNodes;
- this._selectedNodes = selectedNodes;
- this.dispatchEvent(new OrAssetTreeSelectionEvent({
- oldNodes: oldSelection,
- newNodes: selectedNodes
- }));
+ if(actuallySelectedIds?.length) {
+ this.selectedIds = actuallySelectedIds;
+ }
+ if(selectedNodes !== undefined || this.selectedNodes !== undefined) {
+ const oldSelection = this._selectedNodes;
+ this._selectedNodes = selectedNodes ?? [];
+ this.dispatchEvent(new OrAssetTreeSelectionEvent({
+ oldNodes: oldSelection,
+ newNodes: selectedNodes ?? []
+ }));
+ }
}
protected _updateSort(nodes: UiAssetTreeNode[], sortFunction: (a: UiAssetTreeNode, b: UiAssetTreeNode) => number) {
@@ -722,18 +720,30 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
nodes.forEach((node) => this._updateSort(node.children, sortFunction));
}
- protected _toggleExpander(expander: HTMLElement, node: UiAssetTreeNode | null, silent: boolean = false) {
+ protected async _toggleExpander(expander: HTMLElement, node: UiAssetTreeNode | null, silent: boolean = false) {
if (node && node.expandable) {
node.expanded = !node.expanded;
if (node.expanded) {
this._expandedNodes.push(node);
+
+ // Load children (from cache or using WebSocket) of the now 'expanded' node
+ const hasCachedChildren = node.children?.length;
+ if(hasCachedChildren) {
+ console.debug(`Reusing cache for loading children of asset ${node.asset?.id}...`);
+ } else {
+ const cache: Asset[] = [];
+ OrAssetTree._forEachNodeRecursive(this._nodes ?? [], n => n.asset && cache.push(n.asset));
+ await this._loadAssets(node.asset?.id, 0, cache).catch(e => console.warn(e));
+ }
+
} else {
this._expandedNodes = this._expandedNodes.filter(n => n !== node);
}
+ // Update HTML attributes of the now 'expanded' node
const elem = expander.parentElement!.parentElement!.parentElement!;
- elem.toggleAttribute("data-expanded");
+ elem.toggleAttribute("data-expanded", node.expanded);
if (!silent) {
this.dispatchEvent(new OrAssetTreeToggleExpandEvent({node: node}));
}
@@ -809,9 +819,17 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
const isExpander = evt && (evt.target as HTMLElement).className.indexOf("expander") >= 0;
const isParentCheckbox = evt && (evt.target as OrIcon)?.icon?.includes("checkbox-multiple");
+ const isLoadMoreButton = evt && (evt.target as OrMwcInput)?.parentElement?.classList.contains("loadmore-element");
if (isExpander) {
this._toggleExpander((evt.target as HTMLElement), node);
+
+ } else if (isLoadMoreButton) {
+ if(node) {
+ const cache: Asset[] = [];
+ OrAssetTree._forEachNodeRecursive(this._nodes ?? [], n => n.asset && cache.push(n.asset));
+ this._loadAssets(node.asset?.id, node.children?.length ?? 0, cache);
+ }
} else {
let canSelect = true;
@@ -1095,45 +1113,27 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
this._doFiltering();
}
- protected _onFilterInputEvent(_e: KeyboardEvent) {
- this._onFilterInput(this._filterInput?.nativeValue, false);
- }
-
- protected _onFilterInput(newValue: string | undefined, force: boolean): void {
+ protected _onFilterInput(newValue: string | undefined): void {
this.applyFilter(newValue);
-
- if (this._searchInputTimer) {
- clearTimeout(this._searchInputTimer);
- }
-
- if (!force) {
- this._searchInputTimer = window.setTimeout(() => {
- this._doFiltering();
- }, 350);
- } else {
- this._doFiltering();
- }
+ this._doFiltering();
}
protected async _doFiltering() {
- // Clear timeout in case we got here from value change
- if (this._searchInputTimer) {
- clearTimeout(this._searchInputTimer);
- this._searchInputTimer = undefined;
- }
if (this.isConnected && this._nodes) {
- if (!this._filter.asset && !this._filter.attribute && !this._filter.assetType && !this._filter.attributeValue) {
- // Clear the filter
+ // Clear filter if everything is not set anymore
+ if (!this._filter.asset?.length && !this._filter.attribute?.length && !this._filter.assetType?.length && !this._filter.attributeValue?.length) {
+ console.debug("Clearing asset tree filter...");
OrAssetTree._forEachNodeRecursive(this._nodes!, (node) => {
node.notMatchingFilter = false;
node.hidden = false;
});
- this.requestUpdate("_nodes");
+ this.refresh(); // Clear cache, and refetch the assets
return;
}
+ console.debug("Filtering asset tree using filter:", this._filter);
this.disabled = true;
// Use a matcher function - this can be altered independent of the filtering logic
@@ -1145,11 +1145,29 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
queryRequired = true;
}
- this.getMatcher(queryRequired).then((matcher: (asset: Asset) => boolean) => {
+ this.getMatcher(queryRequired).then(({ matcher, assets }) => {
+ assets ??= [];
if (this._nodes) {
- this._nodes.forEach((node: UiAssetTreeNode) => {
- this.filterTreeNode(node, matcher);
+
+ // Add nodes to the tree if not done yet
+ const cache: Asset[] = [];
+ OrAssetTree._forEachNodeRecursive(this._nodes ?? [], n => n.asset && cache.push(n.asset));
+ const assetsWithoutDuplicates = new Map([...cache, ...assets].map(item => [item.id, item])).values();
+ this._buildTreeNodes([...assetsWithoutDuplicates]);
+
+ // Filter out nodes that should not be visible
+ const visibleNodes = new Map<string, boolean>();
+ OrAssetTree._forEachNodeRecursive(this._nodes ?? [], n => {
+ const visible = this.filterTreeNode(n, matcher);
+ if(visible && !n.notMatchingFilter && n.asset?.id) {
+ visibleNodes.set(n.asset.id, visible);
+ }
});
+ // If only 1 asset is shown, automatically select it
+ if(visibleNodes.size === 1) {
+ console.debug("Only 1 asset is shown, automatically selecting it...");
+ this.selectedIds = Array.from(visibleNodes.keys());
+ }
this.disabled = false;
}
});
@@ -1157,11 +1175,11 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
}
}
- protected getMatcher(requireQuery: boolean): Promise<((asset: Asset) => boolean)> {
+ protected async getMatcher(requireQuery: boolean): Promise<{ matcher: ((asset: Asset) => boolean), assets?: Asset[]}> {
if (requireQuery) {
return this.getMatcherFromQuery();
} else {
- return this.getSimpleNameMatcher();
+ return { matcher: await this.getSimpleNameMatcher() };
}
}
@@ -1179,7 +1197,7 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
};
}
- protected async getMatcherFromQuery(): Promise<((asset: Asset) => boolean)> {
+ protected async getMatcherFromQuery(): Promise<{ assets: Asset[], matcher: ((asset: Asset) => boolean)}> {
let assetCond: StringPredicate[] | undefined;
let attributeCond: LogicGroup<AttributePredicate> | undefined;
let assetTypeCond: string[] | undefined;
@@ -1216,17 +1234,27 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
}
assetQueries.push({
+ realm: {
+ name: manager.displayRealm
+ },
select: {
attributes: attributeCond ? undefined : []
},
+ orderBy: {
+ property: this._getOrderBy(this.sortBy)
+ },
names: assetCond,
types: assetTypeCond,
- attributes: attributeCond
+ attributes: attributeCond,
+ limit: Math.max(this.queryLimit, 1)
});
// If the "Asset string input" is 22 characters long, we also query for the asset id
if(this._filter.asset && this._filter.asset.length === 22) {
assetQueries.push({
+ realm: {
+ name: manager.displayRealm
+ },
select: {
attributes: attributeCond ? undefined : []
},
@@ -1237,26 +1265,46 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
});
}
- let foundAssets: Asset[];
+ let foundAssets: Asset[] = [];
let foundAssetIds: string[];
- try {
- const promises = assetQueries.map(q => manager.rest.api.AssetResource.queryAssets(q));
- const responses = await Promise.all(promises);
- foundAssets = responses.flatMap(r => r.data);
- foundAssetIds = foundAssets.map(a => a.id!);
-
- } catch (e) {
- console.error("Error querying Asset Tree assets with filter:", e);
- this._filter.assetType.forEach((assetT: string) => {
- if (this._assetTypes.findIndex((assetD: AssetDescriptor) => assetD.name === assetT) === -1) {
- showSnackbar(undefined, "filter.assetTypeDoesNotExist", "dismiss");
- }
- });
- foundAssetIds = [];
- }
+ try {
+ console.debug(`Querying assets using filter '${this._filterInput.nativeValue}'...`);
+ const promises = assetQueries.map(q => manager.rest.api.AssetResource.queryAssets(q));
+ const responses = await Promise.all(promises);
+ foundAssets = responses.flatMap(r => r.data);
+ foundAssetIds = foundAssets.map(a => a.id!);
+ console.debug(`The filter query found ${foundAssets.length} assets!`);
- return (asset) => {
+ } catch (e) {
+ console.error("Error querying Asset Tree assets with filter:", e);
+ this._filter.assetType.forEach((assetT: string) => {
+ if (this._assetTypes.findIndex((assetD: AssetDescriptor) => assetD.name === assetT) === -1) {
+ showSnackbar(undefined, "filter.assetTypeDoesNotExist", "dismiss");
+ }
+ });
+ foundAssetIds = [];
+ }
+
+ // Query parents of the found assets if not cached yet.
+ const parentIds = new Set(foundAssets.filter(a => a.path && a.path.length > 1).flatMap(a => a.path!.slice(0, -1)));
+ const unknownParentIds = Array.from(parentIds).filter(id => id && !this.assets?.some(a => a.id === id));
+ if (unknownParentIds.length > 0) {
+ try {
+ console.debug(`Querying parents of ${unknownParentIds.length} assets...`);
+ const parentAssets = await manager.rest.api.AssetResource.queryAssets({
+ select: { attributes: attributeCond ? undefined : [] },
+ ids: unknownParentIds
+ });
+ console.debug(`The filter query found ${parentAssets.data.length} parents!`);
+ foundAssetIds = foundAssets.map(a => a.id!);
+ foundAssets = [...foundAssets, ...parentAssets.data];
+ } catch (e) {
+ console.error("Error querying Asset Tree parents of found assets:", e);
+ }
+ }
+
+ return { assets: foundAssets, matcher: (asset) => {
let attrValueCheck = true;
if (this._filter.attribute.length > 0 && this._filter.attributeValue.length > 0 && foundAssetIds.includes(asset.id!)) {
@@ -1350,7 +1398,7 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
}
return foundAssetIds.includes(asset.id!) && attrValueCheck;
- };
+ }};
}
protected isAnyFilter(): boolean {
@@ -1580,17 +1628,14 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
}, {
paramsSerializer: params => Qs.stringify(params, {arrayFormat: 'repeat'})
}).then((response) => {
- // Clear nodes to re-fetch them
- this.refresh();
- this.disabled = false;
-
+ this._onDeselectClicked();
if (response.status !== 204) {
showErrorDialog(i18next.t("deleteAssetsFailed"));
}
}).catch((reason) => {
- this.refresh();
- this.disabled = false;
showErrorDialog(i18next.t("deleteAssetsFailed"));
+ }).finally(() => {
+ this.disabled = false;
});
};
@@ -1667,66 +1712,110 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
}
}
- protected _loadAssets() {
+ protected _getOrderBy(sortBy?: string): AssetQueryOrderBy$Property {
+ switch (sortBy) {
+ case "createdOn": return AssetQueryOrderBy$Property.CREATED_ON;
+ case "type": return AssetQueryOrderBy$Property.ASSET_TYPE;
+ default: return AssetQueryOrderBy$Property.NAME;
+ }
+ }
- const sortFunction = this._getSortFunction();
+ /**
+ * Main function to load assets and populate the tree.
+ * Based on the HTML attributes of this component, it either fetches using a WebSocket connection or using a dataProvider.
+ * Once retrieved, these assets will be passed along to the {@link _buildTreeNodes} to construct the tree nodes.
+ * If the user has applied a filter, it will also be taken into count using {@link _doFiltering}.
+ *
+ * @param parentId - The parent ID an asset MUST be a child of during WebSocket retrieval. This is useful for pagination.
+ * @param offset - Offset number of the assets to request through WebSocket. This is useful for pagination.
+ * @param cache - An array of assets to populate the tree with alongside the retrieved nodes.
+ * @protected
+ */
+ protected async _loadAssets(parentId?: string, offset = 0, cache?: Asset[]): Promise<AssetTreeEvent | undefined> {
+ console.debug(`Loading assets with ${parentId ? `parent ${parentId}` : `no parents`}...`);
- if (!this.assets) {
+ // If asset objects are provided in the HTML attribute, load these instead.
+ if (this.assets) {
+ console.debug(`Assets already pre-loaded using HTML attributes; reusing them to construct the tree UI...`);
+ this._loading = false;
+ this._buildTreeNodes(this.assets);
+ return;
+ }
- if (!this._connected) {
- return;
- }
+ if (!this._connected) {
+ throw new Error("Not connected to the server; cannot load assets.");
+ }
- if (this._loading) {
- return;
- }
+ if (this._loading) {
+ throw new Error("Already loading assets for asset tree; ignoring request.");
+ }
- this._loading = true;
+ this._loading = true;
- if(this.dataProvider) {
- this.dataProvider().then(assets => {
- this._loading = false;
- this._buildTreeNodes(assets, sortFunction);
- if(this._filterInput?.value) {
- this._doFiltering();
- }
- })
+ if(this.dataProvider) {
+ this.dataProvider().then(assets => {
+ this._loading = false;
+ this._buildTreeNodes(assets);
+ if(this._filterInput?.value) {
+ this._doFiltering();
+ }
+ });
- } else {
+ } else {
+ const query: AssetQuery = {
+ realm: {
+ name: manager.displayRealm
+ },
+ parents: parentId ? [{ id: parentId }] : [], // Filters by parent ID. If parentId is null, it will only request 'top level' assets.
+ select: { // Just need the basic asset info
+ attributes: []
+ },
+ orderBy: {
+ property: this._getOrderBy(this.sortBy)
+ },
+ offset: offset,
+ limit: Math.max(this.queryLimit, 1)
+ };
- const query: AssetQuery = {
- realm: {
- name: manager.displayRealm
- },
- select: { // Just need the basic asset info
- attributes: []
- }
- };
-
- if (this.assetIds) {
- query.ids = this.assetIds;
- query.recursive = true;
- } else if (this.rootAssets) {
- query.ids = this.rootAssets.map((asset) => asset.id!);
- query.recursive = true;
- } else if (this.rootAssetIds) {
- query.ids = this.rootAssetIds;
- query.recursive = true;
- }
- this._sendEventWithReply({
- eventType: "read-assets",
- assetQuery: query
- }).then((ev) => {
- this._loading = false;
- this._buildTreeNodes((ev as AssetsEvent).assets!, sortFunction);
- if(this._filterInput?.value) {
- this._doFiltering();
- }
- });
+ if (this.assetIds) {
+ query.ids = this.assetIds;
+ query.recursive = true;
+ } else if (this.rootAssets) {
+ query.ids = this.rootAssets.map((asset) => asset.id!);
+ query.recursive = true;
+ } else if (this.rootAssetIds) {
+ query.ids = this.rootAssetIds;
+ query.recursive = true;
}
- } else {
- this._loading = false;
- this._buildTreeNodes(this.assets, sortFunction);
+ const eventPromise = this._sendEventWithReply({
+ eventType: "read-asset-tree",
+ assetQuery: query
+ });
+ eventPromise.then(ev => {
+ const newAssets = (ev as AssetTreeEvent).assetTree?.assets ?? [];
+ const hasMore = (ev as AssetTreeEvent).assetTree?.hasMore ?? false;
+ if(!parentId) {
+ this._hasMoreParents = hasMore;
+ } else if(parentId && this._incompleteParentIds.includes(parentId) && !hasMore) {
+ this._incompleteParentIds = this._incompleteParentIds.filter(id => id !== parentId);
+ } else if(parentId && hasMore) {
+ this._incompleteParentIds = [...this._incompleteParentIds, parentId];
+ }
+ console.debug(`Received read-assets-tree event with ${newAssets.length} assets.`);
+ console.debug(`Combining these assets with the cache of ${cache?.length ?? 0} assets...`);
+ this._loading = false;
+ if(cache) {
+ const assets = [...cache, ...newAssets.filter(a => !cache.find(c => c.id === a.id))];
+ this._buildTreeNodes(assets);
+ } else {
+ this._buildTreeNodes(newAssets);
+ }
+ if(this._filterInput?.value) {
+ this._doFiltering();
+ }
+ }) as Promise<AssetTreeEvent>;
+
+ return eventPromise as Promise<AssetTreeEvent>;
}
}
@@ -1741,7 +1830,7 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
public onEventsConnect() {
this._connected = true;
- this._loadAssets();
+ this._loadAssets().catch(console.warn);
}
public onEventsDisconnect() {
@@ -1757,7 +1846,7 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
if (event.eventType === "assets") {
const assetsEvent = event as AssetsEvent;
- this._buildTreeNodes(assetsEvent.assets!, this._getSortFunction());
+ this._buildTreeNodes(assetsEvent.assets!);
return;
}
@@ -1787,7 +1876,7 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
}
// In case of filter already active, do not override the actual state of assetTree
- this._buildTreeNodes(assets, this._getSortFunction());
+ this._buildTreeNodes(assets);
if (this._filterInput?.value) {
this._doFiltering();
}
@@ -1795,9 +1884,14 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
}
}
-
-
- protected _buildTreeNodes(assets: Asset[], sortFunction: (a: UiAssetTreeNode, b: UiAssetTreeNode) => number) {
+ /**
+ * Function that creates and constructs the tree node objects to display.
+ * @param assets - List of assets to display in the tree
+ * @param sortFunction - Optional sorting function for ordering the nodes
+ * @protected
+ */
+ protected _buildTreeNodes(assets: Asset[], sortFunction = this._getSortFunction()) {
+ console.debug(`Building asset tree nodes for ${assets.length} assets...`);
if (!assets || assets.length === 0) {
this._nodes = [];
} else {
@@ -1875,7 +1969,7 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
const newExpanded: UiAssetTreeNode[] = [];
this._expandedNodes.forEach(expandedNode => {
OrAssetTree._forEachNodeRecursive(this._nodes!, n => {
- if (n.asset && expandedNode && expandedNode.asset && n.asset.id === expandedNode.asset.id) {
+ if (n.asset?.id && expandedNode?.asset?.id && n.asset.id === expandedNode.asset.id && this.isExpandable(expandedNode.asset.id)) {
n.expanded = true;
newExpanded.push(n);
@@ -1894,6 +1988,7 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
this._expandedNodes = newExpanded;
}
+ console.debug(`Asset tree nodes built. Now selecting ${this.selectedIds?.length} nodes...`);
if (this.selectedIds && this.selectedIds.length > 0) {
this._updateSelectedNodes();
}
@@ -1910,10 +2005,7 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
protected _buildChildTreeNodes(treeNode: UiAssetTreeNode, assets: AssetWithReparentId[], sortFunction: (a: UiAssetTreeNode, b: UiAssetTreeNode) => number) {
let children: UiAssetTreeNode[] | undefined = this.assetsChildren[treeNode.asset!.id!];
treeNode.children = children ? children.sort(sortFunction) : [];
-
- if (treeNode.children.length > 0) {
- treeNode.expandable = true;
- }
+ treeNode.expandable = (treeNode.asset as any)?.hasChildren || treeNode.children?.length;
treeNode.children.forEach((childNode) => {
childNode.parent = treeNode;
@@ -2004,7 +2096,7 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
}
public _onDragEnter(ev: any): void {
- let currentElement = ev.currentTarget as HTMLElement;
+ let currentElement = ev.currentTarget as HTMLElement;
currentElement.classList.add('over');
@@ -2022,6 +2114,12 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
this._expandTimer = undefined;
}
+ /**
+ * Generates the HTML TemplateResult for an individual node / tree item.
+ * @param treeNode Node to display
+ * @param level Level of depth in the tree from 0 to infinite. (0 = top level. If it has 2 parents, level = 2)
+ * @protected
+ */
protected _treeNodeTemplate(treeNode: UiAssetTreeNode, level: number): TemplateResult | string | undefined {
const descriptor = AssetModelUtil.getAssetDescriptor(treeNode.asset!.type!);
@@ -2045,6 +2143,7 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
}
if (treeNode.expanded && treeNode.children.length === 0) {
+ console.debug("Tree node has no children, collapsing it...");
treeNode.expanded = false;
}
@@ -2076,6 +2175,11 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {
</div>
<ol>
${!treeNode.children || (treeNode.expandable && !treeNode.expanded) ? `` : treeNode.children.map((childNode) => this._treeNodeTemplate(childNode, level + 1)).filter(t => !!t)}
+ ${when(treeNode.asset?.id && this._incompleteParentIds.includes(treeNode.asset.id), () => html`
+ <li class="asset-list-element loadmore-element">
+ <or-mwc-input type=${InputType.BUTTON} outlined label="loadMore" style="padding-left: ${(level + 1) * 22}px;"></or-mwc-input>
+ </li>
+ `)}
</ol>
</li>
`;
diff --git a/ui/component/or-asset-tree/src/style.ts b/ui/component/or-asset-tree/src/style.ts
index 3e373cb65..0fcb833a0 100644
--- a/ui/component/or-asset-tree/src/style.ts
+++ b/ui/component/or-asset-tree/src/style.ts
@@ -98,6 +98,7 @@ export const style = css`
margin: 0;
color: var(--internal-or-asset-tree-text-color);
padding: 0;
+ height: 100%;
}
#list, ol {
@@ -108,6 +109,10 @@ export const style = css`
padding: 0;
}
+ #list li {
+ width: 100%;
+ }
+
#list li:not([data-expanded]) > ol {
display: none;
}
@@ -132,9 +137,14 @@ export const style = css`
padding: 5px 0;
margin: -5px 0;
}
- .end-element {
+ .end-element, .loadmore-element {
height: 44px;
}
+ .loadmore-element {
+ display: flex;
+ padding-left: 15px;
+ align-items: center;
+ }
.node-container {
display: flex;
diff --git a/ui/component/or-asset-tree/test/fixtures/index.ts b/ui/component/or-asset-tree/test/fixtures/index.ts
index 50c5e9f31..27d48d1bf 100644
--- a/ui/component/or-asset-tree/test/fixtures/index.ts
+++ b/ui/component/or-asset-tree/test/fixtures/index.ts
@@ -1,4 +1,5 @@
import type {Page} from "@openremote/test";
+import type {Locator} from "@playwright/test";
export class AssetTree {
constructor(private readonly page: Page) {}
@@ -11,18 +12,18 @@ export class AssetTree {
}
/**
- * Fills the filter input with the supplied text
- * @param text - Text to filter nodes by
+ * Returns a locator of all nodes that contain assets
*/
- fillFilterInput(text: string) {
- return this.page.fill(`or-asset-tree #filterInput input[type="text"]`, text);
+ getAssetNodes() {
+ return this.page.locator(`or-asset-tree ol li:has(.node-container[node-asset-id]:not([node-asset-id=""]))`);
}
/**
- * Returns a locator of all nodes that contain assets
+ * Returns a locator of all child nodes of the supplied node
+ * @param node - Locator pointing to the parent node
*/
- getAssetNodes() {
- return this.page.locator(`or-asset-tree ol li [node-asset-id]:not([node-asset-id=""])`);
+ getChildNodes(node: Locator) {
+ return node.locator(`ol li .node-container[node-asset-id]:not([node-asset-id=""])`);
}
/**
diff --git a/ui/component/or-asset-viewer/test/fixtures/index.ts b/ui/component/or-asset-viewer/test/fixtures/index.ts
index b4929705f..a35f797a4 100644
--- a/ui/component/or-asset-viewer/test/fixtures/index.ts
+++ b/ui/component/or-asset-viewer/test/fixtures/index.ts
@@ -15,6 +15,14 @@ export class AssetViewer {
await selector.click();
}
+ /**
+ * Get a locator to the asset header.
+ * @param assetName The asset name
+ */
+ getHeaderLocator(assetName: string) {
+ return this.page.locator(`#asset-header`, { hasText: assetName });
+ }
+
/**
* Get a locator to an attribute.
* @param attribute The attribute name
diff --git a/ui/util/webpack.util.js b/ui/util/webpack.util.js
index 93c40c8f7..7303b4ca8 100644
--- a/ui/util/webpack.util.js
+++ b/ui/util/webpack.util.js
@@ -188,6 +188,14 @@ function getAppConfig(mode, isDevServer, dirname, managerUrl, keycloakUrl, port)
config.devtool = !isDevServer ? false : "inline-source-map";
config.devServer = {
+ client: {
+ overlay: {
+ runtimeErrors: (e) => {
+ console.error(e);
+ return false;
+ }
+ }
+ },
historyApiFallback: {
index: "/" + dirname.split(path.sep).slice(-1)[0] + "/",
},