Skip to content

armgit / core

Public Imported from GitHub
0

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

Improve When-Then JSON Rules UI for scaling to larger instances (#2271)

Martin Peeters2a385d30336c
diff --git a/ui/app/manager/test/fixtures/data/rules.ts b/ui/app/manager/test/fixtures/data/rules.ts
index 8a746a9c0..80b4dc5ea 100644
--- a/ui/app/manager/test/fixtures/data/rules.ts
+++ b/ui/app/manager/test/fixtures/data/rules.ts
@@ -1,8 +1,8 @@
export const energyRule = {
name: "Energy rule",
- attribute_type: "Thing asset",
+ asset_type: "Thing asset",
asset: "Battery",
attribute_when: "Energy level",
attribute_then: "Energy capacity",
- value: 50,
+ value: 50
};
diff --git a/ui/app/manager/test/rules.test.ts b/ui/app/manager/test/rules.test.ts
index 39d27385c..2794798d8 100644
--- a/ui/app/manager/test/rules.test.ts
+++ b/ui/app/manager/test/rules.test.ts
@@ -1,63 +1,127 @@
-import { expect } from "@openremote/test";
-import { test, userStatePath } from "./fixtures/manager.js";
-import { preparedAssetsForRules as assets } from "./fixtures/data/assets.js";
-import { energyRule } from "./fixtures/data/rules.js";
+import {expect} from "@openremote/test";
+import {test, userStatePath} from "./fixtures/manager.js";
+import {preparedAssetsForRules as assets} from "./fixtures/data/assets.js";
+import {energyRule} from "./fixtures/data/rules.js";
+import {Asset} from "@openremote/model";
+
+test.use({storageState: userStatePath});
/**
- * @given The realm "smartcity" with user "smartcity" and assets are set up
- * @and Logged into OpenRemote "smartcity" realm as "smartcity"
- * @and Navigated to the "Rules" tab
- * @and Click add new rule
+ * Simple function that generates assets based on {@link assets}
+ * @param multiplier - Amount of assets to generate per asset type
*/
-test.beforeEach(async ({ page, manager }) => {
- await manager.setup("smartcity", { assets });
- await manager.goToRealmStartPage("smartcity");
- await manager.navigateToTab("Rules");
- await page.click(".mdi-plus >> nth=0");
-});
-
-test.use({ storageState: userStatePath });
+function generateALotOfAssets(multiplier = 5): Asset[] {
+ return Array.from({length: multiplier}, (_, i) =>
+ assets.map((a: Asset) => ({...a, name: `${a.name} ${i}`}))
+ ).flat();
+}
/**
- * @when Selecting When-Then rule
+ * @when Creating a When-Then rule
* @and Naming the rule
* @and Configuring a When condition on the asset
* @and Configuring a Then action on the same asset
* @and Saving the rule
* @then The When-Then rule should appear in the rule list
*/
-test("Create a When-Then rule for an asset with a trigger and action", async ({ page, manager, shared }) => {
- await page.locator("li").filter({ hasText: "When-Then" }).click();
- await page.fill("text=Rule name", energyRule.name);
-
- await page.click("or-rule-when #component span");
- await page.locator("or-rule-when li").filter({ hasText: energyRule.attribute_type }).click();
- await page.click("text=Asset Any of this type");
- await page.click(`#idSelect >> text=${energyRule.asset}`);
- await page.getByRole("button", { name: "Attribute", exact: true }).click();
- await page.click(`li[role="option"]:has-text("${energyRule.attribute_when}")`);
- await page.getByRole("button", { name: "Operator", exact: true }).click();
- await page.click("text=Less than or equal to");
- await page.getByRole("spinbutton", { name: "Energy level" }).fill(energyRule.value.toString());
-
- await page.getByRole("button", { name: "Add action" }).click();
- await page.click(`or-rule-then-otherwise li[role="menuitem"]:has-text("${energyRule.attribute_type}")`);
- await page.click("text=Asset Matched");
- await page.click(`#matchSelect li[role="option"]:has-text("${energyRule.asset}")`);
- await page.getByRole("button", { name: "Attribute", exact: true }).click();
- await page.click(`li[role="option"]:has-text("${energyRule.attribute_then}")`);
- await page.getByRole("spinbutton", { name: "Value" }).fill(energyRule.value.toString());
-
- await shared.interceptResponse<number>("**/rules/realm", (rule) => {
- if (rule) manager.rules.push(rule);
- });
-
- await page.getByRole("button", { name: "Save" }).click();
- await expect(page.locator(`text=${energyRule.name}`)).toHaveCount(1);
+test("Create a When-Then rule for an asset with a trigger and action", async ({page, manager, shared}) => {
+ await manager.setup("smartcity", {assets});
+ await manager.goToRealmStartPage("smartcity");
+ await manager.navigateToTab("Rules");
+ await page.click(".mdi-plus >> nth=0");
+ await page.locator("li").filter({hasText: "When-Then"}).click();
+ await page.fill("text=Rule name", energyRule.name);
+
+ await page.click("or-rule-when #component span");
+ await page.locator("or-rule-when li").filter({hasText: energyRule.asset_type}).click();
+ await page.click("text=Asset Any of this type");
+ await page.click(`#idSelect >> text=${energyRule.asset}`);
+ await page.getByRole("button", {name: "Attribute", exact: true}).click();
+ await page.click(`li[role="option"]:has-text("${energyRule.attribute_when}")`);
+ await page.getByRole("button", {name: "Operator", exact: true}).click();
+ await page.click("text=Less than or equal to");
+ await page.getByRole("spinbutton", {name: "Energy level"}).fill(energyRule.value.toString());
+
+ await page.getByRole("button", {name: "Add action"}).click();
+ await page.click(`or-rule-then-otherwise li[role="menuitem"]:has-text("${energyRule.asset_type}")`);
+ await page.click("text=Asset Matched");
+ await page.click(`#matchSelect li[role="option"]:has-text("${energyRule.asset}")`);
+ await page.getByRole("button", {name: "Attribute", exact: true}).click();
+ await page.click(`li[role="option"]:has-text("${energyRule.attribute_then}")`);
+ await page.getByRole("spinbutton", {name: "Value"}).fill(energyRule.value.toString());
+
+ await shared.interceptResponse<number>("**/rules/realm", (rule) => {
+ if (rule) manager.rules.push(rule);
+ });
+
+ await page.getByRole("button", {name: "Save"}).click();
+ await expect(page.locator(`text=${energyRule.name}`)).toHaveCount(1);
+});
+
+/**
+ * @when Creating a When-Then rule
+ * @and Naming the rule
+ * @and Configuring a When condition by searching for a specific asset
+ * @and Configuring a Then action by searching for a different asset
+ * @and Saving the rule
+ * @then The When-Then rule should appear in the rule list
+ */
+test("Create a When-Then rule by searching for an asset", async ({page, manager, shared}) => {
+ const multiplier = 100;
+ const aLotOfAssets = generateALotOfAssets(multiplier);
+ await manager.setup("smartcity", {assets: aLotOfAssets});
+ await manager.goToRealmStartPage("smartcity");
+ await manager.navigateToTab("Rules");
+
+ // Make sure the correct amount assets are set up, and the variables for this rule are adjusted
+ expect(manager.assets.length).toBe(multiplier * assets.length);
+ const firstAssetName = [...manager.assets].find(a => a.name?.includes(energyRule.asset))?.name ?? "";
+ const lastAssetName = [...manager.assets].reverse().find(a => a?.name?.includes(energyRule.asset))?.name ?? "";
+ expect(firstAssetName).toContain(energyRule.asset);
+ expect(lastAssetName).toContain(energyRule.asset);
+
+ await page.click(".mdi-plus >> nth=0");
+ await page.locator("li").filter({hasText: "When-Then"}).click();
+ await page.fill("text=Rule name", energyRule.name);
+
+ // Select asset type of the When clause, search for the last asset in the list, and select the attribute
+ await page.click("or-rule-when #component span");
+ await page.locator("or-rule-when li").filter({hasText: energyRule.asset_type}).click();
+ await page.click(`text=Asset Any of this type`);
+ await expect(page.getByRole('textbox', { name: 'Search'})).toBeVisible();
+ await page.getByRole('textbox', {name: 'Search'}).click();
+ await page.keyboard.type(lastAssetName);
+ await expect(page.locator("or-rule-asset-query or-mwc-input li[role=option]").getByText(lastAssetName, { exact: true })).toBeVisible();
+ await page.locator("or-rule-asset-query or-mwc-input li[role=option]").filter({hasText: lastAssetName}).click();
+ await page.getByRole("button", {name: "Attribute", exact: true}).click();
+ await page.click(`or-rule-asset-query or-mwc-input li[role="option"]:has-text("${energyRule.attribute_when}")`);
+ await page.getByRole("button", {name: "Operator", exact: true}).click();
+ await page.click("text=Less than or equal to");
+ await page.getByRole("spinbutton", {name: "Energy level"}).fill(energyRule.value.toString());
+
+ // Configure Then clause
+ await page.getByRole("button", {name: "Add action"}).click();
+ await page.click(`or-rule-then-otherwise li[role="menuitem"]:has-text("${energyRule.asset_type}")`);
+ await page.click("text=Matched");
+ await expect(page.getByRole('textbox', { name: 'Search'})).toBeVisible();
+ await page.getByRole('textbox', {name: 'Search'}).click();
+ await page.keyboard.type(firstAssetName);
+ await expect(page.locator("or-rule-action-attribute or-mwc-input li[role=option]").getByText(firstAssetName, { exact: true })).toBeVisible();
+ await page.locator("or-rule-action-attribute or-mwc-input li[role=option]").filter({hasText: firstAssetName}).click();
+ await page.getByRole("button", {name: "Attribute", exact: true}).click();
+ await page.click(`or-rule-action-attribute or-mwc-input li[role=option]:has-text("${energyRule.attribute_then}")`);
+ await page.getByRole("spinbutton", {name: "Value"}).fill(energyRule.value.toString());
+
+ await shared.interceptResponse<number>("**/rules/realm", (rule) => {
+ if (rule) manager.rules.push(rule);
+ });
+
+ await page.getByRole("button", {name: "Save"}).click();
+ await expect(page.locator(`text=${energyRule.name}`)).toHaveCount(1);
});
/**
- * @when Selecting Flow rule
+ * @when Creating a Flow rule
* @and Naming the rule
* @and Dragging elements onto the canvas
* @and Assigning attributes and values
@@ -65,69 +129,73 @@ test("Create a When-Then rule for an asset with a trigger and action", async ({
* @and Saving the rule
* @then The Flow rule should appear in the rule list
*/
-test("Create a Flow rule for an asset with logic connections", async ({ page, shared, manager }) => {
- await page.locator("li", { hasText: "Flow" }).click();
- await page.fill("text=Rule name", "Solar panel");
-
- await page.locator(".node-item.input-node", { hasText: "Attribute value" }).hover();
- await shared.drag(450, 250);
- await page.hover("text=Number");
- await shared.drag(450, 350);
- await page.hover("text=Number");
- await shared.drag(450, 500);
- await page.hover("text=Number");
- await shared.drag(450, 600);
- await page.hover("text=>");
- await shared.drag(650, 300);
- await page.hover("text=Number switch");
- await shared.drag(800, 425);
- await page.locator(".node-item.output-node", { hasText: "Attribute value" }).hover();
- await shared.drag(1000, 425);
-
- await page.getByRole("button", { name: "Attribute" }).nth(0).click();
- await page.getByRole("alertdialog").getByText("Solar Panel").click();
- await page.getByRole("option", { name: "Power", exact: true }).click();
- await page.getByRole("button", { name: "Add" }).click();
-
- await page.getByRole("button", { name: "Attribute" }).nth(1).click();
- await page.getByRole("alertdialog").getByText("Solar Panel").click();
- await page.getByRole("option", { name: "Power forecast", exact: true }).click();
- await page.getByRole("button", { name: "Add" }).click();
-
- await page.fill('[placeholder="value"] >> nth=0', "50");
- await page.fill('[placeholder="value"] >> nth=1', "60");
- await page.fill('[placeholder="value"] >> nth=2', "40");
-
- await page.dragAndDrop(".socket >> nth=0", ".socket-side.inputs flow-node-socket .socket >> nth=0");
- await page.dragAndDrop(
- "flow-node:nth-child(2) .socket-side flow-node-socket .socket",
- "flow-node-socket:nth-child(2) .socket"
- );
- await page.dragAndDrop(
- "div:nth-child(3) flow-node-socket .socket",
- " flow-node:nth-child(6) .socket-side.inputs flow-node-socket .socket >> nth=0"
- );
- await page.dragAndDrop(
- "flow-node:nth-child(3) .socket-side flow-node-socket .socket",
- "flow-node:nth-child(6) .socket-side.inputs flow-node-socket:nth-child(2)"
- );
- await page.dragAndDrop(
- "flow-node:nth-child(4) .socket-side flow-node-socket .socket",
- "flow-node-socket:nth-child(3) .socket"
- );
- await page.dragAndDrop(
- "flow-node:nth-child(6) .socket-side.outputs flow-node-socket .socket",
- "flow-node:nth-child(7) .socket-side flow-node-socket .socket"
- );
-
- await shared.interceptResponse<number>("**/rules/realm", (rule) => {
- if (rule) manager.rules.push(rule);
- });
-
- await page.getByRole("button", { name: "Save" }).click();
- await expect(page.locator("or-rule-tree").getByText("Solar panel")).toHaveCount(1);
+test("Create a Flow rule for an asset with logic connections", async ({page, shared, manager}) => {
+ await manager.setup("smartcity", {assets});
+ await manager.goToRealmStartPage("smartcity");
+ await manager.navigateToTab("Rules");
+ await page.click(".mdi-plus >> nth=0");
+ await page.locator("li", {hasText: "Flow"}).click();
+ await page.fill("text=Rule name", "Solar panel");
+
+ await page.locator(".node-item.input-node", {hasText: "Attribute value"}).hover();
+ await shared.drag(450, 250);
+ await page.hover("text=Number");
+ await shared.drag(450, 350);
+ await page.hover("text=Number");
+ await shared.drag(450, 500);
+ await page.hover("text=Number");
+ await shared.drag(450, 600);
+ await page.hover("text=>");
+ await shared.drag(650, 300);
+ await page.hover("text=Number switch");
+ await shared.drag(800, 425);
+ await page.locator(".node-item.output-node", {hasText: "Attribute value"}).hover();
+ await shared.drag(1000, 425);
+
+ await page.getByRole("button", {name: "Attribute"}).nth(0).click();
+ await page.getByRole("alertdialog").getByText("Solar Panel").click();
+ await page.getByRole("option", {name: "Power", exact: true}).click();
+ await page.getByRole("button", {name: "Add"}).click();
+
+ await page.getByRole("button", {name: "Attribute"}).nth(1).click();
+ await page.getByRole("alertdialog").getByText("Solar Panel").click();
+ await page.getByRole("option", {name: "Power forecast", exact: true}).click();
+ await page.getByRole("button", {name: "Add"}).click();
+
+ await page.fill('[placeholder="value"] >> nth=0', "50");
+ await page.fill('[placeholder="value"] >> nth=1', "60");
+ await page.fill('[placeholder="value"] >> nth=2', "40");
+
+ await page.dragAndDrop(".socket >> nth=0", ".socket-side.inputs flow-node-socket .socket >> nth=0");
+ await page.dragAndDrop(
+ "flow-node:nth-child(2) .socket-side flow-node-socket .socket",
+ "flow-node-socket:nth-child(2) .socket"
+ );
+ await page.dragAndDrop(
+ "div:nth-child(3) flow-node-socket .socket",
+ " flow-node:nth-child(6) .socket-side.inputs flow-node-socket .socket >> nth=0"
+ );
+ await page.dragAndDrop(
+ "flow-node:nth-child(3) .socket-side flow-node-socket .socket",
+ "flow-node:nth-child(6) .socket-side.inputs flow-node-socket:nth-child(2)"
+ );
+ await page.dragAndDrop(
+ "flow-node:nth-child(4) .socket-side flow-node-socket .socket",
+ "flow-node-socket:nth-child(3) .socket"
+ );
+ await page.dragAndDrop(
+ "flow-node:nth-child(6) .socket-side.outputs flow-node-socket .socket",
+ "flow-node:nth-child(7) .socket-side flow-node-socket .socket"
+ );
+
+ await shared.interceptResponse<number>("**/rules/realm", (rule) => {
+ if (rule) manager.rules.push(rule);
+ });
+
+ await page.getByRole("button", {name: "Save"}).click();
+ await expect(page.locator("or-rule-tree").getByText("Solar panel")).toHaveCount(1);
});
-test.afterEach(async ({ manager }) => {
- await manager.cleanUp();
+test.afterEach(async ({manager}) => {
+ await manager.cleanUp();
});
diff --git a/ui/component/or-mwc-components/src/or-mwc-input.ts b/ui/component/or-mwc-components/src/or-mwc-input.ts
index f68ab7a9f..cb37a38e8 100644
--- a/ui/component/or-mwc-components/src/or-mwc-input.ts
+++ b/ui/component/or-mwc-components/src/or-mwc-input.ts
@@ -891,7 +891,7 @@ export class OrMwcInput extends LitElement {
}
public focus() {
- if (this.type === InputType.RANGE && this._mdcComponent2) {
+ if (this.type === InputType.RANGE && this._mdcComponent2 && typeof (this._mdcComponent2 as any).focus === "function") {
(this._mdcComponent2 as any).focus();
} else if (this._mdcComponent && typeof (this._mdcComponent as any).focus === "function") {
(this._mdcComponent as any).focus();
@@ -1140,7 +1140,7 @@ export class OrMwcInput extends LitElement {
<span class="mdc-floating-label" style="color: rgba(0, 0, 0, 0.6); text-transform: capitalize; visibility: ${this.searchableValue ? 'hidden' : 'visible'}" id="my-label-id">
<or-translate .value="${this.searchLabel}"></or-translate>
</span>
- <input class="mdc-text-field__input" type="text"
+ <input id="searchable-input" class="mdc-text-field__input" type="text"
@keyup="${(e: KeyboardEvent) => this.searchableValue = (e.target as HTMLInputElement).value}"
/>
</label>
diff --git a/ui/component/or-rules/src/index.ts b/ui/component/or-rules/src/index.ts
index 64cda9eda..fbffa524c 100644
--- a/ui/component/or-rules/src/index.ts
+++ b/ui/component/or-rules/src/index.ts
@@ -538,26 +538,24 @@ export function getAssetInfos(config: RulesConfig | undefined, useActionConfig:
// Function for getting assets by type
// loadedAssets is an object given as parameter that will be updated if new assets are fetched.
-export async function getAssetsByType(type: string, realm?: string, loadedAssets?: Map<string, Asset[]>): Promise<{ assets?: Asset[], loadedAssets?: Map<string, Asset[]>}> {
- if(loadedAssets?.has(type)) {
+export async function getAssetsByType(type: string, customQuery?: AssetQuery, loadedAssets?: Map<string, Asset[]>): Promise<{ assets?: Asset[], loadedAssets?: Map<string, Asset[]>}> {
+ if (loadedAssets?.has(type)) {
return {
assets: loadedAssets?.get(type),
loadedAssets: loadedAssets
- }
+ };
} else {
- if(!loadedAssets) {
- loadedAssets = new Map<string, any[]>();
- }
+ loadedAssets ??= new Map<string, any[]>();
const assetQuery: AssetQuery = {
+ realm: {
+ name: manager.displayRealm
+ },
types: [type],
orderBy: {
property: AssetQueryOrderBy$Property.NAME
}
- }
- if(realm != undefined) {
- assetQuery.realm = { name: realm }
- }
- const response = await manager.rest.api.AssetResource.queryAssets(assetQuery);
+ };
+ const response = await manager.rest.api.AssetResource.queryAssets({...assetQuery, ...customQuery});
loadedAssets.set(type, response.data);
return {
assets: response.data,
diff --git a/ui/component/or-rules/src/json-viewer/or-rule-action-attribute.ts b/ui/component/or-rules/src/json-viewer/or-rule-action-attribute.ts
index 122c4f4b0..3d085b320 100644
--- a/ui/component/or-rules/src/json-viewer/or-rule-action-attribute.ts
+++ b/ui/component/or-rules/src/json-viewer/or-rule-action-attribute.ts
@@ -1,5 +1,5 @@
import {css, html, LitElement, PropertyValues, TemplateResult} from "lit";
-import {customElement, property} from "lit/decorators.js";
+import {customElement, property, state} from "lit/decorators.js";
import {getAssetIdsFromQuery, getAssetTypeFromQuery, RulesConfig} from "../index";
import {
Asset,
@@ -7,16 +7,16 @@ import {
RuleActionUpdateAttribute,
RuleActionWriteAttribute,
WellknownValueTypes,
- AssetModelUtil
+ AssetModelUtil, AssetQuery
} from "@openremote/model";
import {Util} from "@openremote/core";
import "@openremote/or-attribute-input";
import {InputType, OrInputChangedEvent} from "@openremote/or-mwc-components/or-mwc-input";
-import {i18next, translate} from "@openremote/or-translate"
+import {i18next, translate} from "@openremote/or-translate";
import {OrRulesJsonRuleChangedEvent} from "./or-rule-json-viewer";
import {OrAttributeInputChangedEvent} from "@openremote/or-attribute-input";
-import { ifDefined } from "lit/directives/if-defined.js";
-import { when } from "lit/directives/when.js";
+import {ifDefined} from "lit/directives/if-defined.js";
+import {when} from "lit/directives/when.js";
// language=CSS
const style = css`
@@ -58,22 +58,26 @@ export class OrRuleActionAttribute extends translate(i18next)(LitElement) {
public assetInfos?: AssetTypeInfo[];
@property({type: Object})
- public assetProvider!: (type: string) => Promise<Asset[] | undefined>
+ public assetProvider!: (type: string, query?: AssetQuery) => Promise<Asset[] | undefined>;
- @property({type: Array, attribute: false})
- protected _assets?: Asset[];
+ @state()
+ protected _cache?: {query: AssetQuery, assets: Asset[]};
+ @state()
+ protected _selected?: Asset;
- public shouldUpdate(_changedProperties: PropertyValues): boolean {
- if (_changedProperties.has("action")) {
- this._assets = undefined;
+ protected _loading = false;
+
+ public shouldUpdate(changedProps: PropertyValues): boolean {
+ if (changedProps.has("action")) {
+ this._cache = undefined;
}
- return super.shouldUpdate(_changedProperties);
+ return super.shouldUpdate(changedProps);
}
public refresh() {
// Clear assets
- this._assets = undefined;
+ this._cache = undefined;
}
protected _getAssetType() {
@@ -97,56 +101,63 @@ export class OrRuleActionAttribute extends translate(i18next)(LitElement) {
}
const query = this.action.target.assets ? this.action.target.assets : this.action.target.matchedAssets ? this.action.target.matchedAssets : undefined;
- const assetDescriptor = this.assetInfos ? this.assetInfos.find((assetTypeInfo) => assetTypeInfo.assetDescriptor!.name === assetType) : undefined;
+ const assetDescriptor = this.assetInfos ? this.assetInfos.find(assetTypeInfo => assetTypeInfo.assetDescriptor!.name === assetType) : undefined;
if (!assetDescriptor) {
return html``;
}
- if (!this._assets) {
+ if (!this._cache && !this._loading) {
this.loadAssets(assetType);
}
// TODO: Add multiselect support
const ids = getAssetIdsFromQuery(query);
const idValue = ids && ids.length > 0 ? ids[0] : "*";
- const idOptions: [string, string] [] = [
+ const idOptions: Map<string, string> = new Map([
["*", i18next.t("matched")]
- ];
+ ]);
+
+ // Set list of displayed assets, and filtering assets out if needed.
+ // If <= 25 assets: display everything
+ // If between 25 and 100 assets: display everything with search functionality
+ // If >= 100 assets: only display if in line with search input
+ const assets: Asset[] = this._cache ? this._cache.assets : [];
+ const searchable = assets.length > 25;
+ if (searchable && this._selected) {
+ idOptions.set(this._selected.id!, this._selected.name!);
+ }
+
let searchProvider: (search?: string) => Promise<[any, string][]>;
return html`
<!-- Show SELECT input with 'loading' until the assets are retrieved -->
- ${when((!this._assets), () => html`
- <or-mwc-input id="matchSelect" class="min-width" type="${InputType.SELECT}" .readonly="${true}" .label="${i18next.t('loading')}"></or-mwc-input>
+ ${when((!this._cache || this._loading), () => html`
+ <or-mwc-input id="matchSelect" class="min-width" type="${InputType.SELECT}" .readonly="${true}" .label="${i18next.t("loading")}"></or-mwc-input>
`, () => {
-
- // Set list of displayed assets, and filtering assets out if needed.
- // If <= 25 assets: display everything
- // If between 25 and 100 assets: display everything with search functionality
- // If > 100 assets: only display if in line with search input
- if (this._assets!.length <= 25) {
- idOptions.push(...this._assets!.map((asset) => [asset.id!, asset.name!] as [string, string]));
+ if (!searchable) {
+ assets.forEach(a => idOptions.set(a.id!, a.name!));
} else {
searchProvider = async (search?: string) => {
+ await this.loadAssets(assetType, search, idValue); // Wait for asset retrieval based on search
if (search) {
- return this._assets!.filter((asset) => asset.name?.toLowerCase().includes(search.toLowerCase())).map((asset) => [asset.id!, asset.name!] as [string, string]);
- } else if (this._assets!.length <= 100) {
- idOptions.push(...this._assets!.map((asset) => [asset.id!, asset.name!] as [string, string]));
- return idOptions;
+ return assets.filter(a => a.name?.toLowerCase().includes(search.toLowerCase())).map(a => [a.id!, a.name!] as [string, string]);
+ } else if (assets.length <= 100) {
+ assets.forEach(a => idOptions.set(a.id!, a.name!));
+ return [...idOptions];
} else {
- const asset = this._assets?.find((asset) => asset.id == idValue);
- if (asset && idOptions.find(([id, _value]) => id == asset.id) == undefined) {
- idOptions.push([asset.id!, asset.name!]); // add selected asset if there is one.
+ const selected = assets.find(a => a.id === idValue);
+ if (selected && !Array.from(idOptions.keys()).includes(selected.id!)) {
+ idOptions.set(selected.id!, selected.name!); // add selected asset if there is one.
}
- return idOptions;
+ return [...idOptions];
}
- }
+ };
}
// Get selected asset and its descriptors
- const asset = idValue && idValue !== "*" ? this._assets!.find(a => a.id === idValue) : undefined;
+ const asset = idValue && idValue !== "*" ? this._cache!.assets.find(a => a.id === idValue) : undefined;
const descriptors = AssetModelUtil.getAttributeAndValueDescriptors(assetType, this.action.attributeName, asset && asset.attributes && this.action.attributeName ? asset.attributes[this.action.attributeName] : undefined);
// Only RW attributes can be used in actions
@@ -180,8 +191,8 @@ export class OrRuleActionAttribute extends translate(i18next)(LitElement) {
return html`
<or-mwc-input id="matchSelect" class="min-width" .label="${i18next.t("asset")}" .type="${InputType.SELECT}"
- .options="${idOptions}" .searchProvider="${searchProvider}" .value="${idValue}" .readonly="${this.readonly || false}"
- @or-mwc-input-changed="${(e: OrInputChangedEvent) => { this._assetId = (e.detail.value); this.refresh(); }}"
+ .options="${[...idOptions]}" .searchProvider="${searchProvider}" .value="${idValue}" .readonly="${this.readonly || false}"
+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => { this._assetId = (e.detail.value); }}"
></or-mwc-input>
${attributes.length > 0 ? html`
<or-mwc-input id="attributeSelect" class="min-width" .label="${i18next.t("attribute")}" .type="${InputType.SELECT}" @or-mwc-input-changed="${(e: OrInputChangedEvent) => this.setActionAttributeName(e.detail.value)}" .readonly="${this.readonly || false}" ?searchable="${(attributes.length >= 25)}" .options="${attributes}" .value="${this.action.attributeName}"></or-mwc-input>
@@ -194,11 +205,10 @@ export class OrRuleActionAttribute extends translate(i18next)(LitElement) {
`;
}
- protected set _assetId(assetId: string) {
+ protected set _assetId(assetId: string | undefined) {
const assetType = this._getAssetType();
-
- if (assetId === "*") {
+ if (!assetId || assetId === "*") {
this.action.target!.assets = undefined;
this.action.target = {
matchedAssets: {
@@ -206,8 +216,9 @@ export class OrRuleActionAttribute extends translate(i18next)(LitElement) {
assetType || ""
]
}
- }
+ };
} else {
+ this._selected = this._cache?.assets?.find(a => a.id === assetId);
this.action.target!.matchedAssets = undefined;
this.action.target = {
assets: {
@@ -218,7 +229,7 @@ export class OrRuleActionAttribute extends translate(i18next)(LitElement) {
assetType || ""
]
}
- }
+ };
}
this.dispatchEvent(new OrRulesJsonRuleChangedEvent());
@@ -238,9 +249,48 @@ export class OrRuleActionAttribute extends translate(i18next)(LitElement) {
this.requestUpdate();
}
- protected loadAssets(type: string) {
- this.assetProvider(type).then(assets => {
- this._assets = assets;
- })
+ /**
+ * Fetches assets using the {@link assetProvider} from the parent component.
+ * This is often linked to the OpenRemote HTTP API to request assets from using an {@link AssetQuery} object.
+ * @param type - The asset type name to filter by
+ * @param search - The asset name to filter by (acts as a search)
+ * @param idValue - Selected asset ID to query along
+ * @protected
+ */
+ protected async loadAssets(type: string, search?: string, idValue?: string): Promise<Asset[] | undefined> {
+ const promises: Promise<Asset[] | undefined>[] = [];
+
+ const query: AssetQuery = { limit: 100 };
+ if (search) {
+ query.names ??= [];
+ query.names.push({ predicateType: "string", value: search });
+ }
+ // If the cache contains assets from the same query, don't send HTTP request again
+ const isQueryCached = this._cache?.query && Util.objectsEqual(this._cache.query, query, true);
+ if (!this._loading && !isQueryCached) {
+ this._loading = true;
+
+ // Use assetProvider from the parent component to retrieve assets using HTTP
+ promises.push(this.assetProvider(type, {...query}));
+
+ // When idValue is present, it should also be fetched alongside the other assets
+ if (idValue && idValue !== "*") {
+ promises.push(this.assetProvider(type, { ids: [idValue] }));
+ }
+
+ // Start retrieving assets through the assetProvider
+ const responses = await Promise.all(promises);
+ this._loading = false;
+
+ // Only update the state when we retrieve new assets
+ const assets = responses.filter(value => !!value).flat();
+ const cachedIds = this._cache?.assets.map(asset => asset.id) ?? [];
+ this._cache = {
+ query: query,
+ assets: [...(this._cache?.assets ?? []), ...(assets?.filter(a => !cachedIds.includes(a.id)) ?? [])]
+ };
+ return assets;
+ }
+ return this._cache?.assets;
}
}
diff --git a/ui/component/or-rules/src/json-viewer/or-rule-asset-query.ts b/ui/component/or-rules/src/json-viewer/or-rule-asset-query.ts
index bed2840b2..f0dbd32b6 100644
--- a/ui/component/or-rules/src/json-viewer/or-rule-asset-query.ts
+++ b/ui/component/or-rules/src/json-viewer/or-rule-asset-query.ts
@@ -16,20 +16,20 @@ import {
ValuePredicateUnion,
WellknownMetaItems,
WellknownValueTypes,
- AssetModelUtil
+ AssetModelUtil, AssetQuery
} from "@openremote/model";
import {AssetQueryOperator, getAssetIdsFromQuery, getAssetTypeFromQuery, RulesConfig} from "../index";
import "@openremote/or-mwc-components/or-mwc-input";
import {InputType, OrInputChangedEvent} from "@openremote/or-mwc-components/or-mwc-input";
import "@openremote/or-attribute-input";
import {Util} from "@openremote/core";
-import {i18next, translate} from "@openremote/or-translate"
+import {i18next, translate} from "@openremote/or-translate";
import {buttonStyle} from "../style";
import {OrRulesJsonRuleChangedEvent} from "./or-rule-json-viewer";
import {OrAttributeInputChangedEvent} from "@openremote/or-attribute-input";
import "./modals/or-rule-radial-modal";
import { ifDefined } from "lit/directives/if-defined.js";
-import {when} from 'lit/directives/when.js';
+import {when} from "lit/directives/when.js";
import moment from "moment";
// language=CSS
@@ -122,10 +122,15 @@ export class OrRuleAssetQuery extends translate(i18next)(LitElement) {
public assetInfos?: AssetTypeInfo[];
@property({type: Object})
- public assetProvider!: (type: string) => Promise<Asset[] | undefined>
+ public assetProvider!: (type: string, query?: AssetQuery) => Promise<Asset[] | undefined>;
@state()
- protected _assets?: Asset[];
+ protected _cache?: {query: AssetQuery, assets: Asset[]};
+
+ @state()
+ protected _selected?: Asset;
+
+ protected _loading = false;
// Value predicates for specific value descriptors
protected _queryOperatorsMap: {[type: string]: AssetQueryOperator[]} = {};
@@ -201,7 +206,7 @@ export class OrRuleAssetQuery extends translate(i18next)(LitElement) {
public refresh() {
// Clear assets
- this._assets = undefined;
+ this._cache = undefined;
}
protected attributePredicateEditorTemplate(assetTypeInfo: AssetTypeInfo, asset: Asset | undefined, attributePredicate: AttributePredicate) {
@@ -209,14 +214,14 @@ export class OrRuleAssetQuery extends translate(i18next)(LitElement) {
const assetDescriptor = assetTypeInfo.assetDescriptor!;
const operator = this.getOperator(attributePredicate);
const attributeName = this.getAttributeName(attributePredicate);
- let attribute = asset && asset.attributes && attributeName ? asset.attributes[attributeName] : undefined;
+ const attribute = asset && asset.attributes && attributeName ? asset.attributes[attributeName] : undefined;
let attributes: [string, string][] = [];
const descriptors = AssetModelUtil.getAttributeAndValueDescriptors(asset ? asset.type : assetDescriptor.name, attribute || attributeName, attribute);
if (asset && asset.attributes) {
attributes = Object.values(asset.attributes)
- .filter((attribute) => attribute.meta && (attribute.meta.hasOwnProperty(WellknownMetaItems.RULESTATE) ? attribute.meta[WellknownMetaItems.RULESTATE] : attribute.meta.hasOwnProperty(WellknownMetaItems.AGENTLINK)))
- .map((attr) => {
+ .filter(attr => attr.meta && (attr.meta.hasOwnProperty(WellknownMetaItems.RULESTATE) ? attr.meta[WellknownMetaItems.RULESTATE] : attr.meta.hasOwnProperty(WellknownMetaItems.AGENTLINK)))
+ .map(attr => {
const descriptors = AssetModelUtil.getAttributeAndValueDescriptors(asset.type, attr.name, attr);
const label = Util.getAttributeLabel(attr, descriptors[0], asset.type, false);
return [attr.name!, label];
@@ -224,14 +229,14 @@ export class OrRuleAssetQuery extends translate(i18next)(LitElement) {
} else {
attributes = !assetTypeInfo || !assetTypeInfo.attributeDescriptors ? [] :
assetTypeInfo.attributeDescriptors
- .map((ad) => {
+ .map(ad => {
const descriptors = AssetModelUtil.getAttributeAndValueDescriptors(assetDescriptor.name, ad);
const label = Util.getAttributeLabel(undefined, descriptors ? descriptors[0] : undefined, assetDescriptor.name, false);
return [ad.name!, label];
});
}
- attributes.sort(Util.sortByString((attr) => attr[1]));
+ attributes.sort(Util.sortByString(attr => attr[1]));
const operators = attributeName ? this.getOperators(assetDescriptor, descriptors ? descriptors[0] : undefined, descriptors ? descriptors[1] : undefined, attribute, attributeName) : [];
@@ -348,13 +353,11 @@ export class OrRuleAssetQuery extends translate(i18next)(LitElement) {
return style;
}
- public shouldUpdate(_changedProperties: PropertyValues): boolean {
-
- if (_changedProperties.has("condition")) {
- this._assets = undefined;
+ public shouldUpdate(changedProps: PropertyValues): boolean {
+ if (changedProps.has("condition")) {
+ this._cache = undefined;
}
-
- return super.shouldUpdate(_changedProperties);
+ return super.shouldUpdate(changedProps);
}
protected get query() {
@@ -390,16 +393,16 @@ export class OrRuleAssetQuery extends translate(i18next)(LitElement) {
const assetType = getAssetTypeFromQuery(this.query);
if (!assetType) {
- return html`<span class="invalidLabel">${i18next.t('errorOccurred')}</span>`;
+ return html`<span class="invalidLabel">${i18next.t("errorOccurred")}</span>`;
}
- const assetTypeInfo = this.assetInfos ? this.assetInfos.find((assetTypeInfo) => assetTypeInfo.assetDescriptor!.name === assetType) : undefined;
+ const assetTypeInfo = this.assetInfos ? this.assetInfos.find(assetTypeInfo => assetTypeInfo.assetDescriptor!.name === assetType) : undefined;
if (!assetTypeInfo) {
- return html`<span class="invalidLabel">${i18next.t('errorOccurred')}</span>`;
+ return html`<span class="invalidLabel">${i18next.t("errorOccurred")}</span>`;
}
- if (!this._assets) {
+ if (!this._cache && !this._loading) {
this.loadAssets(assetType);
}
@@ -416,40 +419,47 @@ export class OrRuleAssetQuery extends translate(i18next)(LitElement) {
// TODO: Add multiselect support
const ids = getAssetIdsFromQuery(this.query);
const idValue = ids && ids.length > 0 ? ids[0] : "*";
- const idOptions: [string, string] [] = [
+ const idOptions: Map<string, string> = new Map([
["*", i18next.t("anyOfThisType")]
- ];
+ ]);
+
+ // Set list of displayed assets, and filtering assets out if needed.
+ // If <= 25 assets: display everything
+ // If between 25 and 100 assets: display everything with search functionality
+ // If >= 100 assets: only display if in line with search input
+ const assets: Asset[] = this._cache ? this._cache.assets : [];
+ const searchable = assets.length > 25;
+ if (searchable && this._selected) {
+ idOptions.set(this._selected.id!, this._selected.name!);
+ }
+
let searchProvider: (search?: string) => Promise<[any, string][]>;
return html`
<div class="attribute-group">
<!-- Show SELECT input with 'loading' until the assets are retrieved -->
- ${when((!this._assets), () => html`
- <or-mwc-input id="idSelect" class="min-width" type="${InputType.SELECT}" .readonly="${true}" .label="${i18next.t('loading')}"></or-mwc-input>
+ ${when((!this._cache || this._loading), () => html`
+ <or-mwc-input id="idSelect" class="min-width" type="${InputType.SELECT}" .readonly="${true}" .label="${i18next.t("loading")}"></or-mwc-input>
`, () => {
-
- // Set list of displayed assets, and filtering assets out if needed.
- // If <= 25 assets: display everything
- // If between 25 and 100 assets: display everything with search functionality
- // If > 100 assets: only display if in line with search input
- if(this._assets!.length <= 25) {
- idOptions.push(...this._assets!.map((asset) => [asset.id!, asset.name!] as [string, string]));
+ if (!searchable) {
+ assets.forEach(a => idOptions.set(a.id!, a.name!));
} else {
searchProvider = async (search?: string) => {
- if(search) {
- return this._assets!.filter((asset) => asset.name?.toLowerCase().includes(search.toLowerCase())).map((asset) => [asset.id!, asset.name!] as [string, string]);
- } else if (this._assets!.length <= 100) {
- idOptions.push(...this._assets!.map((asset) => [asset.id!, asset.name!] as [string, string]));
- return idOptions;
+ await this.loadAssets(assetType, search, idValue); // Wait for asset retrieval based on search
+ if (search) {
+ return assets.filter(a => a.name?.toLowerCase().includes(search.toLowerCase())).map(a => [a.id!, a.name!] as [string, string]);
+ } else if (assets.length <= 100) {
+ assets.forEach(a => idOptions.set(a.id!, a.name!));
+ return [...idOptions];
} else {
- const asset = this._assets?.find((asset) => asset.id == idValue);
- if(asset && idOptions.find(([id, _value]) => id == asset.id) == undefined) {
- idOptions.push([asset.id!, asset.name!]); // add selected asset if there is one.
+ const asset = assets.find(a => a.id === idValue);
+ if (asset && !Array.from(idOptions.keys()).includes(asset.id!)) {
+ idOptions.set(asset.id!, asset.name!); // add selected asset if there is one.
}
- return idOptions;
+ return [...idOptions];
}
- }
+ };
}
const showAddAttribute = !this.readonly && (!this.config || !this.config.controls || this.config.controls.hideWhenAddAttribute !== true);
@@ -467,8 +477,8 @@ export class OrRuleAssetQuery extends translate(i18next)(LitElement) {
return html`
<or-mwc-input id="idSelect" class="min-width filledSelect" type="${InputType.SELECT}" .readonly="${this.readonly || false}" .label="${i18next.t("asset")}"
- .options="${idOptions}" .value="${idValue}" .searchProvider="${searchProvider}"
- @or-mwc-input-changed="${(e: OrInputChangedEvent) => { this._assetId = (e.detail.value); this.refresh(); }}"
+ .options="${[...idOptions]}" .value="${idValue}" .searchProvider="${searchProvider}"
+ @or-mwc-input-changed="${(e: OrInputChangedEvent) => { this._assetId = (e.detail.value); }}"
></or-mwc-input>
<div class="attributes">
${this.query.attributes && this.query.attributes.items ? this.query.attributes.items.map((attributePredicate, index) => {
@@ -476,7 +486,7 @@ export class OrRuleAssetQuery extends translate(i18next)(LitElement) {
${index > 0 ? html`<or-icon class="small" icon="ampersand"></or-icon>` : ``}
<div class="attribute">
<div>
- ${this.attributePredicateEditorTemplate(assetTypeInfo, idValue !== "*" ? this._assets!.find((asset) => asset.id === idValue) : undefined, attributePredicate)}
+ ${this.attributePredicateEditorTemplate(assetTypeInfo, idValue !== "*" ? this._cache!.assets.find(asset => asset.id === idValue) : undefined, attributePredicate)}
${this.attributeDurationTemplate(this.duration, index, onDurationAdd, onDurationChange)}
</div>
${showRemoveAttribute ? html`
@@ -486,7 +496,7 @@ export class OrRuleAssetQuery extends translate(i18next)(LitElement) {
}) : ``}
${showAddAttribute ? html`
<or-mwc-input class="plus-button" type="${InputType.BUTTON}" icon="plus"
- label="rulesEditorAddAttribute" @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.addAttributePredicate(this.query!.attributes!)}"></or-mwc-input>
+ label="rulesEditorAddAttribute" @or-mwc-input-changed="${(_ev: OrInputChangedEvent) => this.addAttributePredicate(this.query!.attributes!)}"></or-mwc-input>
`: ``}
</div>
`;
@@ -496,7 +506,12 @@ export class OrRuleAssetQuery extends translate(i18next)(LitElement) {
}
protected set _assetId(assetId: string | undefined) {
- !assetId || assetId === "*" ? this.query.ids = undefined : this.query.ids! = [assetId];
+ if (!assetId || assetId === "*") {
+ this.query.ids = undefined;
+ } else {
+ this._selected = this._cache?.assets?.find(a => a.id === assetId);
+ this.query.ids = [assetId];
+ }
this.dispatchEvent(new OrRulesJsonRuleChangedEvent());
this.requestUpdate();
}
@@ -520,7 +535,7 @@ export class OrRuleAssetQuery extends translate(i18next)(LitElement) {
this.requestUpdate();
}
- protected getOperatorMapValue(operatorMap: {[type: string]: AssetQueryOperator[]}, assetType?: string, attributeName?: string, attributeDescriptor?: AttributeDescriptor, valueDescriptor?: ValueDescriptor) {
+ protected getOperatorMapValue(operatorMap: {[type: string]: AssetQueryOperator[]}, assetType?: string, attributeName?: string, _attributeDescriptor?: AttributeDescriptor, valueDescriptor?: ValueDescriptor) {
let assetAttributeMatch: AssetQueryOperator[] | undefined;
let attributeDescriptorMatch: AssetQueryOperator[] | undefined;
@@ -544,7 +559,7 @@ export class OrRuleAssetQuery extends translate(i18next)(LitElement) {
}
}
- protected getOperators(assetDescriptor: AssetDescriptor, attributeDescriptor: AttributeDescriptor | undefined, valueDescriptor: ValueDescriptor | undefined, attribute: Attribute<any> | undefined, attributeName: string): [string, string][] {
+ protected getOperators(_assetDescriptor: AssetDescriptor, attributeDescriptor: AttributeDescriptor | undefined, valueDescriptor: ValueDescriptor | undefined, _attribute: Attribute<any> | undefined, attributeName: string): [string, string][] {
let operators: AssetQueryOperator[] | undefined;
@@ -556,7 +571,7 @@ export class OrRuleAssetQuery extends translate(i18next)(LitElement) {
operators = this.getOperatorMapValue(this._queryOperatorsMap, getAssetTypeFromQuery(this.query), attributeName, attributeDescriptor, valueDescriptor);
}
- return operators ? operators.map((v) => [v, i18next.t(v)]) : [];
+ return operators ? operators.map(v => [v, i18next.t(v)]) : [];
}
protected getOperator(attributePredicate: AttributePredicate): string | undefined {
@@ -702,7 +717,7 @@ export class OrRuleAssetQuery extends translate(i18next)(LitElement) {
index: value === AssetQueryOperator.INDEX_CONTAINS || value === AssetQueryOperator.NOT_INDEX_CONTAINS ? 0 : undefined,
lengthEquals: value === AssetQueryOperator.LENGTH_EQUALS || value === AssetQueryOperator.NOT_LENGTH_EQUALS ? 0 : undefined,
lengthGreaterThan: value === AssetQueryOperator.LENGTH_GREATER_THAN ? 0 : undefined,
- lengthLessThan: value === AssetQueryOperator.LENGTH_GREATER_THAN ? 0 : undefined,
+ lengthLessThan: value === AssetQueryOperator.LENGTH_GREATER_THAN ? 0 : undefined
};
}
break;
@@ -893,9 +908,7 @@ export class OrRuleAssetQuery extends translate(i18next)(LitElement) {
}
protected addAttributePredicate(group: LogicGroup<AttributePredicate>) {
- if (!group.items) {
- group.items = [];
- }
+ group.items ??= [];
group.items.push({});
this.dispatchEvent(new OrRulesJsonRuleChangedEvent());
this.requestUpdate();
@@ -911,9 +924,48 @@ export class OrRuleAssetQuery extends translate(i18next)(LitElement) {
this.requestUpdate();
}
- protected loadAssets(type: string) {
- this.assetProvider(type).then(assets => {
- this._assets = assets;
- })
+ /**
+ * Fetches assets using the {@link assetProvider} from the parent component.
+ * This is often linked to the OpenRemote HTTP API to request assets from using an {@link AssetQuery} object.
+ * @param type - The asset type name to filter by
+ * @param search - The asset name to filter by (acts as a search)
+ * @param idValue - Selected asset ID to query along
+ * @protected
+ */
+ protected async loadAssets(type: string, search?: string, idValue?: string): Promise<Asset[] | undefined> {
+ const promises: Promise<Asset[] | undefined>[] = [];
+
+ const query: AssetQuery = { limit: 100 };
+ if (search) {
+ query.names ??= [];
+ query.names.push({ predicateType: "string", value: search });
+ }
+ // If the cache contains assets from the same query, don't send HTTP request again
+ const isQueryCached = this._cache?.query && Util.objectsEqual(this._cache.query, query, true);
+ if (!this._loading && !isQueryCached) {
+ this._loading = true;
+
+ // Use assetProvider from the parent component to retrieve assets using HTTP
+ promises.push(this.assetProvider(type, {...query}));
+
+ // When idValue is present, it should also be fetched alongside the other assets
+ if (idValue && idValue !== "*") {
+ promises.push(this.assetProvider(type, { ids: [idValue] }));
+ }
+
+ // Start retrieving assets through the assetProvider
+ const responses = await Promise.all(promises);
+ this._loading = false;
+
+ // Only update the state when we retrieve new assets
+ const assets = responses.filter(value => !!value).flat();
+ const cachedIds = this._cache?.assets.map(asset => asset.id) ?? [];
+ this._cache = {
+ query: query,
+ assets: [...(this._cache?.assets ?? []), ...(assets?.filter(a => !cachedIds.includes(a.id)) ?? [])]
+ };
+ return assets;
+ }
+ return this._cache?.assets;
}
}
diff --git a/ui/component/or-rules/src/json-viewer/or-rule-condition.ts b/ui/component/or-rules/src/json-viewer/or-rule-condition.ts
index e8e28e2e9..860e8ef56 100644
--- a/ui/component/or-rules/src/json-viewer/or-rule-condition.ts
+++ b/ui/component/or-rules/src/json-viewer/or-rule-condition.ts
@@ -1,6 +1,6 @@
import {css, html, LitElement, TemplateResult} from "lit";
import {customElement, property, query} from "lit/decorators.js";
-import {AssetTypeInfo, RuleCondition, WellknownAssets, AssetModelUtil} from "@openremote/model";
+import {AssetTypeInfo, RuleCondition, WellknownAssets, AssetModelUtil, AssetQuery} from "@openremote/model";
import {ConditionType, getAssetTypeFromQuery, RulesConfig} from "../index";
import "./or-rule-asset-query";
import "./or-rule-trigger-query";
@@ -143,7 +143,7 @@ class OrRuleCondition extends translate(i18next)(LitElement) {
public assetInfos?: AssetTypeInfo[];
@property({type: Object})
- public assetProvider?: (type: string) => Promise<any[] | undefined>
+ public assetProvider?: (type: string, query?: AssetQuery) => Promise<any[] | undefined>
@query("#asset-query")
protected _assetQuery?: OrRuleAssetQuery;
diff --git a/ui/component/or-rules/src/json-viewer/or-rule-json-viewer.ts b/ui/component/or-rules/src/json-viewer/or-rule-json-viewer.ts
index 467286e23..3d16956a5 100644
--- a/ui/component/or-rules/src/json-viewer/or-rule-json-viewer.ts
+++ b/ui/component/or-rules/src/json-viewer/or-rule-json-viewer.ts
@@ -119,9 +119,6 @@ export class OrRuleJsonViewer extends translate(i18next)(LitElement) implements
@property({attribute: false})
protected _ruleset!: RulesetUnion;
- @state() // to be exact: Map<AssetType name, Asset[]>
- protected _loadedAssets: Map<string, Asset[]> = new Map<string, Asset[]>();
-
protected _rule!: JsonRule;
protected _unsupported = false;
protected _activeAssetPromises: Map<string, Promise<any>> = new Map<string, Promise<any>>();
@@ -207,13 +204,13 @@ export class OrRuleJsonViewer extends translate(i18next)(LitElement) implements
return html`
<div class="section-container">
<or-rule-when .rule="${this._rule}" .config="${this.config}" .assetInfos="${this._whenAssetInfos}" ?readonly="${this.readonly}"
- .assetProvider="${async (type: string) => this.loadAssets(type)}"
+ .assetProvider="${(type: string, query: AssetQuery) => this.loadAssets(type, query)}"
></or-rule-when>
</div>
<div class="section-container">
<or-rule-then-otherwise .rule="${this._rule}" .config="${this.config}" .targetTypeMap="${targetTypeMap}" .assetInfos="${this._actionAssetInfos}" ?readonly="${this.readonly}"
- .assetProvider="${async (type: string) => this.loadAssets(type)}"
+ .assetProvider="${(type: string, query: AssetQuery) => this.loadAssets(type, query)}"
></or-rule-then-otherwise>
</div>
`;
@@ -221,13 +218,18 @@ export class OrRuleJsonViewer extends translate(i18next)(LitElement) implements
// loadAssets function that also tracks what promises/fetches are active.
// If so, await for those to finish to prevent multiple API requests.
- // Also using caching with the _loadedAssets object.
- protected async loadAssets(type: string): Promise<Asset[] | undefined> {
- if(this._activeAssetPromises.has(type)) {
+ protected async loadAssets(type: string, query?: AssetQuery): Promise<Asset[] | undefined> {
+ if (this._activeAssetPromises.has(type)) {
const data = await (this._activeAssetPromises.get(type)); // await for the already existing fetch
return data.assets;
} else {
- const promise = getAssetsByType(type, (this._ruleset.type == "realm" ? this._ruleset.realm : undefined), this._loadedAssets);
+ query ??= {};
+ query.types ??= [];
+ query.types.push(type);
+ query.realm ??= {
+ name: this._ruleset.type == "realm" ? this._ruleset.realm : undefined
+ };
+ const promise = getAssetsByType(type, query);
this._activeAssetPromises.set(type, promise);
const data = await promise;
this._activeAssetPromises.delete(type);
diff --git a/ui/component/or-rules/src/json-viewer/or-rule-then-otherwise.ts b/ui/component/or-rules/src/json-viewer/or-rule-then-otherwise.ts
index 33f1af20e..44c92fefa 100644
--- a/ui/component/or-rules/src/json-viewer/or-rule-then-otherwise.ts
+++ b/ui/component/or-rules/src/json-viewer/or-rule-then-otherwise.ts
@@ -9,7 +9,7 @@ import {
AlarmSeverity,
AlarmStatus,
Asset,
- AssetModelUtil,
+ AssetModelUtil, AssetQuery,
AssetTypeInfo, EmailNotificationMessage,
HTTPMethod,
JsonRule, LocalizedNotificationMessage, PushNotificationMessage,
@@ -257,7 +257,7 @@ class OrRuleThenOtherwise extends translate(i18next)(LitElement) {
public assetInfos?: AssetTypeInfo[];
@property({type: Object})
- public assetProvider?: (type: string) => Promise<Asset[] | undefined>
+ public assetProvider?: (type: string, query?: AssetQuery) => Promise<Asset[] | undefined>
protected get thenAllowAdd() {
return !this.config || !this.config.controls || this.config.controls.hideThenAddAction !== true;
@@ -384,7 +384,8 @@ class OrRuleThenOtherwise extends translate(i18next)(LitElement) {
case ActionType.EMAIL:
case ActionType.EMAIL_LOCALIZED:
const id = type + "-notification";
- template = html`<or-rule-action-notification id="${id}" .rule="${this.rule}" .action="${action}" .actionType="${type}" .config="${this.config}" .assetInfos="${this.assetInfos}" .readonly="${this.readonly}"></or-rule-action-notification>`;
+ template = html`<or-rule-action-notification id="${id}" .rule="${this.rule}" .action="${action}" .actionType="${type}" .config="${this.config}"
+ .assetInfos="${this.assetInfos}" .readonly="${this.readonly}"></or-rule-action-notification>`;
break;
case ActionType.WEBHOOK:
template = html`<or-rule-action-webhook .rule="${this.rule}" .action="${action}" .actionType="${ActionType.WEBHOOK}"></or-rule-action-webhook>`;
@@ -393,7 +394,8 @@ class OrRuleThenOtherwise extends translate(i18next)(LitElement) {
template = html`<or-rule-action-alarm .rule="${this.rule}" .action="${action}" .actionType="${ActionType.ALARM}"></or-rule-action-alarm>`;
break;
default:
- template = html`<or-rule-action-attribute .action="${action}" .targetTypeMap="${this.targetTypeMap}" .config="${this.config}" .assetInfos="${this.assetInfos}" .assetProvider="${this.assetProvider}" .readonly="${this.readonly}"></or-rule-action-attribute>`;
+ template = html`<or-rule-action-attribute .action="${action}" .targetTypeMap="${this.targetTypeMap}" .config="${this.config}" .assetProvider="${this.assetProvider}"
+ .assetInfos="${this.assetInfos}" .readonly="${this.readonly}"></or-rule-action-attribute>`;
break;
}
}
diff --git a/ui/component/or-rules/src/json-viewer/or-rule-when.ts b/ui/component/or-rules/src/json-viewer/or-rule-when.ts
index d0bf94ef8..25e9a833a 100644
--- a/ui/component/or-rules/src/json-viewer/or-rule-when.ts
+++ b/ui/component/or-rules/src/json-viewer/or-rule-when.ts
@@ -1,6 +1,6 @@
import {css, html, LitElement, PropertyValues, TemplateResult} from "lit";
import {customElement, property} from "lit/decorators.js";
-import {AssetDescriptor, JsonRule, LogicGroup, LogicGroupOperator, RuleCondition, WellknownAssets, AssetTypeInfo, Asset} from "@openremote/model";
+import {JsonRule, LogicGroup, LogicGroupOperator, RuleCondition, WellknownAssets, AssetTypeInfo, Asset, AssetQuery} from "@openremote/model";
import {OrRulesRuleUnsupportedEvent, RulesConfig} from "../index";
import {buttonStyle} from "../style";
import "./or-rule-condition";
@@ -115,7 +115,7 @@ class OrRuleWhen extends translate(i18next)(LitElement) {
public readonly?: boolean;
@property({type: Object})
- public assetProvider?: (type: string) => Promise<Asset[]>
+ public assetProvider?: (type: string, query?: AssetQuery) => Promise<Asset[]>
public config?: RulesConfig;