100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
UI updates: Rules performance improvements (#851)
Martin Peeters8cdfd5d8243a
diff --git a/manager/src/web/shared/locales/en/or.json b/manager/src/web/shared/locales/en/or.jsonindex f22a71f1f..5e0d797ff 100644--- a/manager/src/web/shared/locales/en/or.json+++ b/manager/src/web/shared/locales/en/or.json@@ -119,6 +119,7 @@"setParent": "Select parent asset","noAssetTypeSelected": "Please select an asset type on the left","loading": "Loading...",+ "noResults": "No results found.","noAssetsFound": "No assets found","filterInvite": "Filter with at least 3 characters","location": "Location",diff --git a/manager/src/web/shared/locales/nl/or.json b/manager/src/web/shared/locales/nl/or.jsonindex 38290db47..8c6d7e354 100644--- a/manager/src/web/shared/locales/nl/or.json+++ b/manager/src/web/shared/locales/nl/or.json@@ -119,6 +119,7 @@"setParent": "Kies parent asset","noAssetTypeSelected": "Kies een asset type uit de lijst aan de linkerkant","loading": "Aan het laden...",+ "noResults": "Geen resultaten gevonden.","noAssetsFound": "Geen assets gevonden","filterInvite": "Filter met minsters 3 karakters","location": "Locatie",diff --git a/ui/component/or-mwc-components/src/or-mwc-input.ts b/ui/component/or-mwc-components/src/or-mwc-input.tsindex 031d8a925..b75e8d5ea 100644--- a/ui/component/or-mwc-components/src/or-mwc-input.ts+++ b/ui/component/or-mwc-components/src/or-mwc-input.ts@@ -3,6 +3,8 @@ import {customElement, property, state} from "lit/decorators.js";import {Ref, ref, createRef} from "lit/directives/ref.js";import {classMap} from "lit/directives/class-map.js";import {ifDefined} from "lit/directives/if-defined.js";+import {when} from 'lit/directives/when.js';+import {until} from 'lit/directives/until.js';import {MDCTextField} from "@material/textfield";import {MDCComponent} from "@material/base";import {MDCRipple} from "@material/ripple";@@ -14,7 +16,7 @@ import {MDCList, MDCListActionEvent} from "@material/list";import {MDCFormField, MDCFormFieldInput} from "@material/form-field";import {MDCIconButtonToggle, MDCIconButtonToggleEventDetail} from "@material/icon-button";-import {DefaultColor4, DefaultColor8, Util} from "@openremote/core";+import {DefaultColor4, DefaultColor5, DefaultColor8, Util} from "@openremote/core";import "@openremote/or-icon";import {OrIcon} from "@openremote/or-icon";import {@@ -459,7 +461,7 @@ const style = css`}.mdc-list {- flex: 1 1 0;+ flex: 1;overflow: auto;}@@ -511,11 +513,14 @@ const style = css`#select-searchable {background-color: transparent;- border: 1px solid var(--or-app-color5);- margin: 16px 16px 8px;- width: calc(100% - 66px);- border-radius: 4px;+ border: 1px solid var(--or-app-color5, ${unsafeCSS(DefaultColor5)});+ margin: 8px 8px 0;+ width: calc(100% - 16px);+ border-radius: 4px;padding: 4px 16px;+ flex: 0 0 auto;+ align-items: center;+ height: auto;}.mdc-text-field__input::-webkit-calendar-picker-indicator {@@ -592,6 +597,13 @@ const style = css`.mdc-select__menu .mdc-list .mdc-list-item.mdc-list-item--selected or-icon {--or-icon-fill: var(--or-app-color4);}+ .mdc-menu__searchable {+ overflow: hidden;+ flex-direction: column;+ }+ .mdc-menu__searchable.mdc-menu-surface--is-open-below {+ display: flex;+ }`;@customElement("or-mwc-input")@@ -676,13 +688,8 @@ export class OrMwcInput extends LitElement {@property({type: Boolean})public autoSelect?: boolean;- /* SELECT SEARCH PROPERTIES BELOW */-- @property({type: String})- public searchableValue?: string;-- @property({type: Boolean})- public searchable?: boolean;+ @property({type: Object})+ public searchProvider?: (search?: string) => Promise<[any, string][]>/* STYLING PROPERTIES BELOW */@@ -776,6 +783,8 @@ export class OrMwcInput extends LitElement {@state()protected isUiValid = true;@state()+ public searchableValue?: string;+ @state()protected errorMessage?: string;disconnectedCallback(): void {@@ -885,7 +894,6 @@ export class OrMwcInput extends LitElement {}) : ``}</div>`;- break;case InputType.SWITCH:const classesSwitch = {"mdc-switch--disabled": this.disabled || this.readonly,@@ -948,9 +956,11 @@ export class OrMwcInput extends LitElement {"mdc-select--with-leading-icon": !!this.icon};- let opts = this.resolveOptions(this.options);- if(this.searchableValue && opts) {- opts = opts.filter(([optValue, optDisplay]) => optDisplay.toLowerCase().includes((this.searchableValue as string).toLowerCase()));+ let opts: [any, string][] | Promise<[any, string][]>;+ if(this.searchProvider != undefined) {+ opts = this.searchProvider(this.searchableValue);+ } else {+ opts = this.resolveOptions(this.options)!;}const itemClickHandler: (ev: MouseEvent, item: ListItem) => void = (ev, item) => {const value = item.value;@@ -979,6 +989,13 @@ export class OrMwcInput extends LitElement {}this._tempValue = inputValue;}++ // A narrowed down list with search, or a different asynchronous approach does not always trigger @MDCSelect:change,+ // so using itemClickHandler instead to let it trigger anyway.+ else if(this.searchProvider != undefined || !Array.isArray(opts)) {+ this.onValueChange(undefined, item.value);+ }+};const menuCloseHandler = () => {@@ -998,10 +1015,38 @@ export class OrMwcInput extends LitElement {this.onValueChange(undefined, val);};+ const listTemplate = (options: [any, string][]) => {+ if(this.searchProvider != undefined && (!options || options.length == 0)) {+ return html`<span class="mdc-text-field-helper-line" style="margin: 8px 8px 8px 0;">${i18next.t('noResults')}</span>`+ } else {+ return getListTemplate(+ this.multiple ? ListType.MULTI_TICK : ListType.SELECT,+ html`${options?.map(([optValue, optDisplay], index) => {+ return getItemTemplate(+ {+ text: optDisplay,+ value: optValue+ },+ index,+ Array.isArray(this.value) ? this.value as any[] : this.value ? [this.value as any] : [],+ this.multiple ? ListType.MULTI_TICK : ListType.SELECT,+ false,+ itemClickHandler+ );+ })}`,+ false,+ undefined+ );+ }+ }+return html`<div id="component"class="mdc-select ${classMap(classes)}"- @MDCSelect:change="${(e: MDCSelectEvent) => this.onValueChange(undefined, e.detail.index === -1 ? undefined : Array.isArray(opts![e.detail.index]) ? opts![e.detail.index][0] : opts![e.detail.index])}">+ @MDCSelect:change="${async (e: MDCSelectEvent) => {+ const options: [any, string][] = (Array.isArray(opts) ? opts : await opts);+ this.onValueChange(undefined, e.detail.index === -1 ? undefined : Array.isArray(options[e.detail.index]) ? options[e.detail.index][0] : options[e.detail.index]);+ }}"><div class="mdc-select__anchor" role="button"aria-haspopup="listbox"aria-expanded="false"@@ -1032,32 +1077,22 @@ export class OrMwcInput extends LitElement {</span>${!outlined ? html`<div class="mdc-line-ripple"></div>` : ``}</div>- <div id="mdc-select-menu" class="mdc-select__menu mdc-menu mdc-menu-surface mdc-menu-surface--fixed" @MDCMenuSurface:closed="${menuCloseHandler}">- ${this.searchable ? html`- <input class="mdc-text-field__input"- autofocus- id="select-searchable"- type="text"- @keyup="${(e:MDCSelectEvent) => this.searchableValue = (e.target as HTMLInputElement).value}"/>- ` : ``}- ${getListTemplate(- this.multiple ? ListType.MULTI_TICK : ListType.SELECT,- opts ? html`${opts.map(([optValue, optDisplay], index) => {- return getItemTemplate(- {- text: optDisplay,- value: optValue- },- index,- Array.isArray(this.value) ? this.value as any[] : this.value ? [this.value as any] : [],- this.multiple ? ListType.MULTI_TICK : ListType.SELECT,- false,- itemClickHandler- )- })}` : html``,- false,- undefined- )}+ <div id="mdc-select-menu" class="mdc-select__menu mdc-menu mdc-menu-surface mdc-menu-surface--fixed ${this.searchProvider != undefined ? 'mdc-menu__searchable' : undefined}" @MDCMenuSurface:closed="${menuCloseHandler}" style="width: inherit !important;">+ ${when(this.searchProvider != undefined, () => html`+ <label id="select-searchable" class="mdc-text-field mdc-text-field--filled">+ <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">${i18next.t('search')}</span>+ <input class="mdc-text-field__input" type="text"+ @keyup="${(e: KeyboardEvent) => this.searchableValue = (e.target as HTMLInputElement).value}"+ />+ </label>+ `)}+ ${when(Array.isArray(opts), () => {+ return listTemplate(opts as [any, string][]);+ }, () => {+ return until(new Promise(async (resolve) => {+ resolve(listTemplate(await opts));+ }), html`<span class="mdc-text-field-helper-line" style="margin: 8px 8px 8px 0;">${i18next.t('loading')}</span>`)+ })}</div>${hasHelper || showValidationMessage ? html`<p id="component-helper-text" class="mdc-select-helper-text ${classMap(helperClasses)}" aria-hidden="true">@@ -1462,7 +1497,12 @@ export class OrMwcInput extends LitElement {(this._mdcComponent as any).foundation.adapter.floatLabel(!!selectedText);// Set width of fixed select menu to match the component width- //this.shadowRoot!.getElementById("mdc-select-menu")!.style.width = component.getBoundingClientRect().width + "px";+ // Using an observer to prevent forced reflow / DOM measurements; prevents blocking the thread+ const observer = new IntersectionObserver((entries, observer) => {+ (entries[0].target as HTMLElement).style.width = entries[0].boundingClientRect.width + "px";+ observer.unobserve(entries[0].target);+ })+ observer.observe(this.shadowRoot!.getElementById("component")!);// This overrides the standard mdc menu body click capture handler as it doesn't work with webcomponents(mdcSelect as any).menu.menuSurface_.foundation.handleBodyClick = function (evt: MouseEvent) {@@ -1526,7 +1566,7 @@ export class OrMwcInput extends LitElement {// some components need to be kept in sync with the DOMif (this.type === InputType.SELECT && this._mdcComponent) {if (_changedProperties.has("options")) {- (this._mdcComponent as MDCSelect).layoutOptions();+ (this._mdcComponent as MDCSelect).layoutOptions(); // has big impact on performance when the MDCSelect list is large.}(this._mdcComponent as MDCSelect).disabled = !!(this.disabled || this.readonly);(this._mdcComponent as MDCSelect).useDefaultValidation = !this.multiple;@@ -1675,8 +1715,9 @@ export class OrMwcInput extends LitElement {this.dispatchEvent(new OrInputChangedEvent(this.value, previousValue, enterPressed));}- if(this.searchable) {- const searchableElement = this.shadowRoot?.getElementById('select-searchable');+ // Reset search if value has been selected+ if(this.searchProvider != undefined && this.type === InputType.SELECT) {+ const searchableElement = this.shadowRoot?.getElementById('select-searchable')?.children[1];if(searchableElement) {this.searchableValue = undefined;(searchableElement as HTMLInputElement).value = "";diff --git a/ui/component/or-rules/src/index.ts b/ui/component/or-rules/src/index.tsindex 94de9beae..302d9b327 100644--- a/ui/component/or-rules/src/index.ts+++ b/ui/component/or-rules/src/index.ts@@ -26,7 +26,10 @@ import {RuleCondition,RulesetLang,RulesetUnion,- WellknownAssets+ WellknownAssets,+ Asset,+ AssetQueryOrderBy$Property,+ AssetQueryMatch} from "@openremote/model";import "@openremote/or-translate";import "@openremote/or-mwc-components/or-mwc-drawer";@@ -492,6 +495,30 @@ 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, loadedAssets?: Map<string, Asset[]>): Promise<{ assets?: Asset[], loadedAssets?: Map<string, Asset[]>}> {+ if(loadedAssets?.has(type)) {+ return {+ assets: loadedAssets?.get(type),+ loadedAssets: loadedAssets+ }+ } else {+ const response = await manager.rest.api.AssetResource.queryAssets({+ types: [ type ],+ orderBy: {+ property: AssetQueryOrderBy$Property.NAME+ }+ });+ loadedAssets?.set(type, response.data);+ return {+ assets: response.data,+ loadedAssets: loadedAssets+ };+ }++}+export class OrRulesRuleChangedEvent extends CustomEvent<boolean> {public static readonly NAME = "or-rules-rule-changed";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.tsindex 23ec099cb..12f8f5ba2 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@@ -3,15 +3,13 @@ import {customElement, property} from "lit/decorators.js";import {getAssetIdsFromQuery, getAssetTypeFromQuery, RulesConfig} from "../index";import {Asset,- AssetQueryOrderBy$Property,AssetTypeInfo,RuleActionUpdateAttribute,RuleActionWriteAttribute,- WellknownMetaItems,WellknownValueTypes,AssetModelUtil} from "@openremote/model";-import manager, {Util} from "@openremote/core";+import {Util} from "@openremote/core";import "@openremote/or-attribute-input";import {InputType, OrInputChangedEvent} from "@openremote/or-mwc-components/or-mwc-input";import i18next from "i18next";@@ -19,6 +17,7 @@ import {OrRulesJsonRuleChangedEvent} from "./or-rule-json-viewer";import {translate} from "@openremote/or-translate";import {OrAttributeInputChangedEvent} from "@openremote/or-attribute-input";import { ifDefined } from "lit/directives/if-defined.js";+import { when } from "lit/directives/when.js";// language=CSSconst style = css`@@ -59,9 +58,13 @@ export class OrRuleActionAttribute extends translate(i18next)(LitElement) {@property({type: Object})public assetInfos?: AssetTypeInfo[];+ @property({type: Object})+ public assetProvider!: (type: string) => Promise<Asset[] | undefined>+@property({type: Array, attribute: false})protected _assets?: Asset[];+public shouldUpdate(_changedProperties: PropertyValues): boolean {if (_changedProperties.has("action")) {this._assets = undefined;@@ -69,6 +72,11 @@ export class OrRuleActionAttribute extends translate(i18next)(LitElement) {return super.shouldUpdate(_changedProperties);}+ public refresh() {+ // Clear assets+ this._assets = undefined;+ }+protected _getAssetType() {if (!this.action.target) {return;@@ -98,7 +106,6 @@ export class OrRuleActionAttribute extends translate(i18next)(LitElement) {if (!this._assets) {this.loadAssets(assetType);- return html``;}// TODO: Add multiselect support@@ -107,52 +114,84 @@ export class OrRuleActionAttribute extends translate(i18next)(LitElement) {const idOptions: [string, string] [] = [["*", i18next.t("matched")]];-- idOptions.push(...this._assets!.map((asset) => [asset.id!, asset.name!] as [string, string]));-- const asset = idValue && idValue !== "*" ? this._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- let attributes: [string, string][] = [];-- if (asset && asset.attributes) {- attributes = Object.values(asset.attributes)- .map((attr) => {- const label = Util.getAttributeLabel(attr, descriptors[0], assetType, false);- return [attr.name!, label];- });- } else if (assetDescriptor) {- const assetTypeInfo = AssetModelUtil.getAssetTypeInfo(assetDescriptor);-- attributes =- !assetTypeInfo || !assetTypeInfo.attributeDescriptors- ? []- : assetTypeInfo.attributeDescriptors.map((ad) => {- const label = Util.getAttributeLabel(ad, descriptors[0], assetType, false);- return [ad.name!, label];- });- }-- attributes.sort(Util.sortByString((attr) => attr[1]));-- let attributeInput: TemplateResult | undefined;-- if (this.action.attributeName) {- const label = descriptors[1] && (descriptors[1].name === WellknownValueTypes.BOOLEAN) ? "" : i18next.t("value");- let inputType;- if(descriptors[0]?.format?.asSlider) inputType = InputType.NUMBER;- attributeInput = html`<or-attribute-input ?compact=${descriptors[1] && (descriptors[1].name === WellknownValueTypes.GEOJSONPOINT)} .inputType="${ifDefined(inputType)}" @or-attribute-input-changed="${(ev: OrAttributeInputChangedEvent) => this.setActionAttributeValue(ev.detail.value)}" .customProvider="${this.config?.inputProvider}" .label="${label}" .assetType="${assetType}" .attributeDescriptor="${descriptors[0]}" .attributeValueDescriptor="${descriptors[1]}" .value="${this.action.value}" .readonly="${this.readonly || false}"></or-attribute-input>`;- }+ let searchProvider: (search?: string) => Promise<[any, string][]>;return html`- <or-mwc-input id="matchSelect" class="min-width" .label="${i18next.t("asset")}" .type="${InputType.SELECT}" @or-mwc-input-changed="${(e: OrInputChangedEvent) => this._assetId = (e.detail.value)}" .readonly="${this.readonly || false}" .options="${idOptions}" .value="${idValue}"></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}" .options="${attributes}" .value="${this.action.attributeName}"></or-mwc-input>- ${attributeInput}- ` : html`- <or-translate value="No attributes with write permission"></or-translate>- `}++ <!-- 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>+ `, () => {++ // 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]));+ } 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;+ } 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.+ }+ return idOptions;+ }+ }+ }++ // Get selected asset and its descriptors+ const asset = idValue && idValue !== "*" ? this._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+ let attributes: [string, string][] = [];+ if (asset && asset.attributes) {+ attributes = Object.values(asset.attributes)+ .map((attr) => {+ const label = Util.getAttributeLabel(attr, descriptors[0], assetType, false);+ return [attr.name!, label];+ });+ } else if (assetDescriptor) {+ const assetTypeInfo = AssetModelUtil.getAssetTypeInfo(assetDescriptor);++ attributes =+ !assetTypeInfo || !assetTypeInfo.attributeDescriptors+ ? []+ : assetTypeInfo.attributeDescriptors.map((ad) => {+ const label = Util.getAttributeLabel(ad, descriptors[0], assetType, false);+ return [ad.name!, label];+ });+ }++ attributes.sort(Util.sortByString((attr) => attr[1]));+ let attributeInput: TemplateResult | undefined;+ if (this.action.attributeName) {+ const label = descriptors[1] && (descriptors[1].name === WellknownValueTypes.BOOLEAN) ? "" : i18next.t("value");+ let inputType;+ if(descriptors[0]?.format?.asSlider) inputType = InputType.NUMBER;+ attributeInput = html`<or-attribute-input ?compact=${descriptors[1] && (descriptors[1].name === WellknownValueTypes.GEOJSONPOINT)} .inputType="${ifDefined(inputType)}" @or-attribute-input-changed="${(ev: OrAttributeInputChangedEvent) => this.setActionAttributeValue(ev.detail.value)}" .customProvider="${this.config?.inputProvider}" .label="${label}" .assetType="${assetType}" .attributeDescriptor="${descriptors[0]}" .attributeValueDescriptor="${descriptors[1]}" .value="${this.action.value}" .readonly="${this.readonly || false}"></or-attribute-input>`;+ }++ 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(); }}"+ ></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>+ ${attributeInput}+ ` : html`+ <or-translate value="No attributes with write permission"></or-translate>+ `}+ `;+ })}`;}@@ -201,13 +240,8 @@ export class OrRuleActionAttribute extends translate(i18next)(LitElement) {}protected loadAssets(type: string) {- manager.rest.api.AssetResource.queryAssets({- types: [- type- ],- orderBy: {- property: AssetQueryOrderBy$Property.NAME- }- }).then((response) => this._assets = response.data);+ this.assetProvider(type).then(assets => {+ this._assets = 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.tsindex 4f6821d21..8e261328f 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@@ -1,11 +1,10 @@import {css, html, LitElement, PropertyValues} from "lit";-import {customElement, property} from "lit/decorators.js";+import {customElement, property, state} from "lit/decorators.js";import {Asset,AssetDescriptor,AssetQueryMatch,AssetQueryOperator as AQO,- AssetQueryOrderBy$Property,AssetTypeInfo,Attribute,AttributeDescriptor,@@ -23,7 +22,7 @@ import {AssetQueryOperator, getAssetIdsFromQuery, getAssetTypeFromQuery, RulesCoimport "@openremote/or-mwc-components/or-mwc-input";import {InputType, OrInputChangedEvent} from "@openremote/or-mwc-components/or-mwc-input";import "@openremote/or-attribute-input";-import manager, {Util} from "@openremote/core";+import {Util} from "@openremote/core";import i18next from "i18next";import {buttonStyle} from "../style";import {OrRulesJsonRuleChangedEvent} from "./or-rule-json-viewer";@@ -31,6 +30,7 @@ import {translate} from "@openremote/or-translate";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';// language=CSSconst style = css`@@ -56,6 +56,12 @@ const style = css`.attribute-group > * {margin: 10px 3px 6px 3px;}+ .invalidLabel {+ display: flex;+ align-items: center;+ margin: 14px 3px auto 0;+ height: 48px; /* Same as the icon size */+ }`;@customElement("or-rule-asset-query")@@ -72,7 +78,10 @@ export class OrRuleAssetQuery extends translate(i18next)(LitElement) {@property({type: Object})public assetInfos?: AssetTypeInfo[];- @property({type: Array, attribute: false})+ @property({type: Object})+ public assetProvider!: (type: string) => Promise<Asset[] | undefined>++ @state()protected _assets?: Asset[];// Value predicates for specific value descriptors@@ -256,18 +265,17 @@ export class OrRuleAssetQuery extends translate(i18next)(LitElement) {const assetType = getAssetTypeFromQuery(this.query);if (!assetType) {- return html``;+ return html`<span class="invalidLabel">${i18next.t('errorOccurred')}</span>`;}const assetTypeInfo = this.assetInfos ? this.assetInfos.find((assetTypeInfo) => assetTypeInfo.assetDescriptor!.name === assetType) : undefined;if (!assetTypeInfo) {- return html``;+ return html`<span class="invalidLabel">${i18next.t('errorOccurred')}</span>`;}if (!this._assets) {this.loadAssets(assetType);- return html``;}if (!this.query.attributes) {@@ -286,22 +294,53 @@ export class OrRuleAssetQuery extends translate(i18next)(LitElement) {const idOptions: [string, string] [] = [["*", i18next.t("anyOfThisType")]];+ let searchProvider: (search?: string) => Promise<[any, string][]>;- idOptions.push(...this._assets!.map((asset) => [asset.id!, asset.name!] as [string, string]));return html`<div class="attribute-group">- <or-mwc-input id="idSelect" class="min-width" type="${InputType.SELECT}" @or-mwc-input-changed="${(e: OrInputChangedEvent) => this._assetId = (e.detail.value)}" .readonly="${this.readonly || false}" .options="${idOptions}" .value="${idValue}" .label="${i18next.t("asset")}"></or-mwc-input>-- ${this.query.attributes && this.query.attributes.items ? this.query.attributes.items.map((attributePredicate) => {-+ <!-- 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>+ `, () => {++ // 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]));+ } 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;+ } 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.+ }+ return idOptions;+ }+ }+ }return html`- ${this.attributePredicateEditorTemplate(assetTypeInfo, idValue !== "*" ? this._assets!.find((asset) => asset.id === idValue) : undefined, attributePredicate)}- ${showRemoveAttribute ? html`- <button class="button-clear" @click="${() => this.removeAttributePredicate(this.query!.attributes!, attributePredicate)}"><or-icon icon="close-circle"></or-icon></input>- ` : ``}+ <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(); }}"+ ></or-mwc-input>+ ${this.query.attributes && this.query.attributes.items ? this.query.attributes.items.map((attributePredicate) => {+ return html`+ ${this.attributePredicateEditorTemplate(assetTypeInfo, idValue !== "*" ? this._assets!.find((asset) => asset.id === idValue) : undefined, attributePredicate)}+ ${showRemoveAttribute ? html`+ <button class="button-clear" @click="${() => this.removeAttributePredicate(this.query!.attributes!, attributePredicate)}"><or-icon icon="close-circle"></or-icon></input>+ ` : ``}+ `;+ }) : ``}`;- }) : ``}+ })}</div>`;}@@ -690,13 +729,8 @@ export class OrRuleAssetQuery extends translate(i18next)(LitElement) {}protected loadAssets(type: string) {- manager.rest.api.AssetResource.queryAssets({- types: [- type- ],- orderBy: {- property: AssetQueryOrderBy$Property.NAME- }- }).then((response) => this._assets = response.data);+ this.assetProvider(type).then(assets => {+ this._assets = 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.tsindex 2b58e4e63..e8e28e2e9 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@@ -142,6 +142,9 @@ class OrRuleCondition extends translate(i18next)(LitElement) {@property({type: Object})public assetInfos?: AssetTypeInfo[];+ @property({type: Object})+ public assetProvider?: (type: string) => Promise<any[] | undefined>+@query("#asset-query")protected _assetQuery?: OrRuleAssetQuery;@@ -205,7 +208,9 @@ class OrRuleCondition extends translate(i18next)(LitElement) {template = html`<or-rule-trigger-query id="asset-query" .condition="${this.ruleCondition}"></or-rule-trigger-query>`;break;default:- template = html`<or-rule-asset-query id="asset-query" .config="${this.config}" .assetInfos="${this.assetInfos}" .readonly="${this.readonly}" .condition="${this.ruleCondition}"></or-rule-asset-query>`;+ template = html`<or-rule-asset-query id="asset-query" .config="${this.config}" .assetInfos="${this.assetInfos}" .readonly="${this.readonly}"+ .condition="${this.ruleCondition}" .assetProvider="${this.assetProvider}"+ ></or-rule-asset-query>`;break;}}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.tsindex 8a7003cec..97b83c806 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@@ -1,7 +1,7 @@import {css, html, LitElement, PropertyValues, TemplateResult} from "lit";-import {customElement, property} from "lit/decorators.js";+import {customElement, property, state} from "lit/decorators.js";import {- getAssetInfos,+ getAssetInfos, getAssetsByType,getAssetTypeFromQuery,OrRulesRuleChangedEvent,OrRulesRuleUnsupportedEvent,@@ -9,6 +9,7 @@ import {RuleView} from "../index";import {+ Asset,AssetQuery,AssetQueryOperator as AQO,AssetTypeInfo,@@ -119,8 +120,12 @@ export class OrRuleJsonViewer extends translate(i18next)(LitElement) implements@property({attribute: false})protected _ruleset!: RulesetUnion;+ @state()+ protected _loadedAssets: Map<string, Asset[]> = new Map<string, []>();+protected _rule!: JsonRule;protected _unsupported = false;+ protected _activeAssetPromises: Map<string, Promise<any>> = new Map<string, Promise<any>>();protected _assetTypeInfo?: AssetTypeInfo[];_whenAssetInfos?: AssetTypeInfo[];_actionAssetInfos?: AssetTypeInfo[];@@ -197,15 +202,36 @@ export class OrRuleJsonViewer extends translate(i18next)(LitElement) implementsconst targetTypeMap = getTargetTypeMap(this._rule);return html`<div class="section-container">- <or-rule-when .rule="${this._rule}" .config="${this.config}" .assetInfos="${this._whenAssetInfos}" ?readonly="${this.readonly}"></or-rule-when>+ <or-rule-when .rule="${this._rule}" .config="${this.config}" .assetInfos="${this._whenAssetInfos}" ?readonly="${this.readonly}"+ .assetProvider="${async (type: string) => this.loadAssets(type)}"+ ></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}"></or-rule-then-otherwise>+ <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)}"+ ></or-rule-then-otherwise></div>`;}+ // 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)) {+ const data = await (this._activeAssetPromises.get(type)); // await for the already existing fetch+ return data.assets;+ } else {+ const promise = getAssetsByType(type, this._loadedAssets);+ this._activeAssetPromises.set(type, promise);+ const data = await promise;+ this._activeAssetPromises.delete(type);+ this._loadedAssets = data.loadedAssets!;+ return data.assets;+ }+ }+protected loadAssetDescriptors(useActionConfig: boolean) {getAssetInfos(this.config, useActionConfig).then(result => {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.tsindex 60edafca3..5a346b796 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@@ -13,7 +13,9 @@ import {RuleActionUnion,RuleActionWebhook,RuleRecurrence,- WellknownAssets+ WellknownAssets,+ AssetModelUtil,+ Asset} from "@openremote/model";import i18next from "i18next";import {InputType} from "@openremote/or-mwc-components/or-mwc-input";@@ -227,6 +229,9 @@ class OrRuleThenOtherwise extends translate(i18next)(LitElement) {@property({type: Object, attribute: false})public assetInfos?: AssetTypeInfo[];+ @property({type: Object})+ public assetProvider?: (type: string) => Promise<Asset[] | undefined>+protected get thenAllowAdd() {return !this.config || !this.config.controls || this.config.controls.hideThenAddAction !== true;}@@ -353,7 +358,7 @@ class OrRuleThenOtherwise extends translate(i18next)(LitElement) {template = html`<or-rule-action-webhook .rule="${this.rule}" .action="${action}" .actionType="${ActionType.WEBHOOK}"></or-rule-action-webhook>`;break;default:- template = html`<or-rule-action-attribute .action="${action}" .targetTypeMap="${this.targetTypeMap}" .config="${this.config}" .assetInfos="${this.assetInfos}" .readonly="${this.readonly}"></or-rule-action-attribute>`;+ 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>`;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.tsindex 3dcb41f85..382f91d51 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} from "@openremote/model";+import {AssetDescriptor, JsonRule, LogicGroup, LogicGroupOperator, RuleCondition, WellknownAssets, AssetTypeInfo, Asset} from "@openremote/model";import {OrRulesRuleUnsupportedEvent, RulesConfig} from "../index";import {buttonStyle} from "../style";import "./or-rule-condition";@@ -115,6 +115,9 @@ class OrRuleWhen extends translate(i18next)(LitElement) {@property({type: Boolean})public readonly?: boolean;+ @property({type: Object})+ public assetProvider?: (type: string) => Promise<Asset[]>+public config?: RulesConfig;@property({type: Object, attribute: false})@@ -182,7 +185,7 @@ class OrRuleWhen extends translate(i18next)(LitElement) {const content = html`<div class="rule-group-item"><div class="rule-condition">- <or-rule-condition .config="${this.config}" .assetInfos="${this.assetInfos}" .ruleCondition="${condition}" .readonly="${this.readonly}" ></or-rule-condition>+ <or-rule-condition .config="${this.config}" .assetInfos="${this.assetInfos}" .ruleCondition="${condition}" .readonly="${this.readonly}" .assetProvider="${this.assetProvider}"></or-rule-condition>${showRemoveGroup ? html`<button class="button-clear ${showRemoveCondition ? "" : "hidden"}" @click="${() => this.removeItem(condition, group, false)}"><or-icon icon="close-circle"></or-icon></input>` : ``}