100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
UI: Added ability to filter by ID in the asset tree (#2067)
Martin Peetersc4d3a36cf63e
diff --git a/ui/app/manager/.npmignore b/ui/app/manager/.npmignoreindex b2544e0f1..abed2c8ed 100644--- a/ui/app/manager/.npmignore+++ b/ui/app/manager/.npmignore@@ -4,6 +4,7 @@ test/src/webpack.config.jsrspack.config.js+playwright.config.tstsconfig.jsondist/*.map*.tsbuildinfodiff --git a/ui/app/manager/src/pages/page-assets.ts b/ui/app/manager/src/pages/page-assets.tsindex fe900847e..3502c1e9f 100644--- a/ui/app/manager/src/pages/page-assets.ts+++ b/ui/app/manager/src/pages/page-assets.ts@@ -13,7 +13,7 @@ import {} from "@openremote/or-asset-viewer";import {AssetTreeConfig, ChangeParentEventDetail,- OrAssetTree,+ OrAssetTree, OrAssetTreeFilter,OrAssetTreeAddEvent,OrAssetTreeAssetEvent,OrAssetTreeChangeParentEvent, OrAssetTreeRequestAddEvent,@@ -269,7 +269,17 @@ export class PageAssets extends Page<AssetsStateKeyed> {stateChanged(state: AssetsStateKeyed) {this.getRealmState(state); // Order is important here!this._editMode = !!(state.app.params && state.app.params.editMode === "true");- this._assetIds = state.app.params && state.app.params.ids ? state.app.params.ids.split(",") : undefined;+ if(state.app.params?.ids) {+ const newIds = state.app.params.ids.split(",");+ if(!Util.objectsEqual(this._assetIds, newIds, true)) {+ this._assetIds = newIds;+ if(this._assetIds.length === 1) {+ this.updateComplete.finally(() => this._tree?.applyFilter(new OrAssetTreeFilter(this._assetIds[0]), true));+ }+ }+ } else {+ this._assetIds = undefined;+ }}protected _onParentChangeClick() {diff --git a/ui/app/manager/test/assets.test.ts b/ui/app/manager/test/assets.test.tsindex 4904e5bcb..a60a40fa5 100644--- a/ui/app/manager/test/assets.test.ts+++ b/ui/app/manager/test/assets.test.ts@@ -1,7 +1,7 @@import { expect } from "@openremote/test";import { test, userStatePath } from "./fixtures/manager.js";import assets, { assetMap, assetPatches, thing } from "./fixtures/data/assets.js";-import { WellknownMetaItems } from "@openremote/model";+import {WellknownMetaItems} from "@openremote/model";import * as Util from "@openremote/core/lib/util";test.use({ storageState: userStatePath });@@ -42,15 +42,55 @@ assets.forEach(({ type, name, attributes }) => {* @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 }) => {+ 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 page.fill('#filterInput input[type="text"]', name);+ 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" realmdiff --git a/ui/app/manager/test/fixtures/manager.ts b/ui/app/manager/test/fixtures/manager.tsindex 3da5e8c7d..3154d17d5 100644--- a/ui/app/manager/test/fixtures/manager.ts+++ b/ui/app/manager/test/fixtures/manager.ts@@ -12,6 +12,7 @@ import { AssetsPage, RealmsPage, RolesPage, RulesPage, UsersPage } from "./pagesimport { 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";export const adminStatePath = path.join(__dirname, "data/.auth/admin.json");export const userStatePath = path.join(__dirname, "data/.auth/user.json");@@ -340,7 +341,7 @@ export class Manager {}}- protected getAppUrl(realm: string) {+ getAppUrl(realm: string) {return `${new URL(this.baseURL).origin}/manager/?realm=${realm}`;}}@@ -362,6 +363,7 @@ interface PageFixtures {interface ComponentFixtures extends ComponentTestFixtures {assetViewer: AssetViewer;+ assetTree: AssetTree;collapsiblePanel: CollapsiblePanel;jsonForms: JsonForms;}@@ -380,6 +382,7 @@ export const test = base.extend<Fixtures>({usersPage: withManager(UsersPage),// ComponentsassetViewer: withPage(AssetViewer),+ assetTree: withPage(AssetTree),collapsiblePanel: withPage(CollapsiblePanel),jsonForms: withPage(JsonForms),});diff --git a/ui/app/manager/test/fixtures/pages/assets.ts b/ui/app/manager/test/fixtures/pages/assets.tsindex a3cdce3e1..3c58c8d6e 100644--- a/ui/app/manager/test/fixtures/pages/assets.ts+++ b/ui/app/manager/test/fixtures/pages/assets.ts@@ -9,6 +9,10 @@ export class AssetsPage implements BasePage {this.manager.navigateToTab("Assets");}+ async gotoAssetId(realm: string, id: string, editor = false) {+ this.page.goto(this.manager.getAppUrl(realm) + `#/assets/${editor}/${id}`);+ }+/*** Add asset of type and with name.*diff --git a/ui/component/or-asset-tree/src/index.ts b/ui/component/or-asset-tree/src/index.tsindex 01928e153..46623f1b4 100644--- a/ui/component/or-asset-tree/src/index.ts+++ b/ui/component/or-asset-tree/src/index.ts@@ -226,8 +226,8 @@ export class OrAssetTreeFilter {attribute: string[];attributeValue: string[];- constructor() {- this.asset = undefined;+ constructor(asset?: string) {+ this.asset = asset;this.assetType = [];this.attribute = [];this.attributeValue = [];@@ -396,6 +396,26 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {return false;}+ /**+ * A setter function for updating the list of nodes (assets) shown in the UI.+ * @param filter - The {@link OrAssetTreeFilter} to apply.+ * @param reflect - If the changes should be reflected in the filtering UI. (default: false)+ */+ public applyFilter(filter?: OrAssetTreeFilter | string, reflect = false) {+ if(!filter || typeof filter === "string") {+ filter = this.parseFromInputFilter(filter);+ }+ if (Util.objectsEqual(this._filter, filter)) {+ console.debug("Tried to apply filter to the asset tree, but it was the same.", filter);+ return;+ }+ console.debug("Applying filter to the asset tree:", filter);+ this._filter = filter;+ if(reflect) {+ this.updateComplete.finally(() => this._filterInput.value = this.formatFilter(filter));+ }+ }+protected mapDescriptors(descriptors: (AssetDescriptor)[], withNoneValue?: ListItem): ListItem[] {let items: ListItem[] = descriptors.map((descriptor) => {return {@@ -563,7 +583,7 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {this._assetTypeFilter = '';- this._filter = new OrAssetTreeFilter();+ this.applyFilter(new OrAssetTreeFilter());// Call filteringthis._doFiltering();@@ -600,7 +620,7 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {}protected _isReadonly() {- return this.readonly || !manager.hasRole(ClientRole.WRITE_ASSETS);+ return this.readonly || !manager.authenticated || !manager.hasRole(ClientRole.WRITE_ASSETS);}protected shouldUpdate(_changedProperties: PropertyValues): boolean {@@ -617,8 +637,17 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {}if (_changedProperties.has("selectedIds")) {- if (!Util.objectsEqual(_changedProperties.get("selectedIds"), this.selectedIds)) {+ const previous: string[] | undefined = _changedProperties.get("selectedIds");+ if (!Util.objectsEqual(previous, this.selectedIds)) {this._updateSelectedNodes();++ // When selecting a different node than present in the Asset ID filter, it should be removed+ if (previous?.length === 1 && this._filter.asset === previous[0]) {+ this.applyFilter(new OrAssetTreeFilter(), true);+ if (!this.selectedIds?.length) {+ this._doFiltering(); // Only update UI if there is no selection, to prevent flickering+ }+ }}}@@ -907,16 +936,12 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {this._onNodeClicked(null, null);}- protected parseFromInputFilter(inputValue?: string): OrAssetTreeFilter {- let searchValue: string | undefined = this._filterInput.value;- if (inputValue) {- searchValue = inputValue;- }+ protected parseFromInputFilter(inputValue = this._filterInput?.value): OrAssetTreeFilter {let resultingFilter: OrAssetTreeFilter = new OrAssetTreeFilter();- if (searchValue) {- let asset: string = searchValue;- let matchingResult: RegExpMatchArray | null = searchValue.match(/(attribute\:)(\"[^"]+\")\S*/g);+ if (inputValue) {+ let asset: string = inputValue;+ let matchingResult: RegExpMatchArray | null = inputValue.match(/(attribute\:)(\"[^"]+\")\S*/g);if (matchingResult) {if (matchingResult.length > 0) {matchingResult.forEach((value: string, index: number) => {@@ -934,7 +959,7 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {this._attributeValueFilter.disabled = false;}- matchingResult = searchValue.match(/(type\:)\S+/g);+ matchingResult = inputValue.match(/(type\:)\S+/g);if (matchingResult) {if (matchingResult.length > 0) {matchingResult.forEach((value: string, index: number) => {@@ -949,7 +974,7 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {}}- matchingResult = searchValue.match(/(\"[^\"]+\")\:(([^\"\s]+)|(\"[^\"]+\"))/g);+ matchingResult = inputValue.match(/(\"[^\"]+\")\:(([^\"\s]+)|(\"[^\"]+\"))/g);if (matchingResult) {if (matchingResult.length > 0) {matchingResult.forEach((value: string, index: number) => {@@ -1059,7 +1084,7 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {let filterFromSearchInputWithSettings: OrAssetTreeFilter = this.applySettingFields(filterFromSearchInput);- this._filter = filterFromSearchInputWithSettings;+ this.applyFilter(filterFromSearchInputWithSettings);let newFilterForSearchInput: string = this.formatFilter(this._filter);@@ -1070,24 +1095,12 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {this._doFiltering();}- protected _onFilterInputEvent(e: KeyboardEvent) {- let value: string | undefined;-- if (e.composedPath()) {- value = ((e.composedPath()[0] as HTMLInputElement).value) || undefined;- }-- this._onFilterInput(value, false);+ protected _onFilterInputEvent(_e: KeyboardEvent) {+ this._onFilterInput(this._filterInput?.nativeValue, false);}protected _onFilterInput(newValue: string | undefined, force: boolean): void {- let currentFilter: OrAssetTreeFilter = this.parseFromInputFilter(newValue);-- if (Util.objectsEqual(this._filter, currentFilter,true)) {- return;- }-- this._filter = currentFilter;+ this.applyFilter(newValue);if (this._searchInputTimer) {clearTimeout(this._searchInputTimer);@@ -1167,9 +1180,10 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {}protected async getMatcherFromQuery(): Promise<((asset: Asset) => boolean)> {- let assetCond: StringPredicate[] | undefined = undefined;- let attributeCond: LogicGroup<AttributePredicate> | undefined = undefined;- let assetTypeCond: string[] | undefined = undefined;+ let assetCond: StringPredicate[] | undefined;+ let attributeCond: LogicGroup<AttributePredicate> | undefined;+ let assetTypeCond: string[] | undefined;+ const assetQueries: AssetQuery[] = [];if (this._filter.asset) {assetCond = [{@@ -1198,34 +1212,49 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {}};})- }+ };}- const query: AssetQuery = {+ assetQueries.push({select: {attributes: attributeCond ? undefined : []},names: assetCond,types: assetTypeCond,attributes: attributeCond- };-+ });+ // 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({+ select: {+ attributes: attributeCond ? undefined : []+ },+ types: assetTypeCond,+ attributes: attributeCond,+ ids: [this._filter.asset],+ limit: 1+ });+ }- let response: any;+ let foundAssets: Asset[];let foundAssetIds: string[];try {- response = await manager.rest.api.AssetResource.queryAssets(query);- foundAssetIds = response.data.map((asset: Asset) => asset.id!);+ 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) {- this._filter.assetType.forEach((assetT: string) => {- if(this._assetTypes.findIndex((assetD: AssetDescriptor) => { return assetD.name === assetT; }) === -1) {- showSnackbar(undefined, "filter.assetTypeDoesNotExist", "dismiss");- }- });- foundAssetIds = [];- }+ 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 = [];+ }return (asset) => {let attrValueCheck = true;@@ -1239,7 +1268,7 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {}});- let matchingAsset: Asset | undefined = response.data.find((a: Asset) => a.id === asset.id );+ const matchingAsset: Asset | undefined = foundAssets.find((a: Asset) => a.id === asset.id );if (matchingAsset && matchingAsset.attributes) {for (let attributeValIndex = 0; attributeValIndex < attributeVal.length; attributeValIndex++) {@@ -1658,6 +1687,9 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {this.dataProvider().then(assets => {this._loading = false;this._buildTreeNodes(assets, sortFunction);+ if(this._filterInput?.value) {+ this._doFiltering();+ }})} else {@@ -1686,7 +1718,10 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {assetQuery: query}).then((ev) => {this._loading = false;- this._buildTreeNodes((ev as AssetsEvent).assets!, sortFunction)+ this._buildTreeNodes((ev as AssetsEvent).assets!, sortFunction);+ if(this._filterInput?.value) {+ this._doFiltering();+ }});}} else {@@ -1753,7 +1788,7 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {// In case of filter already active, do not override the actual state of assetTreethis._buildTreeNodes(assets, this._getSortFunction());- if (this._filterInput.value) {+ if (this._filterInput?.value) {this._doFiltering();}this.dispatchEvent(new OrAssetTreeAssetEvent(assetEvent));diff --git a/ui/component/or-asset-tree/test/fixtures/index.ts b/ui/component/or-asset-tree/test/fixtures/index.tsnew file mode 100644index 000000000..50c5e9f31--- /dev/null+++ b/ui/component/or-asset-tree/test/fixtures/index.ts@@ -0,0 +1,34 @@+import type {Page} from "@openremote/test";++export class AssetTree {+ constructor(private readonly page: Page) {}++ /**+ * Returns a locator of the filter input+ */+ getFilterInput() {+ return this.page.locator(`or-asset-tree #filterInput input[type="text"]`);+ }++ /**+ * Fills the filter input with the supplied text+ * @param text - Text to filter nodes by+ */+ fillFilterInput(text: string) {+ return this.page.fill(`or-asset-tree #filterInput input[type="text"]`, text);+ }++ /**+ * Returns a locator of all nodes that contain assets+ */+ getAssetNodes() {+ return this.page.locator(`or-asset-tree ol li [node-asset-id]:not([node-asset-id=""])`);+ }++ /**+ * Returns a locator of all nodes that are selected+ */+ getSelectedNodes() {+ return this.page.locator(`or-asset-tree ol li[data-selected]`);+ }+}diff --git a/ui/component/or-components/.npmignore b/ui/component/or-components/.npmignoreindex b2544e0f1..abed2c8ed 100644--- a/ui/component/or-components/.npmignore+++ b/ui/component/or-components/.npmignore@@ -4,6 +4,7 @@ test/src/webpack.config.jsrspack.config.js+playwright.config.tstsconfig.jsondist/*.map*.tsbuildinfodiff --git a/ui/component/or-json-forms/.npmignore b/ui/component/or-json-forms/.npmignoreindex b2544e0f1..abed2c8ed 100644--- a/ui/component/or-json-forms/.npmignore+++ b/ui/component/or-json-forms/.npmignore@@ -4,6 +4,7 @@ test/src/webpack.config.jsrspack.config.js+playwright.config.tstsconfig.jsondist/*.map*.tsbuildinfodiff --git a/ui/component/or-mwc-components/.npmignore b/ui/component/or-mwc-components/.npmignorenew file mode 100644index 000000000..abed2c8ed--- /dev/null+++ b/ui/component/or-mwc-components/.npmignore@@ -0,0 +1,10 @@+build/+build.gradle+test/+src/+webpack.config.js+rspack.config.js+playwright.config.ts+tsconfig.json+dist/*.map+*.tsbuildinfodiff --git a/ui/component/or-translate/.npmignore b/ui/component/or-translate/.npmignoreindex b2544e0f1..abed2c8ed 100644--- a/ui/component/or-translate/.npmignore+++ b/ui/component/or-translate/.npmignore@@ -4,6 +4,7 @@ test/src/webpack.config.jsrspack.config.js+playwright.config.tstsconfig.jsondist/*.map*.tsbuildinfo