Skip to content

armgit / core

Public Imported from GitHub
0

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

UI updates: or-rules-editor renamed or-rules (support for all languages partially added)

Rich Turner517b3c7800a9
diff --git a/deployment/manager/shared/locales/en/or.json b/deployment/manager/shared/locales/en/or.json
index 454b54e45..bc980faed 100644
--- a/deployment/manager/shared/locales/en/or.json
+++ b/deployment/manager/shared/locales/en/or.json
@@ -76,7 +76,7 @@
"confirmDeleteAssets": "Remove assets?",
"ok": "OK",
"cancel": "Cancel",
- "createdOn": "Created on:",
+ "createdOn": "Created on",
"createdOnWithDate": "Created on: {{-date, LLLL}}",
"accessPublicRead": "Public read",
"type": "Type",
@@ -105,5 +105,6 @@
"wait": "Wait",
"history": "History",
"attributes": "Attributes",
- "info": "Info"
+ "info": "Info",
+ "notSupported": "Not supported"
}
diff --git a/ui/app/main/package.json b/ui/app/main/package.json
index 7382a6c6c..bc5b0eaf9 100644
--- a/ui/app/main/package.json
+++ b/ui/app/main/package.json
@@ -20,7 +20,7 @@
"@openremote/or-asset-viewer": "^1.1.0",
"@openremote/or-header": "^1.1.0",
"@openremote/or-map": "^1.1.0",
- "@openremote/or-rules-editor": "^1.1.0",
+ "@openremote/or-rules": "^1.1.0",
"@openremote/or-smart-notify": "^1.1.0",
"@openremote/or-timeline": "^1.1.0",
"@openremote/rest": "^1.1.0",
diff --git a/ui/app/main/src/components/pages/page-rules.ts b/ui/app/main/src/components/pages/page-rules.ts
index 6c328a4d2..c0b16069d 100644
--- a/ui/app/main/src/components/pages/page-rules.ts
+++ b/ui/app/main/src/components/pages/page-rules.ts
@@ -1,7 +1,7 @@
import {html, LitElement, property, css, query, customElement, PropertyValues} from "lit-element";
import {store} from "../../store";
import {connect} from "pwa-helpers/connect-mixin";
-import "@openremote/or-rules-editor";
+import "@openremote/or-rules";
@customElement("page-rules")
class PageRules extends connect(store)(LitElement) {
@@ -12,7 +12,7 @@ class PageRules extends connect(store)(LitElement) {
}
- or-rules-editor {
+ or-rules {
width: 100%;
height: 100%;
}
@@ -21,7 +21,7 @@ class PageRules extends connect(store)(LitElement) {
protected render() {
return html`
- <or-rules-editor></or-rules-editor>
+ <or-rules></or-rules>
`;
}
}
diff --git a/ui/app/main/tsconfig.json b/ui/app/main/tsconfig.json
index c7da13345..08402a654 100644
--- a/ui/app/main/tsconfig.json
+++ b/ui/app/main/tsconfig.json
@@ -17,6 +17,6 @@
{ "path": "../../component/or-asset-tree" },
{ "path": "../../component/or-attribute-input" },
{ "path": "../../component/or-asset-viewer" },
- { "path": "../../component/or-rules-editor" }
+ { "path": "../../component/or-rules" }
]
}
\ No newline at end of file
diff --git a/ui/component/core/src/index.ts b/ui/component/core/src/index.ts
index 5c2faf6f2..addd25834 100644
--- a/ui/component/core/src/index.ts
+++ b/ui/component/core/src/index.ts
@@ -118,6 +118,11 @@ export class IconSetAddedEvent extends CustomEvent<void> {
}
}
+export interface OrManagerEventDetail {
+ event: OREvent;
+ error?: ORError;
+}
+
declare global {
export interface HTMLElementEventMap {
[IconSetAddedEvent.NAME]: IconSetAddedEvent;
@@ -873,18 +878,9 @@ export class Manager implements EventProviderFactory {
// so this will need updating.
protected async loadAndInitialiseKeycloak(): Promise<boolean> {
- // Load the keycloak JS API
- const promise = new Promise<Event>((resolve, reject) => {
- // Load keycloak script from keycloak server
- const scriptElement = document.createElement("script");
- scriptElement.src = this._config.keycloakUrl + "/js/keycloak.js";
- scriptElement.onload = (e) => resolve(e);
- scriptElement.onerror = (e) => reject(e);
- document.querySelector("head")!.appendChild(scriptElement);
- });
-
try {
- await promise;
+ // Load the keycloak JS API
+ await Util.loadJs(this._config.keycloakUrl + "/js/keycloak.js");
// Should have Keycloak global var now
if (!(window as any).Keycloak) {
@@ -957,6 +953,7 @@ export class Manager implements EventProviderFactory {
}
} catch (error) {
this._setError(ORError.KEYCLOAK_FAILED_TO_LOAD);
+ console.error("Failed to load Keycloak");
return false;
}
}
diff --git a/ui/component/core/src/util.ts b/ui/component/core/src/util.ts
index d8e721342..42cf0ca06 100644
--- a/ui/component/core/src/util.ts
+++ b/ui/component/core/src/util.ts
@@ -293,8 +293,8 @@ export function loadJs(url: string) {
let script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
- script.addEventListener('load', () => resolve(script), false);
- script.addEventListener('error', () => reject(script), false);
+ script.addEventListener('load', (e) => resolve(e), false);
+ script.addEventListener('error', (e) => reject(e), false);
document.body.appendChild(script);
});
};
diff --git a/ui/component/model/build.gradle b/ui/component/model/build.gradle
index a06bd40f2..00f7a2632 100644
--- a/ui/component/model/build.gradle
+++ b/ui/component/model/build.gradle
@@ -77,7 +77,8 @@ npmBuild.dependsOn generateTypeScript
clean {
doLast {
- delete "dist"
+ def dir = new File("${projectDir}/dist")
+ dir.deleteDir()
}
}
diff --git a/ui/component/or-asset-tree/src/index.ts b/ui/component/or-asset-tree/src/index.ts
index df9677548..c8619f304 100644
--- a/ui/component/or-asset-tree/src/index.ts
+++ b/ui/component/or-asset-tree/src/index.ts
@@ -8,6 +8,8 @@ import manager, {AssetModelUtil, OREvent, EventCallback} from "@openremote/core"
import {OrInputChangedEvent, InputType} from "@openremote/or-input";
import Qs from "qs";
import {getAssetDescriptorIconTemplate} from "@openremote/or-icon";
+import {getContentWithMenuTemplate, MenuItem} from "@openremote/or-mwc-components/dist/or-mwc-menu";
+import {i18next} from "@openremote/or-translate";
export interface UiAssetTreeNode extends AssetTreeNode {
selected: boolean;
@@ -145,6 +147,12 @@ export class OrAssetTree extends LitElement {
@property({type: String})
public realm?: string;
+ @property({type: Boolean})
+ public readonly: boolean = false;
+
+ @property({type: Boolean})
+ public disabled: boolean = false;
+
@property({type: Boolean})
public multiSelect?: boolean = true;
@@ -169,15 +177,6 @@ export class OrAssetTree extends LitElement {
@property()
protected _showLoading: boolean = true;
- @query("#sort-menu")
- protected _sortMenu!: HTMLDivElement;
-
- @query("#delete-not-allowed-modal")
- protected _deleteNotAllowedModal!: HTMLDivElement;
-
- @query("#delete-confirm-modal")
- protected _deleteConfirmModal!: HTMLDivElement;
-
protected _selectedNodes: UiAssetTreeNode[] = [];
protected _initCallback?: EventCallback;
protected _ready = false;
@@ -207,18 +206,6 @@ export class OrAssetTree extends LitElement {
} else {
this._onReady();
}
-
- this.addEventListener("click", (evt) => {
- if (this._sortMenu.hasAttribute("data-visible") && !this._sortMenu.contains(evt.target as Node)) {
- this._sortMenu.toggleAttribute("data-visible");
- }
- if (this._deleteNotAllowedModal.hasAttribute("data-visible") && !this._deleteNotAllowedModal.contains(evt.target as Node)) {
- this._deleteNotAllowedModal.toggleAttribute("data-visible");
- }
- if (this._deleteConfirmModal.hasAttribute("data-visible") && !this._deleteConfirmModal.contains(evt.target as Node)) {
- this._deleteConfirmModal.toggleAttribute("data-visible");
- }
- });
}
protected render() {
@@ -230,49 +217,17 @@ export class OrAssetTree extends LitElement {
${manager.isSuperUser() ? html `<or-input id="realm-picker" type="${InputType.SELECT}" .value="${this._getRealm()}" .options="${this._realms ? this._realms.map((tenant) => [tenant.realm, tenant.displayName]) : []}" @or-input-changed="${(evt: OrInputChangedEvent) => this._onRealmChanged(evt)}"></or-input>` : ``}
</div>
- <div id="header-btns">
- <button style="display:none;" ?hidden="${!manager.hasRole("write:rules") || !this.selectedIds || this.selectedIds.length === 0}" @click="${() => this._onCopyClicked()}"><or-icon icon="content-copy"></or-icon></button>
- <button ?hidden="${!manager.hasRole("write:rules") || !this.selectedIds || this.selectedIds.length === 0}" @click="${() => this._onDeleteClicked()}"><or-icon icon="delete"></or-icon></button>
- <button hidden @click="${() => this._onAddClicked()}"><or-icon icon="plus"></or-icon></button>
- <button hidden @click="${() => this._onSearchClicked()}"><or-icon icon="magnify"></or-icon></button>
- <button @click="${() => this._onSortClicked()}"><or-icon icon="sort-variant"></or-icon></button>
- <div class="modal-container">
- <div class="modal" id="sort-menu">
- <div class="modal-content">
- <ul>
- <li @click="${() => this.sortBy = "name"}" ?data-selected="${!this.sortBy || this.sortBy === "name"}"><or-icon icon="check"></or-icon><or-translate value="name"></or-translate></li>
- <li @click="${() => this.sortBy = "type"}" ?data-selected="${this.sortBy === "type"}"><or-icon icon="check"></or-icon><or-translate value="assetType"></or-translate></li>
- <li @click="${() => this.sortBy = "created"}" ?data-selected="${this.sortBy === "created"}"><or-icon icon="check"></or-icon><or-translate value="creationDate"></or-translate></li>
- <li @click="${() => this.sortBy = "status"}" ?data-selected="${this.sortBy === "status"}"><or-icon icon="check"></or-icon><or-translate value="status"></or-translate></li>
- </ul>
- </div>
- </div>
- </div>
- <div class="modal-container">
- <div class="modal" id="delete-not-allowed-modal">
- <div class="modal-content">
- <p>
- <or-translate value="deleteAssetsNoChildrenAllowed"></or-translate>
- </p>
- <div class="modal-btns">
- <span class="btn" @click="${() => this._deleteNotAllowedModal.toggleAttribute("data-visible")}"><or-translate value="ok"></or-translate></span>
- </div>
- </div>
- </div>
- </div>
- <div class="modal-container">
- <div class="modal" id="delete-confirm-modal">
- <div class="modal-content">
- <p>
- <or-translate value="confirmDeleteAssets"></or-translate>
- </p>
- <div class="modal-btns">
- <span class="btn" @click="${() => this._deleteConfirmModal.toggleAttribute("data-visible")}"><or-translate value="cancel"></or-translate></span>
- <span class="btn" @click="${() => this._doDelete()}"><or-translate value="ok"></or-translate></span>
- </div>
- </div>
- </div>
- </div>
+ <div id="header-btns">
+ <or-input style="display: none;" ?hidden="${this._isReadonly() || !this.selectedIds || this.selectedIds.length === 0}" type="${InputType.BUTTON}" icon="content-copy" @click="${() => this._onCopyClicked()}"></or-input>
+ <or-input ?hidden="${this._isReadonly() || !this.selectedIds || this.selectedIds.length === 0}" type="${InputType.BUTTON}" icon="delete" @click="${() => this._onDeleteClicked()}"></or-input>
+ <or-input style="display: none;" ?hidden="${this._isReadonly()}" type="${InputType.BUTTON}" icon="plus" @click="${() => this._onAddClicked()}"></or-input>
+ <or-input hidden type="${InputType.BUTTON}" icon="magnify" @click="${() => this._onSearchClicked()}"></or-input>
+
+ ${getContentWithMenuTemplate(
+ html`<or-input type="${InputType.BUTTON}" icon="sort-variant"></or-input>`,
+ ["name", "type", "createdOn", "status"].map((sort) => {return {value: sort, content: html`<span class="no-wrap">${i18next.t(sort)}</span>`} as MenuItem;}),
+ this.sortBy,
+ (v) => this._onSortClicked(v))}
</div>
</div>
@@ -294,6 +249,10 @@ export class OrAssetTree extends LitElement {
`;
}
+ protected _isReadonly() {
+ return this.readonly || !manager.hasRole("write:rules");
+ }
+
protected _treeNodeTemplate(treeNode: UiAssetTreeNode, level: number): TemplateResult | string {
const descriptor = AssetModelUtil.getAssetDescriptor(treeNode.asset!.type!);
@@ -421,7 +380,7 @@ export class OrAssetTree extends LitElement {
}
protected _onDeleteClicked() {
- this._doRequest(new OrAssetTreeRequestDeleteEvent(this._selectedNodes), (nodes) => this._showDeleteModal());
+ this._doRequest(new OrAssetTreeRequestDeleteEvent(this._selectedNodes), (nodes) => this._doDelete());
}
protected _onAddClicked() {
@@ -432,13 +391,8 @@ export class OrAssetTree extends LitElement {
}
- protected _onSortClicked() {
- // Do open on next task to prevent click handler closing it immediately
- if (!this._sortMenu.hasAttribute("data-visible")) {
- window.setTimeout(() => {
- this._sortMenu.toggleAttribute("data-visible");
- });
- }
+ protected _onSortClicked(sortBy: string) {
+ this.sortBy = sortBy;
}
protected _doSelect(detail: NodeClickEventDetail) {
@@ -476,7 +430,7 @@ export class OrAssetTree extends LitElement {
this.selectedIds = selectedIds;
}
- protected _showDeleteModal() {
+ protected _doDelete() {
if (!this._selectedNodes) {
return;
@@ -484,24 +438,15 @@ export class OrAssetTree extends LitElement {
// Check each selected node has no children
if (this._selectedNodes.find((node) => node.children && node.children.length > 0)) {
- // Do open on next task to prevent click handler closing it immediately
- window.setTimeout(() => {
- this._deleteNotAllowedModal.toggleAttribute("data-visible");
- });
+ window.alert(i18next.t("deleteAssetsNoChildrenAllowed"));
return;
}
- // Do open on next task to prevent click handler closing it immediately
- window.setTimeout(() => {
- this._deleteConfirmModal.toggleAttribute("data-visible");
- });
- }
-
- protected _doDelete() {
- if (!this._selectedNodes) {
+ if (!this._okToDelete()) {
return;
}
+ this.disabled = true;
manager.rest.api.AssetResource.delete({
assetId: this._selectedNodes.map((node) => node.asset!.id!)
}, {
@@ -518,7 +463,11 @@ export class OrAssetTree extends LitElement {
// Clear nodes to refetch them
this._nodes = undefined;
});
- this._showLoading = true;
+ this.disabled = true;
+ }
+
+ protected _okToDelete() {
+ return window.confirm(i18next.t("confirmDeleteAssets"));
}
protected _doAdd() {
@@ -530,19 +479,7 @@ export class OrAssetTree extends LitElement {
}
protected _getSortFunction(): (a: UiAssetTreeNode, b: UiAssetTreeNode) => number {
-
- const nameSort = (a: UiAssetTreeNode, b: UiAssetTreeNode) => { return a.asset!.name! < b.asset!.name! ? -1 : a.asset!.name! > b.asset!.name! ? 1 : 0 };
-
- switch (this.sortBy) {
- case "created":
- return (a, b) => { return a.asset!.createdOn! < b.asset!.createdOn! ? -1 : a.asset!.createdOn! > b.asset!.createdOn! ? 1 : nameSort(a, b) };
- case "status":
- return (a, b) => { return a.asset!.name! < b.asset!.name! ? -1 : a.asset!.name! > b.asset!.name! ? 1 : nameSort(a, b) };
- case "type":
- return (a, b) => { return a.asset!.type! < b.asset!.type! ? -1 : a.asset!.type! > b.asset!.type! ? 1 : nameSort(a, b) };
- default:
- return nameSort;
- }
+ return (a, b) => { return (a.asset as any)![this.sortBy!] < (b.asset as any)![this.sortBy!] ? -1 : (a.asset as any)![this.sortBy!] > (b.asset as any)![this.sortBy!] ? 1 : 0 };
}
protected _getRealm(): string | undefined {
diff --git a/ui/component/or-asset-tree/src/style.ts b/ui/component/or-asset-tree/src/style.ts
index 61584ef89..9c3094ec9 100644
--- a/ui/component/or-asset-tree/src/style.ts
+++ b/ui/component/or-asset-tree/src/style.ts
@@ -11,7 +11,7 @@ export const style = css`
--internal-or-asset-tree-header-text-color: var(--or-asset-tree-header-text-color, var(--or-app-color7, ${unsafeCSS(DefaultColor1)}));
--internal-or-asset-tree-header-menu-background-color: var(--or-asset-tree-header-menu-background-color, var(--internal-or-asset-tree-header-text-color));
--internal-or-asset-tree-header-menu-text-color: var(--or-asset-tree-header-menu-text-color, inherit);
- --internal-or-asset-tree-header-height: var(--or-asset-tree-header-height, 40px);
+ --internal-or-asset-tree-header-height: var(--or-asset-tree-header-height, 48px);
--internal-or-asset-tree-background-color: var(--or-asset-tree-background-color, var(--or-app-color1, ${unsafeCSS(DefaultColor1)}));
--internal-or-asset-tree-text-color: var(--or-asset-tree-text-color, inherit);
--internal-or-asset-tree-item-height: var(--or-asset-tree-item-height, 24px);
@@ -53,14 +53,13 @@ export const style = css`
#header {
background-color: var(--internal-or-asset-tree-header-color);
display: flex;
+ align-items: center;
width: 100%;
height: var(--internal-or-asset-tree-header-height);
border-bottom: 1px solid ${unsafeCSS(DefaultColor5)};
z-index: 1000;
- }
-
- #header > * {
line-height: var(--internal-or-asset-tree-header-height);
+ color: var(--internal-or-asset-tree-header-text-color);
}
#title-container {
@@ -79,8 +78,7 @@ export const style = css`
#title {
font-weight: 500;
- font-size: 16px;
- color: var(--internal-or-asset-tree-header-text-color);
+ font-size: 16px;
}
#realm-picker {
@@ -95,100 +93,7 @@ export const style = css`
flex-direction: row;
padding-right: 5px;
}
-
- .modal-container {
- position: relative;
- line-height: normal;
- }
-
- .modal {
- position: absolute;
- height: 0;
- overflow: hidden;
- }
-
- .modal[data-visible] {
- transition: all 0.5s ease-in;
- height: auto;
- overflow: visible;
- }
-
- .modal-content {
- border: 1px solid var(--internal-or-asset-tree-line-color);
- box-shadow: ${unsafeCSS(DefaultBoxShadow)};
- -moz-box-shadow: ${unsafeCSS(DefaultBoxShadow)};
- -webkit-box-shadow: ${unsafeCSS(DefaultBoxShadow)};
- color: var(--internal-or-asset-tree-header-menu-text-color);
- background-color: var(--internal-or-asset-tree-header-menu-background-color);
- padding: 5px 0;
- font-size: 14px;
- }
-
- .modal-content > ul {
- list-style-type: none;
- padding: 0;
- margin: 0;
- white-space: nowrap;
- }
-
- .modal-content > ul > li {
- padding: 8px 10px;
- cursor: pointer;
- }
- .modal-content > ul > li:hover {
- background-color: var(--internal-or-asset-tree-selected-background-color);
- }
-
- .modal-content > ul > li > or-icon {
- visibility: hidden;
- width: 16px;
- height: 16px;
- margin-right: 8px;
- --or-icon-fill: var(--internal-or-asset-tree-header-color);
- --or-icon-stroke: var(--internal-or-asset-tree-header-color);
- --or-icon-stroke-width: 2px;
- }
-
- .modal-content > ul > li[data-selected] > or-icon {
- visibility: visible;
- }
-
- .modal-content > p {
- padding: 0 15px;
- margin: 10px 0;
- }
-
- .modal-btns {
- text-align: right;
- padding: 5px 15px;
- }
-
- .modal-btns .btn {
- font-weight: 500;
- cursor: pointer;
- text-transform: uppercase;
- }
-
- .modal-btns .btn + .btn {
- margin-left: 15px;
- }
-
- #sort-menu {
- left: -130px;
- top: calc(var(--internal-or-asset-tree-header-height) - 5px);
- }
-
- #delete-not-allowed-modal {
- left: -200px;
- top: calc(var(--internal-or-asset-tree-header-height) - 5px);
- }
-
- #delete-confirm-modal {
- left: -200px;
- top: calc(var(--internal-or-asset-tree-header-height) - 5px);
- }
-
#list-container {
flex: 1 1 auto;
overflow: auto;
diff --git a/ui/component/or-asset-tree/tsconfig.json b/ui/component/or-asset-tree/tsconfig.json
index fc75e1a9e..fc31eb69f 100644
--- a/ui/component/or-asset-tree/tsconfig.json
+++ b/ui/component/or-asset-tree/tsconfig.json
@@ -14,6 +14,7 @@
{ "path": "../model" },
{ "path": "../or-translate" },
{ "path": "../or-input" },
- { "path": "../or-icon" }
+ { "path": "../or-icon" },
+ { "path": "../or-mwc-components" }
]
}
\ No newline at end of file
diff --git a/ui/component/or-input/src/index.ts b/ui/component/or-input/src/index.ts
index 24be2a9a0..553b4d400 100644
--- a/ui/component/or-input/src/index.ts
+++ b/ui/component/or-input/src/index.ts
@@ -1,7 +1,6 @@
-import {css, customElement, html, LitElement, property, PropertyValues, TemplateResult, unsafeCSS} from "lit-element";
+import {css, customElement, html, LitElement, property, PropertyValues, TemplateResult, unsafeCSS, query} from "lit-element";
import {classMap} from "lit-html/directives/class-map";
import {ifDefined} from "lit-html/directives/if-defined";
-import {orInputStyle} from "./style";
import {MDCTextField} from "@material/textfield";
import {MDCComponent} from "@material/base";
import {MDCRipple} from "@material/ripple";
@@ -11,6 +10,7 @@ import {MDCSelect, MDCSelectEvent, } from "@material/select";
import {MDCFormField, MDCFormFieldInput} from "@material/form-field";
import {MDCIconButtonToggle, MDCIconButtonToggleEventDetail} from "@material/icon-button";
import moment from "moment";
+import {DefaultColor1, DefaultColor4} from "@openremote/core";
// TODO: Add webpack/rollup to build so consumers aren't forced to use the same tooling
const buttonStyle = require("!!raw-loader!@material/button/dist/mdc.button.css");
@@ -80,6 +80,82 @@ export enum InputType {
SELECT = "select"
}
+// language=CSS
+const style = css`
+
+ :host {
+ display: inline-block;
+ --internal-or-input-color: var(--or-input-color, var(--or-app-color4, ${unsafeCSS(DefaultColor4)}));
+ --internal-or-input-text-color: var(--or-input-text-color, var(--or-app-color1, inherit));
+
+ --mdc-theme-primary: var(--internal-or-input-color);
+ --mdc-theme-on-primary: var(--internal-or-input-text-color);
+ --mdc-theme-secondary: var(--internal-or-input-color);
+ }
+
+ #wrapper {
+ display: flex;
+ align-items: center;
+ }
+
+ #wrapper > label {
+ margin-left: 10px;
+ }
+
+ .or-input--rounded {
+ border-radius: 50% !important;
+ }
+
+ /* MDC TEXT FIELD AND SELECT DON'T USE THEME VARS */
+ .mdc-text-field--focused:not(.mdc-text-field--disabled) .mdc-floating-label {
+ color: var(--mdc-theme-primary);
+ }
+ .mdc-text-field--focused .mdc-text-field__input:required ~ .mdc-floating-label::after,
+ .mdc-text-field--focused .mdc-text-field__input:required ~ .mdc-notched-outline .mdc-floating-label::after {
+ color: var(--mdc-theme-primary);
+ }
+
+ .mdc-select:not(.mdc-select--disabled).mdc-select--focused .mdc-floating-label {
+ color: var(--mdc-theme-primary);
+ }
+
+ .mdc-text-field, .mdc-text-field-helper-line {
+ width: inherit;
+ }
+
+ .mdc-text-field--dense:not(.mdc-text-field--no-label):not(.mdc-text-field--outlined) {
+ height: 52px;
+ }
+
+ .mdc-text-field--dense.mdc-text-field--no-label {
+ height: 40px;
+ }
+
+ .mdc-text-field--dense .mdc-text-field__input {
+ white-space: nowrap;
+ }
+
+ .mdc-select__dropdown-icon {
+ background: none;
+ }
+
+ .mdc-select--focused .mdc-select__dropdown-icon {
+ --or-icon-fill: var(--internal-or-input-color);
+ }
+
+ .mdc-icon-button {
+ --or-icon-fill: var(--internal-or-input-text-color);
+ }
+
+ .mdc-icon-button {
+ padding: 0;
+ }
+
+ #field {
+ height: 100%;
+ }
+`;
+
@customElement("or-input")
export class OrInput extends LitElement {
@@ -99,7 +175,7 @@ export class OrInput extends LitElement {
css`${unsafeCSS(listStyle)}`,
css`${unsafeCSS(menuStyle)}`,
css`${unsafeCSS(menuSurfaceStyle)}`,
- orInputStyle
+ style
];
}
@@ -244,7 +320,7 @@ export class OrInput extends LitElement {
return html`<span>RADIO</span>`;
case InputType.SWITCH:
return html`
- <div id="field" class="mdc-form-field ${this.dense ? "mdc-form-field--dense" : ""}">
+ <span id="wrapper">
<div id="component" class="mdc-switch ${this.disabled || this.readonly ? "mdc-switch--disabled" : ""} ${this.value ? "mdc-switch--checked" : ""}">
<div class="mdc-switch__track"></div>
<div class="mdc-switch__thumb-underlay">
@@ -253,13 +329,13 @@ export class OrInput extends LitElement {
?checked="${this.value}"
?required="${this.required}"
?disabled="${this.disabled || this.readonly}"
- @change="${(e: Event) => this.onValueChange((e.target as HTMLInputElement).checked)}"
+ @change="${(e: Event) => this.onValueChange((e.target as HTMLInputElement), (e.target as HTMLInputElement).checked)}"
role="switch">
</div>
</div>
</div>
<label for="elem">${this.label}</label>
- </div>
+ </span>
`;
case InputType.SELECT:
const classes = {
@@ -291,7 +367,7 @@ export class OrInput extends LitElement {
?required="${this.required}"
?readonly="${this.readonly}"
?disabled="${this.disabled}"
- @MDCSelect:change="${(e: MDCSelectEvent) => this.onValueChange(e.detail.index === -1 ? undefined : e.detail.value)}">
+ @MDCSelect:change="${(e: MDCSelectEvent) => this.onValueChange(undefined, e.detail.index === -1 ? undefined : e.detail.value)}">
<or-icon class="mdc-select__dropdown-icon" icon="menu-down"></or-icon>
<div id="elem" class="mdc-select__selected-text" role="button" aria-haspopup="listbox" aria-controls="component-helper-text" aria-describedby="component-helper-text" aria-labelledby="component-label component"></div>
<div id="menu" class="mdc-select__menu mdc-menu mdc-menu-surface" role="listbox">
@@ -317,7 +393,7 @@ export class OrInput extends LitElement {
<button id="component" class="mdc-icon-button ${this.value ? "mdc-icon-button--on" : ""}"
?readonly="${this.readonly}"
?disabled="${this.disabled}"
- @MDCIconButtonToggle:change="${(evt: MDCIconButtonToggleEventDetail) => this.onValueChange(evt.isOn)}">
+ @MDCIconButtonToggle:change="${(evt: MDCIconButtonToggleEventDetail) => this.onValueChange(undefined, evt.isOn)}">
${this.icon ? html`<or-icon class="mdc-icon-button__icon" aria-hidden="true" icon="${this.icon}"></or-icon>` : ``}
${this.iconOn ? html`<or-icon class="mdc-icon-button__icon mdc-icon-button__icon--on" aria-hidden="true" icon="${this.iconOn}"></or-icon>` : ``}
</button>
@@ -342,7 +418,7 @@ export class OrInput extends LitElement {
<button id="component" class="${classMap(classes)}"
?readonly="${this.readonly}"
?disabled="${this.disabled}"
- @onmousedown="${() => {if (isMomentary) this.onValueChange(true)}}" @onmouseup="${() => isMomentary ? this.onValueChange(false) : this.onValueChange(true)}">
+ @onmousedown="${() => {if (isMomentary) this.onValueChange(undefined, true)}}" @onmouseup="${() => isMomentary ? this.onValueChange(undefined, false) : this.onValueChange(undefined, true)}">
${!isIconButton ? html`<div class="mdc-button__ripple"></div>` : ``}
${this.icon ? html`<or-icon class="${isIconButton ? "" : this.action ? "mdc-fab__icon" : "mdc-button__icon"}" aria-hidden="true" icon="${this.icon}"></or-icon>` : ``}
${this.label ? html`<span class="${this.action ? "mdc-fab__label" : "mdc-button__label"}">${this.label}</span>` : ``}
@@ -358,7 +434,7 @@ export class OrInput extends LitElement {
?checked="${this.value}"
?required="${this.required}"
?disabled="${this.disabled || this.readonly}"
- @change="${(e: Event) => this.onValueChange((e.target as HTMLInputElement).checked)}"
+ @change="${(e: Event) => this.onValueChange((e.target as HTMLInputElement), (e.target as HTMLInputElement).value)}"
class="mdc-checkbox__native-control" id="elem"/>
<div class="mdc-checkbox__background">
<svg class="mdc-checkbox__checkmark" viewBox="0 0 24 24">
@@ -430,7 +506,7 @@ export class OrInput extends LitElement {
?required="${this.required}"
?readonly="${this.readonly}"
?disabled="${this.disabled}"
- @change="${(e: Event) => this.onValueChange((e.target as HTMLTextAreaElement).value)}"
+ @change="${(e: Event) => this.onValueChange((e.target as HTMLTextAreaElement), (e.target as HTMLTextAreaElement).value)}"
minlength="${ifDefined(this.minLength)}"
maxlength="${ifDefined(this.maxLength)}"
rows="${this.rows ? this.rows : 5}"
@@ -442,7 +518,7 @@ export class OrInput extends LitElement {
?required="${this.required}"
?readonly="${this.readonly}"
?disabled="${this.disabled}"
- @change="${(e: Event) => this.onValueChange((e.target as HTMLInputElement).value)}"
+ @change="${(e: Event) => this.onValueChange((e.target as HTMLInputElement), (e.target as HTMLInputElement).value)}"
.value="${val}"
min="${ifDefined(this.min)}"
max="${ifDefined(this.max)}"
@@ -523,7 +599,9 @@ export class OrInput extends LitElement {
this._mdcComponent = new MDCSwitch(component);
break;
default:
- this._mdcComponent = new MDCTextField(component);
+ const textField = new MDCTextField(component);
+ textField.useNativeValidation = false;
+ this._mdcComponent = textField;
break;
}
}
@@ -558,7 +636,19 @@ export class OrInput extends LitElement {
`;
}
- protected onValueChange(newValue: any | undefined) {
+ protected onValueChange(elem: HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement | undefined, newValue: any | undefined) {
+
+ let valid = true;
+
+ if (elem && this._mdcComponent) {
+
+ // trigger validation
+ valid = elem.checkValidity();
+ if (this._mdcComponent instanceof MDCTextField) {
+ this._mdcComponent.valid = valid;
+ }
+ }
+
const previousValue = this.value;
if (newValue === "null") {
diff --git a/ui/component/or-input/src/style.ts b/ui/component/or-input/src/style.ts
deleted file mode 100644
index d0e3f90ac..000000000
--- a/ui/component/or-input/src/style.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import {css, unsafeCSS} from "lit-element";
-import {DefaultColor1, DefaultColor4} from "@openremote/core";
-
-// TODO this is temp work, should be replaced with material design components / styling
-// language=CSS
-export const orInputStyle = css`
-
- :host {
- display: inline-block;
- --internal-or-input-color: var(--or-input-color, var(--or-app-color4, ${unsafeCSS(DefaultColor4)}));
- --internal-or-input-text-color: var(--or-input-text-color, var(--or-app-color1, ${unsafeCSS(DefaultColor1)}));
-
- --mdc-theme-primary: var(--internal-or-input-color);
- --mdc-theme-on-primary: var(--internal-or-input-text-color);
- --mdc-theme-secondary: var(--internal-or-input-color);
- }
-
- .or-input--rounded {
- border-radius: 50% !important;
- }
-
- .mdc-text-field--dense .mdc-text-field__input {
- white-space: nowrap;
- }
-
- /* MDC TEXT FIELD AND SELECT DON'T USE THEME VARS */
- .mdc-text-field--focused:not(.mdc-text-field--disabled) .mdc-floating-label {
- color: var(--mdc-theme-primary);
- }
- .mdc-text-field--focused .mdc-text-field__input:required ~ .mdc-floating-label::after,
- .mdc-text-field--focused .mdc-text-field__input:required ~ .mdc-notched-outline .mdc-floating-label::after {
- color: var(--mdc-theme-primary);
- }
-
- .mdc-select:not(.mdc-select--disabled).mdc-select--focused .mdc-floating-label {
- color: var(--mdc-theme-primary);
- }
-
- .mdc-text-field, .mdc-text-field-helper-line {
- width: inherit;
- }
-
- .mdc-text-field--dense:not(.mdc-text-field--no-label):not(.mdc-text-field--outlined) {
- height: 52px;
- }
-
- .mdc-text-field--dense.mdc-text-field--no-label {
- height: 40px;
- }
-
- .mdc-switch {
- margin: 18px;
- }
-
- .mdc-select__dropdown-icon {
- background: none;
- }
-
- .mdc-select--focused .mdc-select__dropdown-icon {
- --or-icon-fill: var(--internal-or-input-color);
- }
-
- .mdc-icon-button {
- --or-icon-fill: var(--mdc-theme-primary);
- }
-
- .mdc-icon-button {
- padding: 0;
- }
-`;
diff --git a/ui/component/or-mwc-components/src/or-mwc-menu.ts b/ui/component/or-mwc-components/src/or-mwc-menu.ts
index 2bc00b74b..b6ce11acb 100644
--- a/ui/component/or-mwc-components/src/or-mwc-menu.ts
+++ b/ui/component/or-mwc-components/src/or-mwc-menu.ts
@@ -1,15 +1,21 @@
-import {css, customElement, html, LitElement, property, query, TemplateResult, unsafeCSS, PropertyValues} from "lit-element";
-
-import {MDCMenu, MDCMenuItemComponentEventDetail} from "@material/menu";
+import {
+ css,
+ customElement,
+ html,
+ LitElement,
+ property,
+ PropertyValues,
+ query,
+ TemplateResult,
+ unsafeCSS
+} from "lit-element";
+
+import {MDCMenu} from "@material/menu";
const listStyle = require("!!raw-loader!@material/list/dist/mdc.list.css");
const menuSurfaceStyle = require("!!raw-loader!@material/menu-surface/dist/mdc.menu-surface.css");
const menuStyle = require("!!raw-loader!@material/menu/dist/mdc.menu.css");
-export interface Menu {
- items: (MenuItem | MenuGroup | null)[];
-}
-
export interface MenuGroup {
icon?: string;
items: (MenuItem | null)[];
@@ -39,6 +45,30 @@ declare global {
}
}
+export function getContentWithMenuTemplate(content: TemplateResult, menuItems: (MenuItem | MenuGroup | null)[], selectedValue: string | undefined, valueChangedCallback: (v: string) => void): TemplateResult {
+
+ const openMenu = (evt: Event) => {
+ if (!menuItems) {
+ return;
+ }
+
+ ((evt.currentTarget as Element).parentElement!.lastElementChild as OrMwcMenu).open();
+ };
+
+ return html`
+ <span>
+ <span @click="${openMenu}">${content}</span>
+ ${menuItems ? html`<or-mwc-menu @or-mwc-menu-changed="${(evt: OrMwcMenuChangedEvent) => valueChangedCallback(evt.detail)}" .value="${selectedValue}" .menuItems="${menuItems}" id="menu"></or-mwc-menu>` : ``}
+ </span>
+ `;
+}
+
+// language=CSS
+const style = css`
+ :host {
+ white-space: nowrap;
+ }
+`;
@customElement("or-mwc-menu")
export class OrMwcMenu extends LitElement {
@@ -47,12 +77,13 @@ export class OrMwcMenu extends LitElement {
return [
css`${unsafeCSS(listStyle)}`,
css`${unsafeCSS(menuStyle)}`,
- css`${unsafeCSS(menuSurfaceStyle)}`
+ css`${unsafeCSS(menuSurfaceStyle)}`,
+ style
];
}
- @property({type: Object})
- public menu?: Menu;
+ @property({type: Array})
+ public menuItems?: (MenuItem | MenuGroup | null)[];
@property({type: String})
public value?: string;
@@ -84,7 +115,7 @@ export class OrMwcMenu extends LitElement {
protected render() {
- if (!this.menu || !this.menu.items) {
+ if (!this.menuItems || this.menuItems.length === 0) {
return html``;
}
@@ -92,7 +123,7 @@ export class OrMwcMenu extends LitElement {
<div id="wrapper" class="mdc-menu-surface--anchor">
<div class="mdc-menu mdc-menu-surface" id="menu">
<ul class="mdc-list" role="menu" aria-hidden="true" aria-orientation="vertical" tabindex="-1">
- ${this.getItemsTemplate(this.menu.items)}
+ ${this.getItemsTemplate(this.menuItems)}
</ul>
</div>
</div>
@@ -109,7 +140,7 @@ export class OrMwcMenu extends LitElement {
return html`
<li>
<ul class="mdc-menu__selection-group">
- ${this.getItemsTemplate((item as Menu).items, (item as MenuGroup).icon)}
+ ${this.getItemsTemplate((item as MenuGroup).items, (item as MenuGroup).icon)}
</ul>
</li>
`;
@@ -128,11 +159,13 @@ export class OrMwcMenu extends LitElement {
protected firstUpdated(_changedProperties: PropertyValues): void {
super.firstUpdated(_changedProperties);
- this._mdcComponent = new MDCMenu(this._mdcElem);
- this._mdcComponent!.quickOpen = true;
- const elem = this.anchorElem || this._wrapperElem;
- // This doesn't work
- //this._mdcComponent.setAnchorElement(elem);
+ if (this._mdcElem) {
+ this._mdcComponent = new MDCMenu(this._mdcElem);
+ this._mdcComponent!.quickOpen = true;
+ const elem = this.anchorElem || this._wrapperElem;
+ // This doesn't work
+ //this._mdcComponent.setAnchorElement(elem);
+ }
}
protected updated(_changedProperties: PropertyValues): void {
diff --git a/ui/component/or-rules-editor/src/index.ts b/ui/component/or-rules-editor/src/index.ts
deleted file mode 100644
index 38ea625b5..000000000
--- a/ui/component/or-rules-editor/src/index.ts
+++ /dev/null
@@ -1,1068 +0,0 @@
-import {customElement, html, css, unsafeCSS, LitElement, property, TemplateResult, query} from "lit-element";
-import {DefaultColor1, DefaultColor2, DefaultColor5, DefaultColor3, DefaultBoxShadow, DefaultColor4, DefaultColor6, DefaultDisabledOpacity} from "@openremote/core";
-import i18next from "i18next";
-import "@openremote/or-select";
-import "@openremote/or-icon";
-import {
- AssetDescriptor,
- AttributeDescriptor,
- AttributeValueDescriptor,
- AssetQueryOperator as AQO,
- JsonRulesetDefinition,
- LogicGroup,
- MetaItemDescriptor,
- MetaItemType,
- AssetQuery,
- JsonRule,
- RuleActionTarget,
- RuleActionUnion,
- RuleCondition,
- RulesetLang,
- TenantRuleset,
- ValuePredicateUnion,
- ValueType,
- Attribute
-} from "@openremote/model";
-import manager, {AssetModelUtil} from "@openremote/core";
-import {Util} from "@openremote/core";
-import "@openremote/or-translate";
-import {translate} from "@openremote/or-translate";
-import "./or-rule-list";
-import "./or-rule-when";
-import "./or-rule-then-otherwise";
-import "./or-rule-header";
-import "@openremote/or-panel";
-import {OrRulesList} from "./or-rule-list";
-import {Menu, OrMwcMenu, OrMwcMenuChangedEvent} from "@openremote/or-mwc-components/dist/or-mwc-menu";
-import {InputType, OrInput} from "@openremote/or-input";
-
-export const enum ConditionType {
- ASSET_QUERY = "assetQuery",
- DATE_TIME = "datetime",
- TIMER = "timer"
-}
-
-export const enum ActionType {
- WAIT = "wait",
- NOTIFICATION = "notification",
- ATTRIBUTE = "attribute"
-}
-
-export enum AssetQueryOperator {
- VALUE_EMPTY = "empty",
- VALUE_NOT_EMPTY = "notEmpty",
- EQUALS = "equals",
- NOT_EQUALS = "notEquals",
- GREATER_THAN = "greaterThan",
- GREATER_EQUALS = "greaterEquals",
- LESS_THAN = "lessThan",
- LESS_EQUALS = "lessEquals",
- BETWEEN = "between",
- NOT_BETWEEN = "notBetween",
- CONTAINS = "contains",
- NOT_CONTAINS = "notContains",
- STARTS_WITH = "startsWith",
- NOT_STARTS_WITH = "notStartsWith",
- ENDS_WITH = "endsWith",
- NOT_ENDS_WITH = "notEndsWith",
- CONTAINS_KEY = "containsKey",
- NOT_CONTAINS_KEY = "notContainsKey",
- INDEX_CONTAINS = "indexContains",
- NOT_INDEX_CONTAINS = "notIndexContains",
- LENGTH_EQUALS = "lengthEquals",
- NOT_LENGTH_EQUALS = "notLengthEquals",
- LENGTH_GREATER_THAN = "lengthGreaterThan",
- LENGTH_LESS_THAN = "lengthLessThan",
- IS_TRUE = "true",
- IS_FALSE = "false",
- WITHIN_RADIUS = "withinRadius",
- OUTSIDE_RADIUS = "outsideRadius",
- WITHIN_RECTANGLE = "withinRectangle",
- OUTSIDE_RECTANGLE = "outsideRectangle"
-}
-
-export interface AssetTypeAttributeName {
- assetType: string;
- attributeName: string;
-}
-
-export interface RulesConfig {
- controls?: {
- whenReadonly?: boolean;
- thenReadonly?: boolean;
- headerReadonly?: boolean;
- allowedConditionTypes?: ConditionType[];
- allowedActionTypes?: ActionType[];
- allowedAssetQueryOperators?: Map<AssetTypeAttributeName | AttributeDescriptor | AttributeValueDescriptor | ValueType, AssetQueryOperator[]>;
- hideActionTypeOptions?: boolean;
- hideActionTargetOptions?: boolean;
- hideActionUpdateOptions?: boolean;
- hideConditionTypeOptions?: boolean;
- hideThenAddAction?: boolean;
- hideWhenAddCondition?: boolean;
- hideWhenAddAttribute?: boolean;
- hideWhenAddGroup?: boolean;
- };
- inputProvider?: (assetType: string | undefined, attribute: Attribute | undefined, attributeDescriptor: AttributeDescriptor | undefined, valueDescriptor: AttributeValueDescriptor | undefined, valueChangeNotifier: (value: any | undefined) => void, readonly: boolean | undefined, disabled: boolean | undefined) => ((value: any) => TemplateResult) | undefined;
- descriptors?: {
- all?: RulesDescriptorSection;
- when?: RulesDescriptorSection;
- action?: RulesDescriptorSection;
- };
- templates?: {
- rule?: JsonRule;
- rulesetName?: string;
- whenGroup?: LogicGroup<RuleCondition>;
- whenCondition?: RuleCondition;
- whenAssetQuery?: AssetQuery;
- then?: RuleActionUnion;
- otherwise?: RuleActionUnion;
- };
-}
-
-export interface RulesDescriptorSection {
- includeAssets?: string[];
- excludeAssets?: string[];
- assets?: { [assetType: string]: RulesConfigAsset };
- attributeDescriptors?: {[attributeName: string]: RulesConfigAttribute };
-}
-
-export interface RulesConfigAsset {
- includeAttributes?: string[];
- excludeAttributes?: string[];
- name?: string;
- icon?: string;
- attributeDescriptors?: {[attributeName: string]: RulesConfigAttribute };
-}
-
-export interface RulesConfigAttribute {
- icon?: string;
- valueDescriptor?: RulesConfigAttribute;
- initialValue?: any;
- allowedValues?: any[];
- allowedMin?: any;
- allowedMax?: any;
-}
-
-export interface RulesConfigAttributeValue {
- name?: string;
- icon?: string;
- valueType?: ValueType;
-}
-
-export interface RulesetNode {
- ruleset: TenantRuleset;
- selected: boolean;
-}
-
-export interface RequestEventDetail<T> {
- allow: boolean,
- detail: T
-}
-
-function getAssetDescriptorFromSection(assetTpe: string, config: RulesConfig | undefined, useActionConfig: boolean) {
- if (!config || !config.descriptors) {
- return;
- }
-
- const section = useActionConfig ? config.descriptors.action : config.descriptors.when;
- const allSection = config.descriptors.all;
-
- const descriptor = section && section.assets ? section.assets[assetTpe] : undefined;
- if (descriptor) {
- return descriptor;
- }
-
- return allSection && allSection.assets ? allSection.assets[assetTpe] : undefined;
-}
-
-export function getDescriptorValueType(descriptor?: AttributeDescriptor) {
- if (!descriptor || !descriptor.valueDescriptor) {
- return;
- }
-
- return descriptor.valueDescriptor.valueType;
-}
-
-export function getAssetTypeFromQuery(query?: AssetQuery) {
- return query && query.types && query.types.length > 0 && query.types[0] ? query.types[0].value : undefined;
-}
-
-export function getAssetIdsFromQuery(query?: AssetQuery) {
- return query && query.ids ? [...query.ids] : undefined;
-}
-
-export function getAttributeNames(descriptor?: AssetDescriptor) {
- let attributes: string[] = [];
-
- if (descriptor && descriptor.attributeDescriptors) {
- attributes = descriptor.attributeDescriptors.map((ad) => ad.attributeName!);
- }
-
- return attributes;
-}
-
-export function getAssetDescriptors(config: RulesConfig | undefined, useActionConfig: boolean) {
- const assetDescriptors: AssetDescriptor[] = AssetModelUtil.getAssetDescriptors();
- let allowedAssetTypes: string[] = [];
- let excludedAssetTypes: string[] = [];
-
- if (!config || !config.descriptors) {
- return assetDescriptors;
- }
-
- const section = useActionConfig ? config.descriptors.action : config.descriptors.when;
-
- if (section && section.includeAssets) {
- allowedAssetTypes = [...section.includeAssets];
- }
-
- if (config.descriptors.all && config.descriptors.all.includeAssets) {
- allowedAssetTypes = allowedAssetTypes.concat(config.descriptors.all.includeAssets);
- }
-
- if (section && section.excludeAssets) {
- excludedAssetTypes = [...section.excludeAssets];
- }
-
- if (config.descriptors.all && config.descriptors.all.excludeAssets) {
- excludedAssetTypes = excludedAssetTypes.concat(config.descriptors.all.excludeAssets);
- }
-
- return assetDescriptors.filter((ad) => {
- if (allowedAssetTypes.length > 0 && allowedAssetTypes.indexOf(ad.type!) < 0) {
- return false;
- }
- return excludedAssetTypes.indexOf(ad.type!) < 0;
-
- }).map((ad) => {
- // Amalgamate matching descriptor from config if defined
- const configDescriptor = getAssetDescriptorFromSection(ad.type!, config, useActionConfig);
- if (!configDescriptor) {
- return ad;
- }
-
- const modifiedDescriptor: AssetDescriptor = {
- name: ad.name,
- type: ad.type,
- icon: ad.icon,
- attributeDescriptors: ad.attributeDescriptors ? [...ad.attributeDescriptors] : undefined
- };
-
- if (configDescriptor.icon) {
- modifiedDescriptor.icon = configDescriptor.icon;
- }
- if (configDescriptor.name) {
- modifiedDescriptor.name = configDescriptor.name;
- }
-
- // Remove any excluded attributes
- if (modifiedDescriptor.attributeDescriptors) {
- const inc = configDescriptor.includeAttributes !== undefined ? configDescriptor.includeAttributes : undefined;
- const exc = configDescriptor.excludeAttributes !== undefined ? configDescriptor.excludeAttributes : undefined;
-
- if (inc || exc) {
- modifiedDescriptor.attributeDescriptors = modifiedDescriptor.attributeDescriptors.filter((mad) => {
- if (exc && exc.indexOf(mad.attributeName!) >= 0) {
- return false;
- }
- if (inc && inc.indexOf(mad.attributeName!) < 0) {
- return false;
- }
- return true;
- });
- }
-
- // Override any attribute descriptors
- if (configDescriptor.attributeDescriptors) {
- modifiedDescriptor.attributeDescriptors.map((attributeDescriptor) => {
- let configAttributeDescriptor: RulesConfigAttribute | undefined = configDescriptor.attributeDescriptors![attributeDescriptor.attributeName!];
- if (!configAttributeDescriptor) {
- configAttributeDescriptor = section && section.attributeDescriptors ? section.attributeDescriptors[attributeDescriptor.attributeName!] : undefined;
- }
- if (!configAttributeDescriptor) {
- configAttributeDescriptor = config.descriptors!.all && config.descriptors!.all.attributeDescriptors ? config.descriptors!.all.attributeDescriptors[attributeDescriptor.attributeName!] : undefined;
- }
- if (configAttributeDescriptor) {
- let metaItemDescriptors = attributeDescriptor.metaItemDescriptors;
- if (!metaItemDescriptors) {
- attributeDescriptor.metaItemDescriptors = [];
- metaItemDescriptors = attributeDescriptor.metaItemDescriptors;
- }
-
- if (configAttributeDescriptor.allowedValues) {
- addOrReplaceMetaItemDescriptor(metaItemDescriptors, AssetModelUtil.getMetaItemDescriptorInitialValue(MetaItemType.ALLOWED_VALUES, configAttributeDescriptor.allowedValues));
- }
- if (configAttributeDescriptor.allowedMin) {
- addOrReplaceMetaItemDescriptor(metaItemDescriptors, AssetModelUtil.getMetaItemDescriptorInitialValue(MetaItemType.RANGE_MIN, configAttributeDescriptor.allowedMin));
- }
- if (configAttributeDescriptor.allowedMax) {
- addOrReplaceMetaItemDescriptor(metaItemDescriptors, AssetModelUtil.getMetaItemDescriptorInitialValue(MetaItemType.RANGE_MAX, configAttributeDescriptor.allowedMax));
- }
-
- return {
- attributeName: attributeDescriptor.attributeName,
- valueDescriptor: configAttributeDescriptor.valueDescriptor ? configAttributeDescriptor.valueDescriptor : attributeDescriptor.valueDescriptor,
- initialValue: configAttributeDescriptor.initialValue ? configAttributeDescriptor.initialValue : attributeDescriptor.initialValue,
- metaItemDescriptors: attributeDescriptor.metaItemDescriptors
- };
- }
-
- return attributeDescriptor;
- });
- }
- }
- return modifiedDescriptor;
- });
-}
-
-export function getButtonWithMenuTemplate(menu: Menu, icon: string, value: string | undefined, valueChangedCallback: (v: string) => void): TemplateResult {
-
- const openMenu = (evt: Event) => {
- if (!menu) {
- return;
- }
-
- ((evt.currentTarget as OrInput).parentElement!.lastElementChild as OrMwcMenu).open();
- };
-
- return html`
- <div style="display: table-cell; vertical-align: middle;">
- <or-input type="${InputType.BUTTON}" .icon="${icon}" @click="${openMenu}"></or-input>
- ${menu ? html`<or-mwc-menu @or-mwc-menu-changed="${(evt: OrMwcMenuChangedEvent) => valueChangedCallback(evt.detail)}" .value="${value}" .menu="${menu}" id="menu"></or-mwc-menu>` : ``}
- </div>
- `;
-}
-
-function addOrReplaceMetaItemDescriptor(metaItemDescriptors: MetaItemDescriptor[], metaItemDescriptor: MetaItemDescriptor) {
- const index = metaItemDescriptors.findIndex((mid) => mid.urn === metaItemDescriptor.urn);
- if (index >= 0) {
- metaItemDescriptors.splice(index, 1);
-
- }
- metaItemDescriptors.push(metaItemDescriptor);
-}
-
-export class OrRulesEditorRuleChangedEvent extends CustomEvent<void> {
-
- public static readonly NAME = "or-rules-editor-rule-changed";
-
- constructor() {
- super(OrRulesEditorRuleChangedEvent.NAME, {
- bubbles: true,
- composed: true
- });
- }
-}
-
-export class OrRulesEditorRuleInvalidEvent extends CustomEvent<void> {
-
- public static readonly NAME = "or-rules-editor-rule-invalid";
-
- constructor() {
- super(OrRulesEditorRuleInvalidEvent.NAME, {
- bubbles: true,
- composed: true
- });
- }
-}
-
-export class OrRulesEditorRuleUnsupportedEvent extends CustomEvent<void> {
-
- public static readonly NAME = "or-rules-editor-rule-unsupported";
-
- constructor() {
- super(OrRulesEditorRuleUnsupportedEvent.NAME, {
- bubbles: true,
- composed: true
- });
- }
-}
-
-export class OrRulesEditorRequestSelectEvent extends CustomEvent<RequestEventDetail<TenantRuleset[]>> {
-
- public static readonly NAME = "or-rules-editor-request-select";
-
- constructor(request: TenantRuleset[]) {
- super(OrRulesEditorRequestSelectEvent.NAME, {
- bubbles: true,
- composed: true,
- detail: {
- allow: true,
- detail: request
- }
- });
- }
-}
-
-export class OrRulesEditorRequestAddEvent extends CustomEvent<void> {
-
- public static readonly NAME = "or-rules-editor-request-add";
-
- constructor() {
- super(OrRulesEditorRequestAddEvent.NAME, {
- bubbles: true,
- composed: true
- });
- }
-}
-
-export class OrRulesEditorRequestDeleteEvent extends CustomEvent<TenantRuleset[]> {
-
- public static readonly NAME = "or-rules-editor-request-delete";
-
- constructor(request: TenantRuleset[]) {
- super(OrRulesEditorRequestDeleteEvent.NAME, {
- bubbles: true,
- composed: true,
- detail: request
- });
- }
-}
-
-export class OrRulesEditorRequestCopyEvent extends CustomEvent<TenantRuleset> {
-
- public static readonly NAME = "or-rules-editor-request-copy";
-
- constructor(request: TenantRuleset) {
- super(OrRulesEditorRequestCopyEvent.NAME, {
- bubbles: true,
- composed: true,
- detail: request
- });
- }
-}
-
-export class OrRulesEditorRequestSaveEvent extends CustomEvent<TenantRuleset> {
-
- public static readonly NAME = "or-rules-editor-request-save";
-
- constructor(request: TenantRuleset) {
- super(OrRulesEditorRequestSaveEvent.NAME, {
- bubbles: true,
- composed: true,
- detail: request
- });
- }
-}
-
-export class OrRulesEditorSelectionChangedEvent extends CustomEvent<TenantRuleset[]> {
-
- public static readonly NAME = "or-rules-editor-selection-changed";
-
- constructor(nodes: TenantRuleset[]) {
- super(OrRulesEditorSelectionChangedEvent.NAME, {
- bubbles: true,
- composed: true,
- detail: nodes
- });
- }
-}
-
-declare global {
- export interface HTMLElementEventMap {
- [OrRulesEditorRuleInvalidEvent.NAME]: OrRulesEditorRuleInvalidEvent;
- [OrRulesEditorRuleUnsupportedEvent.NAME]: OrRulesEditorRuleUnsupportedEvent;
- [OrRulesEditorRequestSelectEvent.NAME]: OrRulesEditorRequestSelectEvent;
- [OrRulesEditorRequestAddEvent.NAME]: OrRulesEditorRequestAddEvent;
- [OrRulesEditorRequestDeleteEvent.NAME]: OrRulesEditorRequestDeleteEvent;
- [OrRulesEditorRequestCopyEvent.NAME]: OrRulesEditorRequestCopyEvent;
- [OrRulesEditorRequestSaveEvent.NAME]: OrRulesEditorRequestSaveEvent;
- [OrRulesEditorRuleChangedEvent.NAME]: OrRulesEditorRuleChangedEvent;
- [OrRulesEditorSelectionChangedEvent.NAME]: OrRulesEditorSelectionChangedEvent;
- }
-}
-
-// language=CSS
-export const style = css`
-
- :host {
- display: flex;
- height: 100%;
- width: 100%;
-
- --internal-or-rules-editor-background-color: var(--or-rules-editor-background-color, var(--or-app-color2, ${unsafeCSS(DefaultColor2)}));
- --internal-or-rules-editor-text-color: var(--or-rules-editor-text-color, inherit);
- --internal-or-rules-editor-button-color: var(--or-rules-editor-button-color, var(--or-app-color4, ${unsafeCSS(DefaultColor4)}));
- --internal-or-rules-editor-invalid-color: var(--or-rules-editor-invalid-color, var(--or-app-color6, ${unsafeCSS(DefaultColor6)}));
- --internal-or-rules-editor-panel-color: var(--or-rules-editor-panel-color, var(--or-app-color1, ${unsafeCSS(DefaultColor1)}));
- --internal-or-rules-editor-line-color: var(--or-rules-editor-line-color, var(--or-app-color5, ${unsafeCSS(DefaultColor5)}));
-
- --internal-or-rules-editor-list-selected-color: var(--or-rules-editor-list-selected-color, var(--or-app-color2, ${unsafeCSS(DefaultColor2)}));
- --internal-or-rules-editor-list-text-color: var(--or-rules-editor-list-text-color, var(--or-app-color3, ${unsafeCSS(DefaultColor3)}));
- --internal-or-rules-editor-list-text-size: var(--or-rules-editor-list-text-size, 15px);
-
- --internal-or-rules-editor-list-button-size: var(--or-rules-editor-list-button-size, 24px);
-
- --internal-or-rules-editor-header-background-color: var(--or-rules-editor-header-background-color, var(--or-app-color1, ${unsafeCSS(DefaultColor1)}));
- --internal-or-rules-editor-header-height: var(--or-rules-editor-header-height, 80px);
-
- --or-panel-background-color: var(--internal-or-rules-editor-panel-color);
- }
-
- .shadow {
- -webkit-box-shadow: ${unsafeCSS(DefaultBoxShadow)};
- -moz-box-shadow: ${unsafeCSS(DefaultBoxShadow)};
- box-shadow: ${unsafeCSS(DefaultBoxShadow)};
- }
-
- #rule-list-container {
- min-width: 300px;
- width: 300px;
- z-index: 2;
- display: flex;
- flex-direction: column;
- background-color: var(--internal-or-rules-editor-panel-color);
- color: var(--internal-or-rules-editor-list-text-color);
-
- }
-
- .rule-container {
- display: flex;
- flex-direction: column;
- flex-grow: 1;
- }
-
- or-rule-header {
- min-height: var(--internal-or-rules-editor-header-height);
- height: var(--internal-or-rules-editor-header-height);
- }
-
- .rule-editor-panel {
- display: flex;
- flex-grow: 1;
- background-color: var(--internal-or-rules-editor-background-color);
- }
-
- .section-container {
- flex: 1 0 0px;
- }
-
- .msg {
- display: flex;
- justify-content: center;
- align-items: center;
- flex-direction: column;
- text-align: center;
- margin: auto;
- }
-
- @media only screen
- and (min-device-width : 768px)
- and (max-device-width : 1024px) {
- side-menu {
- min-width: 150px;
- width: 150px;
- }
- }
-`;
-
-@customElement("or-rules-editor")
-class OrRulesEditor extends translate(i18next)(LitElement) {
-
- public static DEFAULT_RULESET_NAME = "New rule";
-
- static get styles() {
- return [
- style
- ];
- }
-
- public config?: RulesConfig;
-
- @property({type: String})
- public realm?: string;
-
- @property({type: Array})
- public selectedIds?: number[];
-
- @property({type: Boolean, attribute: false})
- private _isValidRule?: boolean;
-
- @query("#rules-list")
- private _rulesList!: OrRulesList;
-
- private _activeRuleset?: TenantRuleset;
- private _activeRules?: JsonRule[];
- private _activeModified: boolean = false;
- private _whenAssetDescriptors?: AssetDescriptor[];
- private _actionAssetDescriptors?: AssetDescriptor[];
- private _saveInProgress = false;
-
- private set activeRuleset(ruleset: TenantRuleset | undefined) {
- this._activeRuleset = ruleset;
- this._activeRules = undefined;
- this._activeModified = !!(ruleset && !ruleset.id);
-
- if (ruleset && ruleset.rules) {
- const rules = JSON.parse(ruleset.rules) as JsonRulesetDefinition;
- this._activeRules = rules.rules;
- }
-
- this.requestUpdate();
- }
-
- private get activeRuleset() {
- return this._activeRuleset;
- }
-
- private get activeRule() {
- return this._activeRules && this._activeRules.length > 0 ? this._activeRules[0] : undefined;
- }
-
- constructor() {
- super();
-
- this.addEventListener(OrRulesEditorRuleChangedEvent.NAME, this._onRuleChanged);
- this.addEventListener(OrRulesEditorRequestSelectEvent.NAME, this._onRequestSelect);
- this.addEventListener(OrRulesEditorRequestAddEvent.NAME, this._onRequestAdd);
- this.addEventListener(OrRulesEditorRequestDeleteEvent.NAME, this._onRequestDelete);
- this.addEventListener(OrRulesEditorRequestCopyEvent.NAME, this._onRequestCopy);
- this.addEventListener(OrRulesEditorRequestSaveEvent.NAME, this._onRequestSave);
- this.addEventListener(OrRulesEditorSelectionChangedEvent.NAME, this._onRuleSelectionChanged);
- }
-
- protected ruleEditorPanelTemplate(rule: JsonRule) {
- const targetTypeMap = this.getTargetTypeMap();
- const whenDescriptors = this.getAssetDescriptors(false);
- const actionDescriptors = this.getAssetDescriptors(true);
-
- return html`
- <div class="section-container">
- <or-rule-when .rule="${rule}" .config="${this.config}" .assetDescriptors="${whenDescriptors}" ?readonly="${this.isReadonly("when")}"></or-rule-when>
- </div>
-
- <div class="section-container">
- <or-rule-then-otherwise .rule="${rule}" .config="${this.config}" .targetTypeMap="${targetTypeMap}" .assetDescriptors="${actionDescriptors}" ?readonly="${this.isReadonly("then")}"></or-rule-then-otherwise>
- </div>
- `;
- }
-
- protected render() {
-
- return html`
- <div id="rule-list-container" class="shadow">
- <or-rule-list id="rules-list" .realm="${this.realm}" .selectedIds="${this.selectedIds}"></or-rule-list>
- </div>
- ${this.activeRule ? html`
- <div class="rule-container">
- <or-rule-header class="shadow" .readonly="${this.isReadonly("header")}" .ruleset="${this.activeRuleset}" .rule="${this.activeRule}" .saveEnabled="${!this._saveInProgress && this._isValidRule && this._activeModified}"></or-rule-header>
- <div class="rule-editor-panel">
- ${this.ruleEditorPanelTemplate(this.activeRule)}
- </div>
- </div>
- ` : html`
- <div class="msg"><or-translate value="noRuleSelected"></or-translate></div>
- `}
- `;
- }
-
- protected isReadonly(sectionName: string) {
-
- if (!manager.hasRole("write:rules")) {
- return true;
- }
- if (!this.config || !this.config.controls) {
- return false;
- }
-
- if (sectionName === "when") {
- return this.config.controls.whenReadonly === true;
- }
-
- if (sectionName === "then") {
- return this.config.controls.thenReadonly === true;
- }
-
- if (sectionName === "header") {
- return this.config.controls.headerReadonly === true;
- }
- }
-
- protected _onRuleChanged() {
- this._activeModified = true;
- let isValid = false;
- const rule = this.activeRule;
-
- if (rule) {
- isValid = this._validateRuleset();
- }
-
- this._isValidRule = isValid;
- this.requestUpdate();
- }
-
- protected _validateRuleset(): boolean {
-
- const ruleset = this.activeRuleset;
- const rule = this.activeRule;
-
- if (!ruleset || !rule) {
- return false;
- }
-
- if (!ruleset.name || ruleset.name.length < 3 || ruleset.name.length > 255) {
- return false;
- }
-
- if (!rule.when) {
- return false;
- }
-
- if (!rule.then || rule.then.length === 0) {
- return false;
- }
-
- if (!this.validateConditionGroup(rule.when)) {
- return false;
- }
-
- if (!this.validateRuleActions(rule, rule.then)) {
- return false;
- }
-
- // TODO: Validate other rule sections
- return true;
- }
-
- protected validateConditionGroup(group: LogicGroup<RuleCondition>): boolean {
- if ((!group.items || group.items.length === 0) && (!group.groups || group.groups.length === 0)) {
- return false;
- }
-
- if (group.items) {
- for (const condition of group.items) {
- if (!condition.assets && !condition.datetime && !condition.timer) {
- return false;
- }
-
- if (condition.assets && !this.validateAssetQuery(condition.assets, true, false)) {
- return false;
- }
-
- if (condition.datetime && !this.validateValuePredicate(condition.datetime)) {
- return false;
- }
-
- if (condition.timer && !Util.isTimeDuration(condition.timer)) {
- return false;
- }
- }
- }
-
- if (group.groups) {
- for (const childGroup of group.groups) {
- if (!this.validateConditionGroup(childGroup)) {
- return false;
- }
- }
- }
-
- return true;
- }
-
- protected validateRuleActions(rule: JsonRule, actions?: RuleActionUnion[]): boolean {
- if (!actions) {
- return true;
- }
-
- for (const action of actions) {
- switch (action.action) {
- case "wait":
- if (!action.millis) {
- return false;
- }
- break;
- case "write-attribute":
- if (!action.attributeName) {
- return false;
- }
- if (!this.validateAssetTarget(rule, action.target)) {
- return false;
- }
- break;
- case "notification":
- // TODO: validate notification rule action
- break;
- case "update-attribute":
- if (!action.attributeName) {
- return false;
- }
- if (!action.updateAction) {
- return false;
- }
- if (!this.validateAssetTarget(rule, action.target)) {
- return false;
- }
- break;
- default:
- return false;
- }
- }
-
- return true;
- }
-
- protected validateAssetTarget(rule: JsonRule, target?: RuleActionTarget): boolean {
- if (!target) {
- return true;
- }
-
- if (!target.assets && !target.ruleConditionTag) {
- return false;
- }
-
- if (target.assets) {
- return this.validateAssetQuery(target.assets, false, false);
- }
-
- if (target.matchedAssets) {
- return this.validateAssetQuery(target.matchedAssets, false, true);
- }
-
- const typesAndTags = this.getTypeAndTagsFromGroup(rule.when!);
- if (typesAndTags.findIndex((typeAndTag) => target.ruleConditionTag === typeAndTag[1]) < 0) {
- return false;
- }
-
- return true;
- }
-
- protected validateAssetQuery(query: AssetQuery, isWhen: boolean, isMatchedAssets: boolean): boolean {
-
- if (!query.types || query.types.length === 0) {
- return false;
- }
-
- if (isWhen) {
- if (!query.attributes || !query.attributes.items || query.attributes.items.length === 0) {
- return false;
- }
- } else {
- if (!query.ids || query.ids.length === 0 && !isMatchedAssets) {
- return false;
- }
- }
-
- if (query.types) {
- for (const type of query.types) {
- if (!type.value || !type.predicateType) {
- return false;
- }
- }
- }
-
- if (query.attributes && query.attributes.items) {
- for (const attribute of query.attributes.items) {
- if (!attribute.name || !attribute.name.match || !attribute.name.value) {
- return false;
- }
- if (!attribute.value || !this.validateValuePredicate(attribute.value)) {
- return false;
- }
- }
- }
-
- return true;
- }
-
- protected validateValuePredicate(valuePredicate: ValuePredicateUnion): boolean {
- switch (valuePredicate.predicateType) {
- case "string":
- return valuePredicate.match !== undefined && valuePredicate.value !== undefined;
- case "boolean":
- return valuePredicate.value !== undefined;
- case "string-array":
- return valuePredicate.predicates !== undefined && valuePredicate.predicates.length > 0 && valuePredicate.predicates.findIndex((p) => !p.match || p.value === undefined) === 0;
- case "datetime":
- case "number":
- return valuePredicate.operator !== undefined && valuePredicate.value !== undefined && (valuePredicate.operator !== AQO.BETWEEN || valuePredicate.rangeValue !== undefined);
- case "radial":
- return valuePredicate.radius !== undefined && valuePredicate.lat !== undefined && valuePredicate.lng !== undefined;
- case "rect":
- return valuePredicate.lngMax !== undefined && valuePredicate.latMax !== undefined && valuePredicate.lngMin !== undefined && valuePredicate.latMin !== undefined;
- case "object-value-key":
- return valuePredicate.key !== undefined;
- case "array":
- return (valuePredicate.index && !valuePredicate.value) || valuePredicate.value || valuePredicate.lengthEquals || valuePredicate.lengthLessThan || valuePredicate.lengthGreaterThan;
- case "value-empty":
- case "value-not-empty":
- return true;
- default:
- return false;
- }
- }
-
- protected _onRequestAdd() {
- const shouldContinue = this.okToLeaveActiveRule();
-
- if (!shouldContinue) {
- return;
- }
- let rule = this.config && this.config.templates && this.config.templates.rule ? JSON.parse(JSON.stringify(this.config.templates.rule)) as JsonRule : undefined;
-
- if (!rule) {
- rule = {
-
- };
- }
-
- const name = this.config && this.config.templates && this.config.templates.rulesetName ? this.config.templates.rulesetName : OrRulesEditor.DEFAULT_RULESET_NAME;
- rule.name = name;
- const rules: JsonRulesetDefinition = {
- rules: [rule]
- };
-
- const ruleset: TenantRuleset = {
- id: 0,
- type: "tenant",
- name: name,
- lang: RulesetLang.JSON,
- realm: manager.getRealm(),
- rules: JSON.stringify(rules)
- };
- this.activeRuleset = ruleset;
- }
-
- protected _onRequestSave(e: OrRulesEditorRequestSaveEvent) {
- if (!this.activeRuleset || !this.activeRule) {
- return;
- }
-
- this._saveInProgress = true;
- this.activeRule.name = this.activeRuleset.name;
- this._activeRules![0] = this.activeRule;
- const ruleset = this.activeRuleset;
-
- const rules: JsonRulesetDefinition = {
- rules: this._activeRules
- };
-
- ruleset.rules = JSON.stringify(rules);
- delete ruleset.lastModified;
- delete ruleset.createdOn;
- delete ruleset.status;
- delete ruleset.error;
-
- this._rulesList.disabled = true;
-
- if (ruleset.id) {
- manager.rest.api.RulesResource.updateTenantRuleset(ruleset.id!, ruleset).then((response) => {
- this._saveInProgress = false;
- this._rulesList.refresh();
- this._rulesList.disabled = false;
- });
- } else {
- manager.rest.api.RulesResource.createTenantRuleset(ruleset).then((response) => {
- ruleset.id = response.data;
- this._saveInProgress = false;
- this._rulesList.refresh();
- this._rulesList.disabled = false;
- });
- }
- }
-
- protected _onRequestCopy(e: OrRulesEditorRequestCopyEvent) {
- const shouldContinue = this.okToLeaveActiveRule();
-
- if (!shouldContinue) {
- return;
- }
-
- let ruleset = JSON.parse(JSON.stringify(e.detail)) as TenantRuleset;
- delete ruleset.lastModified;
- delete ruleset.createdOn;
- delete ruleset.status;
- delete ruleset.error;
- this.activeRuleset = ruleset;
- }
-
- protected async _onRequestDelete(event: OrRulesEditorRequestDeleteEvent) {
-
- let confirmed = this.okToLeaveActiveRule();
-
- if (!confirmed) {
- return;
- }
-
- confirmed = !this.activeRuleset!.id || window.confirm(i18next.t("confirmDelete"));
-
- if (!confirmed) {
- return;
- }
-
- this.activeRuleset = undefined;
-
- const rulesetsToDelete = event.detail;
-
- // We need to call the backend so disable list until done
- this._rulesList.disabled = true;
- for (let ruleset of rulesetsToDelete) {
- await manager.rest.api.RulesResource.deleteTenantRuleset(ruleset.id!);
- }
- this._rulesList.refresh();
- this._rulesList.disabled = false;
- }
-
- protected _onRequestSelect(event: OrRulesEditorRequestSelectEvent) {
- event.detail.allow = this.okToLeaveActiveRule();
- }
-
- protected _onRuleSelectionChanged(event: OrRulesEditorSelectionChangedEvent) {
- this.activeRuleset = event.detail.length == 1 ? event.detail[0] : undefined;
- }
-
- protected okToLeaveActiveRule() {
- return !this._activeModified || window.confirm(i18next.t("continueWithoutSaving"));
- }
-
- protected getTypeAndTagsFromGroup(group: LogicGroup<RuleCondition>): [string, string?][] {
- if (!group) {
- return [];
- }
-
- let typesAndTags: [string, string?][] = [];
-
- if (group.items) {
- for (const condition of group.items) {
- const type = getAssetTypeFromQuery(condition.assets);
- if (type) {
- typesAndTags.push([type, condition.tag]);
- }
- }
- }
-
- if (group.groups) {
- for (const condition of group.groups) {
- typesAndTags = typesAndTags.concat(this.getTypeAndTagsFromGroup(condition));
- }
- }
-
- return typesAndTags;
- }
-
- protected getTargetTypeMap(): [string, string?][] {
- if (!this.activeRule || !this.activeRule.when) {
- return [];
- }
-
- return this.getTypeAndTagsFromGroup(this.activeRule.when);
- }
-
- protected getAssetDescriptors(useActionConfig: boolean) {
- if (useActionConfig) {
- if (this._actionAssetDescriptors) {
- return this._actionAssetDescriptors;
- }
- this._actionAssetDescriptors = getAssetDescriptors(this.config, useActionConfig);
- return this._actionAssetDescriptors;
- }
-
- if (this._whenAssetDescriptors) {
- return this._whenAssetDescriptors;
- }
-
- this._whenAssetDescriptors = getAssetDescriptors(this.config, useActionConfig);
- return this._whenAssetDescriptors;
- }
-}
diff --git a/ui/component/or-rules-editor/src/or-rule-header.ts b/ui/component/or-rules-editor/src/or-rule-header.ts
deleted file mode 100644
index 3d2847c2e..000000000
--- a/ui/component/or-rules-editor/src/or-rule-header.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-import {customElement, html, LitElement, property} from "lit-element";
-import "@openremote/or-translate";
-import "@openremote/or-attribute-input";
-import "@openremote/or-select";
-import "@openremote/or-icon";
-import {TenantRuleset} from "@openremote/model";
-
-import {headerStyle} from "./style";
-import {OrRulesEditorRuleChangedEvent, OrRulesEditorRequestSaveEvent} from "./index";
-
-@customElement("or-rule-header")
-class OrRuleHeader extends LitElement {
-
- static get styles() {
- return headerStyle;
- }
-
- @property({type: Object, attribute: false})
- public ruleset!: TenantRuleset;
-
- @property({type: Boolean, attribute: false})
- public saveEnabled: boolean = false;
-
- public readonly: boolean = false;
-
- public changeName(e: any) {
- const value = e.target.value;
- if (this.ruleset) {
- this.ruleset.name = value;
- this.dispatchEvent(new OrRulesEditorRuleChangedEvent());
- }
- }
-
- public saveRuleset() {
- this.dispatchEvent(new OrRulesEditorRequestSaveEvent(this.ruleset));
- }
-
- public toggleEnabled() {
- if (this.ruleset) {
- this.ruleset.enabled = !this.ruleset.enabled;
- this.dispatchEvent(new OrRulesEditorRuleChangedEvent());
- this.requestUpdate();
- }
- }
-
- protected render() {
-
- return html`
- <div id="container">
- <input id="title" ?disabled="${this.readonly}" required placeholder=" " @change="${this.changeName}" type="text" minlength="3" maxlength="255" .value="${this.ruleset ? this.ruleset.name : null}" />
-
- <div id="controls">
- <span id="toggle-label" ?data-disabled="${!this.ruleset!.id}"><or-translate value="active"></or-translate></span>
- <label id="toggle" ?data-disabled="${!this.ruleset!.id}" @click="${this.toggleEnabled}" ?data-checked="${this.ruleset!.enabled}">
- <span></span>
- </label>
-
- ${this.ruleset ? html`
- <button id="save-btn" ?disabled="${!this.saveEnabled}" @click="${this.saveRuleset}"><or-translate value="save"></or-translate></button>
- ` : ``}
- </div>
- </div>
- `;
- }
-}
diff --git a/ui/component/or-rules-editor/src/style.ts b/ui/component/or-rules-editor/src/style.ts
deleted file mode 100644
index e61e9580b..000000000
--- a/ui/component/or-rules-editor/src/style.ts
+++ /dev/null
@@ -1,171 +0,0 @@
-import {css, unsafeCSS} from "lit-element";
-import {DefaultColor1, DefaultColor2, DefaultColor5, DefaultColor3, DefaultBoxShadow, DefaultColor4, DefaultColor6, DefaultDisabledOpacity} from "@openremote/core";
-
-// language=CSS
-export const invalidStyle = css`
- *:invalid {
- border-bottom: 2px solid var(--internal-or-rules-editor-invalid-color);
- }
-`;
-
-// language=CSS
-export const buttonStyle = css`
- .button-clear {
- background: none;
- color: var(--internal-or-rules-editor-button-color);
- --or-icon-fill: var(--internal-or-rules-editor-button-color);
- border: none;
- padding: 0;
- display: inline-block;
- cursor: pointer;
- }
-
- .button-clear:focus {
- outline: 0;
- }
-
- .add-button {
- display: inline-block;
- font-weight: bold;
- font-size: 15px;
- line-height: 24px;
- }
-
- .add-buttons-container {
- display: flex;
- flex-direction: column;
- margin-top: 10px;
- margin-bottom: -10px;
- padding-top: 5px;
- border-top-width: 1px;
- border-top-style: solid;
- border-color: var(--internal-or-rules-editor-line-color);
- }
-
- .add-buttons-container.hidden {
- border: none;
- margin: 0;
- padding: 0;
- }
-
- .add-buttons-container > button {
- display: inline-flex;
- }
-
- .add-buttons-container > button > or-icon {
- margin-right: 5px;
- }
-`;
-
-// language=CSS
-export const headerStyle = css`
-
- ${invalidStyle}
-
- :host {
- display: block;
- width: 100%;
- z-index: 1;
- background-color: var(--internal-or-rules-editor-header-background-color);
- --or-icon-fill: var(--internal-or-rules-editor-panel-color);
- }
-
- #container {
- display: flex;
- height: 100%;
- flex-direction: row;
- padding: 0 20px;
- }
-
- #title {
- font-size: 18px;
- font-weight: bold;
- border: 2px solid transparent;
- background-color: transparent;
- transition: all 150ms ease-in;
- width: 350px;
- max-width: 100%;
- }
-
- #title:hover {
- border-bottom-color: 2px solid var(--internal-or-rules-editor-line-color);
- }
-
- #title:focus {
- outline: none;
- }
-
- #controls {
- margin: 0 0 0 auto;
- display: flex;
- flex-direction: row;
- align-items: center;
- height: 100%;
- }
-
- #save-btn {
- padding: 0 20px;
- font-size: 14px;
- height: 40px;
- border-radius: 5px;
- border: none;
- background-color: var(--internal-or-rules-editor-button-color);
- margin-left: auto;
- color: var(--internal-or-rules-editor-panel-color);
- font-weight: bold;
- cursor: pointer;
- }
-
- #save-btn[disabled] {
- opacity: ${unsafeCSS(DefaultDisabledOpacity)};
- pointer-events: none;
- }
-
- /* The switch - the box around the slider */
- #toggle {
- position: relative;
- display: inline-block;
- width: 36px;
- height: 14px;
- margin: 13px 30px 13px 10px;
- }
-
- /* The slider */
- #toggle > span {
- position: absolute;
- cursor: pointer;
- top: 0;
- left: 0;
- right: 0;
- bottom: 0;
- background-color: #ccc;
- -webkit-transition: .4s;
- transition: .4s;
- border-radius: 34px;
- }
-
- #toggle-label[data-disabled], #toggle[data-disabled] {
- opacity: ${unsafeCSS(DefaultDisabledOpacity)};
- pointer-events: none;
- }
-
- #toggle > span:before {
- position: absolute;
- content: "";
- height: 20px;
- width: 20px;
- left: 0;
- top: -3px;
- opacity: 1;
- background-color: white;
- border-radius: 50%;
- -webkit-transition: .4s;
- transition: .4s;
- box-shadow: ${unsafeCSS(DefaultBoxShadow)};
- }
-
- #toggle[data-checked] > span:before {
- background-color: var(--internal-or-rules-editor-button-color);
- transform: translateX(20px);
- }
-`;
diff --git a/ui/component/or-rules-editor/.npmignore b/ui/component/or-rules/.npmignore
similarity index 100%
rename from ui/component/or-rules-editor/.npmignore
rename to ui/component/or-rules/.npmignore
diff --git a/ui/component/or-rules-editor/README.md b/ui/component/or-rules/README.md
similarity index 100%
rename from ui/component/or-rules-editor/README.md
rename to ui/component/or-rules/README.md
diff --git a/ui/component/or-rules-editor/build.gradle b/ui/component/or-rules/build.gradle
similarity index 100%
rename from ui/component/or-rules-editor/build.gradle
rename to ui/component/or-rules/build.gradle
diff --git a/ui/component/or-rules-editor/package.json b/ui/component/or-rules/package.json
similarity index 91%
rename from ui/component/or-rules-editor/package.json
rename to ui/component/or-rules/package.json
index 94a2ee9c6..bfd3b9115 100644
--- a/ui/component/or-rules-editor/package.json
+++ b/ui/component/or-rules/package.json
@@ -1,7 +1,7 @@
{
- "name": "@openremote/or-rules-editor",
+ "name": "@openremote/or-rules",
"version": "1.1.0",
- "description": "OpenRemote Rules Editor",
+ "description": "OpenRemote rules related UI components",
"main": "dist/umd/index.bundle.js",
"module": "dist/index.js",
"types": "dist/index.d.ts",
diff --git a/ui/component/or-rules/src/index.ts b/ui/component/or-rules/src/index.ts
new file mode 100644
index 000000000..cca0a5bfe
--- /dev/null
+++ b/ui/component/or-rules/src/index.ts
@@ -0,0 +1,666 @@
+import {css, customElement, html, LitElement, property, query, TemplateResult, unsafeCSS} from "lit-element";
+import manager, {
+ AssetModelUtil,
+ DefaultBoxShadow,
+ DefaultColor1,
+ DefaultColor2,
+ DefaultColor3,
+ DefaultColor4,
+ DefaultColor5,
+ DefaultColor6
+} from "@openremote/core";
+import i18next from "i18next";
+import "@openremote/or-select";
+import "@openremote/or-icon";
+import {
+ AssetDescriptor,
+ AssetQuery,
+ Attribute,
+ AttributeDescriptor,
+ AttributeValueDescriptor,
+ JsonRule,
+ LogicGroup,
+ MetaItemDescriptor,
+ MetaItemType,
+ RuleActionUnion,
+ RuleCondition,
+ RulesetLang,
+ RulesetUnion,
+ TenantRuleset,
+ ValueType
+} from "@openremote/model";
+import "@openremote/or-translate";
+import {translate} from "@openremote/or-translate";
+import "./or-rule-list";
+import "./or-rule-viewer";
+import {OrRuleList} from "./or-rule-list";
+import {OrRuleViewer} from "./or-rule-viewer";
+
+export const enum ConditionType {
+ ASSET_QUERY = "assetQuery",
+ DATE_TIME = "datetime",
+ TIMER = "timer"
+}
+
+export const enum ActionType {
+ WAIT = "wait",
+ NOTIFICATION = "notification",
+ ATTRIBUTE = "attribute"
+}
+
+export enum AssetQueryOperator {
+ VALUE_EMPTY = "empty",
+ VALUE_NOT_EMPTY = "notEmpty",
+ EQUALS = "equals",
+ NOT_EQUALS = "notEquals",
+ GREATER_THAN = "greaterThan",
+ GREATER_EQUALS = "greaterEquals",
+ LESS_THAN = "lessThan",
+ LESS_EQUALS = "lessEquals",
+ BETWEEN = "between",
+ NOT_BETWEEN = "notBetween",
+ CONTAINS = "contains",
+ NOT_CONTAINS = "notContains",
+ STARTS_WITH = "startsWith",
+ NOT_STARTS_WITH = "notStartsWith",
+ ENDS_WITH = "endsWith",
+ NOT_ENDS_WITH = "notEndsWith",
+ CONTAINS_KEY = "containsKey",
+ NOT_CONTAINS_KEY = "notContainsKey",
+ INDEX_CONTAINS = "indexContains",
+ NOT_INDEX_CONTAINS = "notIndexContains",
+ LENGTH_EQUALS = "lengthEquals",
+ NOT_LENGTH_EQUALS = "notLengthEquals",
+ LENGTH_GREATER_THAN = "lengthGreaterThan",
+ LENGTH_LESS_THAN = "lengthLessThan",
+ IS_TRUE = "true",
+ IS_FALSE = "false",
+ WITHIN_RADIUS = "withinRadius",
+ OUTSIDE_RADIUS = "outsideRadius",
+ WITHIN_RECTANGLE = "withinRectangle",
+ OUTSIDE_RECTANGLE = "outsideRectangle"
+}
+
+export interface AssetTypeAttributeName {
+ assetType: string;
+ attributeName: string;
+}
+
+export interface RulesConfig {
+ controls?: {
+ allowedLanguages?: RulesetLang[];
+ allowedConditionTypes?: ConditionType[];
+ allowedActionTypes?: ActionType[];
+ allowedAssetQueryOperators?: Map<AssetTypeAttributeName | AttributeDescriptor | AttributeValueDescriptor | ValueType, AssetQueryOperator[]>;
+ hideActionTypeOptions?: boolean;
+ hideActionTargetOptions?: boolean;
+ hideActionUpdateOptions?: boolean;
+ hideConditionTypeOptions?: boolean;
+ hideThenAddAction?: boolean;
+ hideWhenAddCondition?: boolean;
+ hideWhenAddAttribute?: boolean;
+ hideWhenAddGroup?: boolean;
+ };
+ inputProvider?: (assetType: string | undefined, attribute: Attribute | undefined, attributeDescriptor: AttributeDescriptor | undefined, valueDescriptor: AttributeValueDescriptor | undefined, valueChangeNotifier: (value: any | undefined) => void, readonly: boolean | undefined, disabled: boolean | undefined) => ((value: any) => TemplateResult) | undefined;
+ descriptors?: {
+ all?: RulesDescriptorSection;
+ when?: RulesDescriptorSection;
+ action?: RulesDescriptorSection;
+ };
+ rulesetName?: string;
+ json?: {
+ rule?: JsonRule;
+ whenGroup?: LogicGroup<RuleCondition>;
+ whenCondition?: RuleCondition;
+ whenAssetQuery?: AssetQuery;
+ then?: RuleActionUnion;
+ otherwise?: RuleActionUnion;
+ };
+}
+
+export interface RulesDescriptorSection {
+ includeAssets?: string[];
+ excludeAssets?: string[];
+ assets?: { [assetType: string]: RulesConfigAsset };
+ attributeDescriptors?: {[attributeName: string]: RulesConfigAttribute };
+}
+
+export interface RulesConfigAsset {
+ includeAttributes?: string[];
+ excludeAttributes?: string[];
+ name?: string;
+ icon?: string;
+ attributeDescriptors?: {[attributeName: string]: RulesConfigAttribute };
+}
+
+export interface RulesConfigAttribute {
+ icon?: string;
+ valueDescriptor?: RulesConfigAttribute;
+ initialValue?: any;
+ allowedValues?: any[];
+ allowedMin?: any;
+ allowedMax?: any;
+}
+
+export interface RulesConfigAttributeValue {
+ name?: string;
+ icon?: string;
+ valueType?: ValueType;
+}
+
+export interface RulesetNode {
+ ruleset: TenantRuleset;
+ selected: boolean;
+}
+
+export interface RequestEventDetail<T> {
+ allow: boolean,
+ detail: T
+}
+
+export interface RuleView {
+ validate: () => boolean;
+ beforeSave: () => void;
+ ruleset?: RulesetUnion;
+ readonly?: boolean;
+ config?: RulesConfig;
+}
+
+function getAssetDescriptorFromSection(assetTpe: string, config: RulesConfig | undefined, useActionConfig: boolean) {
+ if (!config || !config.descriptors) {
+ return;
+ }
+
+ const section = useActionConfig ? config.descriptors.action : config.descriptors.when;
+ const allSection = config.descriptors.all;
+
+ const descriptor = section && section.assets ? section.assets[assetTpe] : undefined;
+ if (descriptor) {
+ return descriptor;
+ }
+
+ return allSection && allSection.assets ? allSection.assets[assetTpe] : undefined;
+}
+
+export function getDescriptorValueType(descriptor?: AttributeDescriptor) {
+ if (!descriptor || !descriptor.valueDescriptor) {
+ return;
+ }
+
+ return descriptor.valueDescriptor.valueType;
+}
+
+export function getAssetTypeFromQuery(query?: AssetQuery) {
+ return query && query.types && query.types.length > 0 && query.types[0] ? query.types[0].value : undefined;
+}
+
+export function getAssetIdsFromQuery(query?: AssetQuery) {
+ return query && query.ids ? [...query.ids] : undefined;
+}
+
+export function getAttributeNames(descriptor?: AssetDescriptor) {
+ let attributes: string[] = [];
+
+ if (descriptor && descriptor.attributeDescriptors) {
+ attributes = descriptor.attributeDescriptors.map((ad) => ad.attributeName!);
+ }
+
+ return attributes;
+}
+
+export function getAssetDescriptors(config: RulesConfig | undefined, useActionConfig: boolean) {
+ const assetDescriptors: AssetDescriptor[] = AssetModelUtil.getAssetDescriptors();
+ let allowedAssetTypes: string[] = [];
+ let excludedAssetTypes: string[] = [];
+
+ if (!config || !config.descriptors) {
+ return assetDescriptors;
+ }
+
+ const section = useActionConfig ? config.descriptors.action : config.descriptors.when;
+
+ if (section && section.includeAssets) {
+ allowedAssetTypes = [...section.includeAssets];
+ }
+
+ if (config.descriptors.all && config.descriptors.all.includeAssets) {
+ allowedAssetTypes = allowedAssetTypes.concat(config.descriptors.all.includeAssets);
+ }
+
+ if (section && section.excludeAssets) {
+ excludedAssetTypes = [...section.excludeAssets];
+ }
+
+ if (config.descriptors.all && config.descriptors.all.excludeAssets) {
+ excludedAssetTypes = excludedAssetTypes.concat(config.descriptors.all.excludeAssets);
+ }
+
+ return assetDescriptors.filter((ad) => {
+ if (allowedAssetTypes.length > 0 && allowedAssetTypes.indexOf(ad.type!) < 0) {
+ return false;
+ }
+ return excludedAssetTypes.indexOf(ad.type!) < 0;
+
+ }).map((ad) => {
+ // Amalgamate matching descriptor from config if defined
+ const configDescriptor = getAssetDescriptorFromSection(ad.type!, config, useActionConfig);
+ if (!configDescriptor) {
+ return ad;
+ }
+
+ const modifiedDescriptor: AssetDescriptor = {
+ name: ad.name,
+ type: ad.type,
+ icon: ad.icon,
+ attributeDescriptors: ad.attributeDescriptors ? [...ad.attributeDescriptors] : undefined
+ };
+
+ if (configDescriptor.icon) {
+ modifiedDescriptor.icon = configDescriptor.icon;
+ }
+ if (configDescriptor.name) {
+ modifiedDescriptor.name = configDescriptor.name;
+ }
+
+ // Remove any excluded attributes
+ if (modifiedDescriptor.attributeDescriptors) {
+ const inc = configDescriptor.includeAttributes !== undefined ? configDescriptor.includeAttributes : undefined;
+ const exc = configDescriptor.excludeAttributes !== undefined ? configDescriptor.excludeAttributes : undefined;
+
+ if (inc || exc) {
+ modifiedDescriptor.attributeDescriptors = modifiedDescriptor.attributeDescriptors.filter((mad) => {
+ if (exc && exc.indexOf(mad.attributeName!) >= 0) {
+ return false;
+ }
+ if (inc && inc.indexOf(mad.attributeName!) < 0) {
+ return false;
+ }
+ return true;
+ });
+ }
+
+ // Override any attribute descriptors
+ if (configDescriptor.attributeDescriptors) {
+ modifiedDescriptor.attributeDescriptors.map((attributeDescriptor) => {
+ let configAttributeDescriptor: RulesConfigAttribute | undefined = configDescriptor.attributeDescriptors![attributeDescriptor.attributeName!];
+ if (!configAttributeDescriptor) {
+ configAttributeDescriptor = section && section.attributeDescriptors ? section.attributeDescriptors[attributeDescriptor.attributeName!] : undefined;
+ }
+ if (!configAttributeDescriptor) {
+ configAttributeDescriptor = config.descriptors!.all && config.descriptors!.all.attributeDescriptors ? config.descriptors!.all.attributeDescriptors[attributeDescriptor.attributeName!] : undefined;
+ }
+ if (configAttributeDescriptor) {
+ let metaItemDescriptors = attributeDescriptor.metaItemDescriptors;
+ if (!metaItemDescriptors) {
+ attributeDescriptor.metaItemDescriptors = [];
+ metaItemDescriptors = attributeDescriptor.metaItemDescriptors;
+ }
+
+ if (configAttributeDescriptor.allowedValues) {
+ addOrReplaceMetaItemDescriptor(metaItemDescriptors, AssetModelUtil.getMetaItemDescriptorInitialValue(MetaItemType.ALLOWED_VALUES, configAttributeDescriptor.allowedValues));
+ }
+ if (configAttributeDescriptor.allowedMin) {
+ addOrReplaceMetaItemDescriptor(metaItemDescriptors, AssetModelUtil.getMetaItemDescriptorInitialValue(MetaItemType.RANGE_MIN, configAttributeDescriptor.allowedMin));
+ }
+ if (configAttributeDescriptor.allowedMax) {
+ addOrReplaceMetaItemDescriptor(metaItemDescriptors, AssetModelUtil.getMetaItemDescriptorInitialValue(MetaItemType.RANGE_MAX, configAttributeDescriptor.allowedMax));
+ }
+
+ return {
+ attributeName: attributeDescriptor.attributeName,
+ valueDescriptor: configAttributeDescriptor.valueDescriptor ? configAttributeDescriptor.valueDescriptor : attributeDescriptor.valueDescriptor,
+ initialValue: configAttributeDescriptor.initialValue ? configAttributeDescriptor.initialValue : attributeDescriptor.initialValue,
+ metaItemDescriptors: attributeDescriptor.metaItemDescriptors
+ };
+ }
+
+ return attributeDescriptor;
+ });
+ }
+ }
+ return modifiedDescriptor;
+ });
+}
+
+function addOrReplaceMetaItemDescriptor(metaItemDescriptors: MetaItemDescriptor[], metaItemDescriptor: MetaItemDescriptor) {
+ const index = metaItemDescriptors.findIndex((mid) => mid.urn === metaItemDescriptor.urn);
+ if (index >= 0) {
+ metaItemDescriptors.splice(index, 1);
+
+ }
+ metaItemDescriptors.push(metaItemDescriptor);
+}
+
+export class OrRulesRuleChangedEvent extends CustomEvent<boolean> {
+
+ public static readonly NAME = "or-rules-rule-changed";
+
+ constructor(valid: boolean) {
+ super(OrRulesRuleChangedEvent.NAME, {
+ bubbles: true,
+ composed: true,
+ detail: valid
+ });
+ }
+}
+
+export class OrRulesRuleUnsupportedEvent extends CustomEvent<void> {
+
+ public static readonly NAME = "or-rules-rule-unsupported";
+
+ constructor() {
+ super(OrRulesRuleUnsupportedEvent.NAME, {
+ bubbles: true,
+ composed: true
+ });
+ }
+}
+
+export class OrRulesRequestSelectEvent extends CustomEvent<RequestEventDetail<RulesetUnion[]>> {
+
+ public static readonly NAME = "or-rules-request-select";
+
+ constructor(request: TenantRuleset[]) {
+ super(OrRulesRequestSelectEvent.NAME, {
+ bubbles: true,
+ composed: true,
+ detail: {
+ allow: true,
+ detail: request
+ }
+ });
+ }
+}
+
+export class OrRulesRequestAddEvent extends CustomEvent<RulesetLang> {
+
+ public static readonly NAME = "or-rules-request-add";
+
+ constructor(lang: RulesetLang) {
+ super(OrRulesRequestAddEvent.NAME, {
+ bubbles: true,
+ composed: true,
+ detail: lang
+ });
+ }
+}
+
+export class OrRulesRequestDeleteEvent extends CustomEvent<RulesetUnion[]> {
+
+ public static readonly NAME = "or-rules-request-delete";
+
+ constructor(request: TenantRuleset[]) {
+ super(OrRulesRequestDeleteEvent.NAME, {
+ bubbles: true,
+ composed: true,
+ detail: request
+ });
+ }
+}
+
+export class OrRulesRequestCopyEvent extends CustomEvent<RulesetUnion> {
+
+ public static readonly NAME = "or-rules-request-copy";
+
+ constructor(request: TenantRuleset) {
+ super(OrRulesRequestCopyEvent.NAME, {
+ bubbles: true,
+ composed: true,
+ detail: request
+ });
+ }
+}
+
+export class OrRulesSaveStartEvent extends CustomEvent<void> {
+
+ public static readonly NAME = "or-rules-save-start";
+
+ constructor() {
+ super(OrRulesSaveStartEvent.NAME, {
+ bubbles: true,
+ composed: true
+ });
+ }
+}
+
+export class OrRulesSaveEndEvent extends CustomEvent<boolean> {
+
+ public static readonly NAME = "or-rules-save-end";
+
+ constructor(success: boolean) {
+ super(OrRulesSaveEndEvent.NAME, {
+ bubbles: true,
+ composed: true,
+ detail: success
+ });
+ }
+}
+
+export class OrRulesSelectionChangedEvent extends CustomEvent<RulesetUnion[]> {
+
+ public static readonly NAME = "or-rules-selection-changed";
+
+ constructor(nodes: TenantRuleset[]) {
+ super(OrRulesSelectionChangedEvent.NAME, {
+ bubbles: true,
+ composed: true,
+ detail: nodes
+ });
+ }
+}
+
+declare global {
+ export interface HTMLElementEventMap {
+ [OrRulesRuleUnsupportedEvent.NAME]: OrRulesRuleUnsupportedEvent;
+ [OrRulesRequestSelectEvent.NAME]: OrRulesRequestSelectEvent;
+ [OrRulesRequestAddEvent.NAME]: OrRulesRequestAddEvent;
+ [OrRulesRequestDeleteEvent.NAME]: OrRulesRequestDeleteEvent;
+ [OrRulesRequestCopyEvent.NAME]: OrRulesRequestCopyEvent;
+ [OrRulesSaveStartEvent.NAME]: OrRulesSaveStartEvent;
+ [OrRulesSaveEndEvent.NAME]: OrRulesSaveEndEvent;
+ [OrRulesRuleChangedEvent.NAME]: OrRulesRuleChangedEvent;
+ [OrRulesSelectionChangedEvent.NAME]: OrRulesSelectionChangedEvent;
+ }
+}
+
+// language=CSS
+export const style = css`
+
+ :host {
+ display: flex;
+ height: 100%;
+ width: 100%;
+
+ --internal-or-rules-background-color: var(--or-rules-background-color, var(--or-app-color2, ${unsafeCSS(DefaultColor2)}));
+ --internal-or-rules-text-color: var(--or-rules-text-color, inherit);
+ --internal-or-rules-button-color: var(--or-rules-button-color, var(--or-app-color4, ${unsafeCSS(DefaultColor4)}));
+ --internal-or-rules-invalid-color: var(--or-rules-invalid-color, var(--or-app-color6, ${unsafeCSS(DefaultColor6)}));
+ --internal-or-rules-panel-color: var(--or-rules-panel-color, var(--or-app-color1, ${unsafeCSS(DefaultColor1)}));
+ --internal-or-rules-line-color: var(--or-rules-line-color, var(--or-app-color5, ${unsafeCSS(DefaultColor5)}));
+
+ --internal-or-rules-list-selected-color: var(--or-rules-list-selected-color, var(--or-app-color2, ${unsafeCSS(DefaultColor2)}));
+ --internal-or-rules-list-text-color: var(--or-rules-list-text-color, var(--or-app-color3, ${unsafeCSS(DefaultColor3)}));
+ --internal-or-rules-list-text-size: var(--or-rules-list-text-size, 15px);
+ --internal-or-rules-list-header-height: var(--or-rules-list-header-height, 48px);
+
+ --internal-or-rules-list-button-size: var(--or-rules-list-button-size, 24px);
+
+ --internal-or-rules-header-background-color: var(--or-rules-header-background-color, var(--or-app-color1, ${unsafeCSS(DefaultColor1)}));
+ --internal-or-rules-header-height: var(--or-rules-header-height, 80px);
+
+ --or-panel-background-color: var(--internal-or-rules-panel-color);
+ }
+
+ or-rule-list {
+ min-width: 300px;
+ width: 300px;
+ z-index: 2;
+ display: flex;
+ flex-direction: column;
+ background-color: var(--internal-or-rules-panel-color);
+ color: var(--internal-or-rules-list-text-color);
+ box-shadow: ${unsafeCSS(DefaultBoxShadow)};
+ }
+
+ or-rule-viewer {
+ z-index: 1;
+ }
+`;
+
+@customElement("or-rules")
+export class OrRules extends translate(i18next)(LitElement) {
+
+ public static DEFAULT_RULESET_NAME = "New rule";
+
+ static get styles() {
+ return [
+ style
+ ];
+ }
+
+ @property({type: Boolean})
+ public readonly?: boolean;
+
+ @property({type: Object})
+ public config?: RulesConfig;
+
+ @property({type: String})
+ public realm?: string;
+
+ @property({type: String})
+ public language?: RulesetLang;
+
+ @property({type: Array})
+ public selectedIds?: number[];
+
+ @property({attribute: false})
+ private _isValidRule?: boolean;
+
+ @query("#rule-list")
+ private _rulesList!: OrRuleList;
+
+ @query("#rule-viewer")
+ private _ruleViewer!: OrRuleViewer;
+
+ @property({attribute: false})
+ private _activeRuleset?: RulesetUnion;
+
+ constructor() {
+ super();
+
+ this.addEventListener(OrRulesRequestSelectEvent.NAME, this._onRequestSelect);
+ this.addEventListener(OrRulesRequestAddEvent.NAME,this._onRequestAdd);
+ this.addEventListener(OrRulesRequestDeleteEvent.NAME, this._onRequestDelete);
+ this.addEventListener(OrRulesRequestCopyEvent.NAME, this._onRequestCopy);
+ this.addEventListener(OrRulesSelectionChangedEvent.NAME, this._onRuleSelectionChanged);
+ this.addEventListener(OrRulesSaveEndEvent.NAME, this._onRuleSaveEnd);
+ this.addEventListener(OrRulesSaveStartEvent.NAME, this._onRuleSaveStart);
+ }
+
+ protected render() {
+
+ return html`
+ <or-rule-list id="rule-list" .realm="${this.realm}" .config="${this.config}" .language="${this.language}" .selectedIds="${this.selectedIds}"></or-rule-list>
+ <or-rule-viewer id="rule-viewer" .ruleset="${this._activeRuleset}" .config="${this.config}" .readonly="${this.isReadonly()}"></or-rule-viewer>
+ `;
+ }
+
+ protected isReadonly(): boolean {
+ return this.readonly || !manager.hasRole("write:rules");
+ }
+
+ protected _onRequestAdd(e: OrRulesRequestAddEvent) {
+ const lang = e.detail;
+ const shouldContinue = this._okToLeaveActiveRule();
+
+ if (!shouldContinue) {
+ return;
+ }
+
+ const name = this.config && this.config.rulesetName ? this.config.rulesetName : OrRules.DEFAULT_RULESET_NAME;
+ const realm = this._rulesList.realm;
+
+ const ruleset: TenantRuleset = {
+ id: 0,
+ type: "tenant",
+ name: name,
+ lang: lang,
+ realm: realm,
+ rules: undefined // View needs to populate this on load
+ };
+ this._activeRuleset = ruleset;
+ }
+
+ protected _onRequestCopy(e: OrRulesRequestCopyEvent) {
+ const shouldContinue = this._okToLeaveActiveRule();
+
+ if (!shouldContinue) {
+ return;
+ }
+
+ let ruleset = JSON.parse(JSON.stringify(e.detail)) as RulesetUnion;
+ delete ruleset.lastModified;
+ delete ruleset.createdOn;
+ delete ruleset.status;
+ delete ruleset.error;
+ delete ruleset.id;
+ this._activeRuleset = ruleset;
+ }
+
+ protected async _onRequestDelete(event: OrRulesRequestDeleteEvent) {
+
+ let confirmed = this._okToLeaveActiveRule();
+
+ if (!confirmed) {
+ return;
+ }
+
+ confirmed = !this._activeRuleset!.id || window.confirm(i18next.t("confirmDelete"));
+
+ if (!confirmed) {
+ return;
+ }
+
+ this._activeRuleset = undefined;
+
+ const rulesetsToDelete = event.detail;
+
+ // We need to call the backend so disable list until done
+ this._rulesList.disabled = true;
+ for (let ruleset of rulesetsToDelete) {
+ try {
+ await manager.rest.api.RulesResource.deleteTenantRuleset(ruleset.id!);
+ } catch (e) {
+ console.error("Failed to delete ruleset '" + ruleset.id + "': " + e);
+ }
+ }
+ this._rulesList.refresh();
+ this._rulesList.disabled = false;
+ }
+
+ protected _onRequestSelect(event: OrRulesRequestSelectEvent) {
+ event.detail.allow = this._okToLeaveActiveRule();
+ }
+
+ protected _onRuleSelectionChanged(event: OrRulesSelectionChangedEvent) {
+ this._activeRuleset = event.detail.length == 1 ? event.detail[0] : undefined;
+ }
+
+ protected _onRuleSaveStart(event: OrRulesSaveStartEvent) {
+ this._rulesList.disabled = true;
+ this._ruleViewer.disabled = true;
+ }
+
+ protected _onRuleSaveEnd(event: OrRulesSaveEndEvent) {
+ this._rulesList.disabled = false;
+ this._ruleViewer.disabled = false;
+
+ if (event.detail) {
+ this._rulesList.refresh();
+ }
+ }
+
+ protected _okToLeaveActiveRule() {
+ return !this._ruleViewer.modified || window.confirm(i18next.t("continueWithoutSaving"));
+ }
+}
diff --git a/ui/component/or-rules-editor/src/or-rule-action-attribute.ts b/ui/component/or-rules/src/json-viewer/or-rule-action-attribute.ts
similarity index 95%
rename from ui/component/or-rules-editor/src/or-rule-action-attribute.ts
rename to ui/component/or-rules/src/json-viewer/or-rule-action-attribute.ts
index eb34db51f..603954f5e 100644
--- a/ui/component/or-rules-editor/src/or-rule-action-attribute.ts
+++ b/ui/component/or-rules/src/json-viewer/or-rule-action-attribute.ts
@@ -1,5 +1,5 @@
import {customElement, html, LitElement, property, PropertyValues, css, TemplateResult} from "lit-element";
-import {getAssetIdsFromQuery, getAssetTypeFromQuery, OrRulesEditorRuleChangedEvent, RulesConfig} from "./index";
+import {getAssetIdsFromQuery, getAssetTypeFromQuery, RulesConfig} from "../index";
import {
Asset,
AssetDescriptor,
@@ -13,6 +13,7 @@ import manager, {AssetModelUtil, Util} from "@openremote/core";
import {getAttributeValueTemplate} from "@openremote/or-attribute-input";
import {InputType, OrInputChangedEvent} from "@openremote/or-input";
import i18next from "i18next";
+import {OrRulesJsonRuleChangedEvent} from "./or-rule-json-viewer";
// language=CSS
const style = css`
@@ -21,7 +22,7 @@ const style = css`
}
:host > * {
- margin-right: 20px;
+ margin-right: 10px;
}
`;
@@ -167,20 +168,20 @@ export class OrRuleActionAttribute extends LitElement {
}
}
- this.dispatchEvent(new OrRulesEditorRuleChangedEvent());
+ this.dispatchEvent(new OrRulesJsonRuleChangedEvent());
this.requestUpdate();
}
protected setActionAttributeName(name: string | undefined) {
this.action.attributeName = name;
this.action.value = undefined;
- this.dispatchEvent(new OrRulesEditorRuleChangedEvent());
+ this.dispatchEvent(new OrRulesJsonRuleChangedEvent());
this.requestUpdate();
}
protected setActionAttributeValue(value: any) {
this.action.value = value;
- this.dispatchEvent(new OrRulesEditorRuleChangedEvent());
+ this.dispatchEvent(new OrRulesJsonRuleChangedEvent());
this.requestUpdate();
}
diff --git a/ui/component/or-rules-editor/src/or-rule-asset-query.ts b/ui/component/or-rules/src/json-viewer/or-rule-asset-query.ts
similarity index 96%
rename from ui/component/or-rules-editor/src/or-rule-asset-query.ts
rename to ui/component/or-rules/src/json-viewer/or-rule-asset-query.ts
index a3022ceaa..3d24dc5f2 100644
--- a/ui/component/or-rules-editor/src/or-rule-asset-query.ts
+++ b/ui/component/or-rules/src/json-viewer/or-rule-asset-query.ts
@@ -22,16 +22,16 @@ import {
getAssetTypeFromQuery,
getAssetIdsFromQuery,
getDescriptorValueType,
- OrRulesEditorRuleChangedEvent,
RulesConfig, getAttributeNames
-} from "./index";
+} from "../index";
import {OrSelectChangedEvent} from "@openremote/or-select";
import "@openremote/or-input";
import {InputType, OrInputChangedEvent} from "@openremote/or-input";
import {getAttributeValueTemplate} from "@openremote/or-attribute-input";
import manager, {Util, AssetModelUtil} from "@openremote/core";
import i18next from "i18next";
-import {buttonStyle} from "./style";
+import {buttonStyle} from "../style";
+import {OrRulesJsonRuleChangedEvent} from "./or-rule-json-viewer";
// language=CSS
const style = css`
@@ -39,11 +39,7 @@ const style = css`
${buttonStyle}
:host {
- display: flex;
- }
-
- :host > * {
- margin-right: 20px;
+ display: block;
}
.attribute-group {
@@ -225,7 +221,7 @@ class OrRuleAssetQuery extends LitElement {
return html`
<div class="attribute-group">
- <or-input type="${InputType.SELECT}" @or-input-changed="${(e: OrInputChangedEvent) => this._assetId = (e.detail.value)}" ?readonly="${this.readonly}" .options="${idOptions}" .value="${idValue}"></or-input>
+ <or-input id="idSelect" type="${InputType.SELECT}" @or-input-changed="${(e: OrInputChangedEvent) => this._assetId = (e.detail.value)}" ?readonly="${this.readonly}" .options="${idOptions}" .value="${idValue}"></or-input>
${this.query.attributes && this.query.attributes.items ? this.query.attributes.items.map((attributePredicate) => {
@@ -244,7 +240,7 @@ class OrRuleAssetQuery extends LitElement {
protected set _assetId(assetId: string | undefined) {
!assetId || assetId === "*" ? this.query.ids = undefined : this.query.ids! = [assetId];
- this.dispatchEvent(new OrRulesEditorRuleChangedEvent());
+ this.dispatchEvent(new OrRulesJsonRuleChangedEvent());
this.requestUpdate();
}
@@ -263,7 +259,7 @@ class OrRuleAssetQuery extends LitElement {
attributePredicate!.name.match = AssetQueryMatch.EXACT;
attributePredicate!.name.value = attributeName;
attributePredicate!.value = undefined;
- this.dispatchEvent(new OrRulesEditorRuleChangedEvent());
+ this.dispatchEvent(new OrRulesJsonRuleChangedEvent());
this.requestUpdate();
}
@@ -407,7 +403,7 @@ class OrRuleAssetQuery extends LitElement {
if (!operator) {
attributePredicate.value = undefined;
- this.dispatchEvent(new OrRulesEditorRuleChangedEvent());
+ this.dispatchEvent(new OrRulesJsonRuleChangedEvent());
this.requestUpdate();
return;
}
@@ -419,7 +415,7 @@ class OrRuleAssetQuery extends LitElement {
if (!valueType || !value) {
attributePredicate.value = undefined;
- this.dispatchEvent(new OrRulesEditorRuleChangedEvent());
+ this.dispatchEvent(new OrRulesJsonRuleChangedEvent());
this.requestUpdate();
return;
}
@@ -602,7 +598,7 @@ class OrRuleAssetQuery extends LitElement {
}
attributePredicate.value = predicate;
- this.dispatchEvent(new OrRulesEditorRuleChangedEvent());
+ this.dispatchEvent(new OrRulesJsonRuleChangedEvent());
this.requestUpdate();
}
@@ -620,7 +616,7 @@ class OrRuleAssetQuery extends LitElement {
}
(valuePredicate as any)[propertyName] = value;
- this.dispatchEvent(new OrRulesEditorRuleChangedEvent());
+ this.dispatchEvent(new OrRulesJsonRuleChangedEvent());
this.requestUpdate();
}
@@ -629,7 +625,7 @@ class OrRuleAssetQuery extends LitElement {
if (index >= 0) {
group.items!.splice(index, 1);
}
- this.dispatchEvent(new OrRulesEditorRuleChangedEvent());
+ this.dispatchEvent(new OrRulesJsonRuleChangedEvent());
this.requestUpdate();
}
@@ -638,7 +634,7 @@ class OrRuleAssetQuery extends LitElement {
group.items = [];
}
group.items.push({});
- this.dispatchEvent(new OrRulesEditorRuleChangedEvent());
+ this.dispatchEvent(new OrRulesJsonRuleChangedEvent());
this.requestUpdate();
}
@@ -648,7 +644,7 @@ class OrRuleAssetQuery extends LitElement {
} else {
group.operator = LogicGroupOperator.OR;
}
- this.dispatchEvent(new OrRulesEditorRuleChangedEvent());
+ this.dispatchEvent(new OrRulesJsonRuleChangedEvent());
this.requestUpdate();
}
diff --git a/ui/component/or-rules-editor/src/or-rule-condition.ts b/ui/component/or-rules/src/json-viewer/or-rule-condition.ts
similarity index 66%
rename from ui/component/or-rules-editor/src/or-rule-condition.ts
rename to ui/component/or-rules/src/json-viewer/or-rule-condition.ts
index 8887b7b2d..f623e2537 100644
--- a/ui/component/or-rules-editor/src/or-rule-condition.ts
+++ b/ui/component/or-rules/src/json-viewer/or-rule-condition.ts
@@ -3,23 +3,24 @@ import {AssetDescriptor, AssetQueryMatch, RuleCondition} from "@openremote/model
import {
ConditionType,
getAssetTypeFromQuery,
- getButtonWithMenuTemplate,
- OrRulesEditorRuleChangedEvent,
RulesConfig
-} from "./index";
+} from "../index";
import "./or-rule-asset-query";
import "@openremote/or-mwc-components/dist/or-mwc-menu";
-import {Menu, MenuItem} from "@openremote/or-mwc-components/dist/or-mwc-menu";
+import {MenuItem} from "@openremote/or-mwc-components/dist/or-mwc-menu";
import "@openremote/or-icon";
import "@openremote/or-translate";
import {getAssetDescriptorIconTemplate} from "@openremote/or-icon";
+import {InputType} from "@openremote/or-input";
import {AssetModelUtil} from "@openremote/core";
import {i18next} from "@openremote/or-translate";
+import {OrRulesJsonRuleChangedEvent} from "./or-rule-json-viewer";
+import {getContentWithMenuTemplate} from "@openremote/or-mwc-components/dist/or-mwc-menu";
const TIMER_COLOR = "4b87ea";
const DATE_TIME_COLOR = "6AEAA4";
-function getWhenTypesMenu(config?: RulesConfig, assetDescriptors?: AssetDescriptor[]): Menu {
+export function getWhenTypesMenu(config?: RulesConfig, assetDescriptors?: AssetDescriptor[]): MenuItem[] {
let addAssetTypes = true;
let addDatetime = true;
@@ -31,15 +32,13 @@ function getWhenTypesMenu(config?: RulesConfig, assetDescriptors?: AssetDescript
addTimer = config.controls.allowedConditionTypes.indexOf(ConditionType.TIMER) >= 0;
}
- const menu: Menu = {
- items: []
- };
+ const menu: MenuItem[] = [];
if (addAssetTypes && assetDescriptors) {
- menu.items.push(...assetDescriptors.map((ad) => {
+ menu.push(...assetDescriptors.map((ad) => {
const content = html`
${getAssetDescriptorIconTemplate(ad)}
- &nbsp;&nbsp;<span style="white-space: nowrap; text-transform: capitalize">${i18next.t(ad.name!, {defaultValue: ad.name!.replace(/_/g, " ").toLowerCase()})}</span>
+ &nbsp;&nbsp;<span style="text-transform: capitalize">${i18next.t(ad.name!, {defaultValue: ad.name!.replace(/_/g, " ").toLowerCase()})}</span>
`;
return {content: content, value: ad.type} as MenuItem
}));
@@ -50,7 +49,7 @@ function getWhenTypesMenu(config?: RulesConfig, assetDescriptors?: AssetDescript
<or-icon style="--or-icon-fill: #${DATE_TIME_COLOR}" icon="clock"></or-icon>
<span style="text-transform: capitalize">&nbsp;<or-translate value="datetime"></or-translate></span>
`;
- menu.items.push({content: content, value: ConditionType.DATE_TIME} as MenuItem);
+ menu.push({content: content, value: ConditionType.DATE_TIME} as MenuItem);
}
if (addTimer) {
@@ -58,17 +57,54 @@ function getWhenTypesMenu(config?: RulesConfig, assetDescriptors?: AssetDescript
<or-icon style="--or-icon-fill: #${TIMER_COLOR}" icon="timer"></or-icon>
<span style="text-transform: capitalize">&nbsp;<or-translate value="timer"></or-translate></span>
`;
- menu.items.push({content: content, value: ConditionType.TIMER} as MenuItem);
+ menu.push({content: content, value: ConditionType.TIMER} as MenuItem);
}
return menu;
}
+export function updateRuleConditionType(ruleCondition: RuleCondition, value: string | undefined, config?: RulesConfig) {
+
+ if (!value || value === "") {
+ ruleCondition.assets = undefined;
+ ruleCondition.timer = undefined;
+ ruleCondition.datetime = undefined;
+ } else if (value === ConditionType.TIMER) {
+ ruleCondition.assets = undefined;
+ ruleCondition.datetime = undefined;
+ ruleCondition.timer = "1h";
+ } else if (value === ConditionType.DATE_TIME) {
+ ruleCondition.assets = undefined;
+ ruleCondition.timer = undefined;
+ ruleCondition.datetime = {
+ predicateType: "datetime"
+ };
+ } else {
+ ruleCondition.timer = undefined;
+ ruleCondition.datetime = undefined;
+
+ if (config && config.json && config.json.whenAssetQuery) {
+ ruleCondition.assets = JSON.parse(JSON.stringify(config.json.whenAssetQuery));
+ } else {
+ ruleCondition.assets = {};
+ }
+
+ if (!ruleCondition.assets!.types || ruleCondition.assets!.types.length === 0) {
+ ruleCondition.assets!.types = [{
+ predicateType: "string",
+ match: AssetQueryMatch.EXACT
+ }];
+ }
+ ruleCondition.assets!.types[0].value = value;
+ }
+}
+
// language=CSS
const style = css`
:host {
display: flex;
flex-direction: row;
+ align-items: center;
}
or-rule-asset-query {
@@ -78,6 +114,10 @@ const style = css`
#type-selector {
margin-top: 10px;
}
+
+ #type {
+ margin-right: 10px;
+ }
`;
@customElement("or-rule-condition")
@@ -132,8 +172,12 @@ class OrRuleCondition extends LitElement {
}
typeTemplate = html`
- <div style="display: table; height: 100%; --or-input-color: #${buttonColor}">
- ${getButtonWithMenuTemplate(getWhenTypesMenu(this.config, this.assetDescriptors), buttonIcon || "", type, (value: string) => this.type = value)}
+ <div id="type" style="--or-input-text-color: #${buttonColor}">
+ ${getContentWithMenuTemplate(
+ html`<or-input class="menu-button" type="${InputType.BUTTON}" .icon="${buttonIcon || ""}"></or-input>`,
+ getWhenTypesMenu(this.config, this.assetDescriptors),
+ type,
+ (value: string) => this.type = value)}
</div>
`;
}
@@ -176,53 +220,8 @@ class OrRuleCondition extends LitElement {
protected set type(value: string | undefined) {
- if (!value || value === "") {
- this.ruleCondition.assets = undefined;
- this.ruleCondition.timer = undefined;
- this.ruleCondition.datetime = undefined;
- this.dispatchEvent(new OrRulesEditorRuleChangedEvent());
- this.requestUpdate();
- return;
- }
-
- if (value === ConditionType.TIMER) {
- this.ruleCondition.assets = undefined;
- this.ruleCondition.datetime = undefined;
- this.ruleCondition.timer = "1h";
- this.dispatchEvent(new OrRulesEditorRuleChangedEvent());
- this.requestUpdate();
- return;
- }
-
- if (value === ConditionType.DATE_TIME) {
- this.ruleCondition.assets = undefined;
- this.ruleCondition.timer = undefined;
- this.ruleCondition.datetime = {
- predicateType: "datetime"
- };
- this.dispatchEvent(new OrRulesEditorRuleChangedEvent());
- this.requestUpdate();
- return;
- }
-
- this.ruleCondition.timer = undefined;
- this.ruleCondition.datetime = undefined;
-
- if (this.config && this.config.templates && this.config.templates.whenAssetQuery) {
- this.ruleCondition.assets = JSON.parse(JSON.stringify(this.config.templates.whenAssetQuery));
- } else {
- this.ruleCondition.assets = {};
- }
-
- if (!this.ruleCondition.assets!.types || this.ruleCondition.assets!.types.length === 0) {
- this.ruleCondition.assets!.types = [{
- predicateType: "string",
- match: AssetQueryMatch.EXACT
- }];
- }
-
- this.ruleCondition.assets!.types[0].value = value;
- this.dispatchEvent(new OrRulesEditorRuleChangedEvent());
+ updateRuleConditionType(this.ruleCondition, value, this.config);
+ this.dispatchEvent(new OrRulesJsonRuleChangedEvent());
this.requestUpdate();
}
}
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
new file mode 100644
index 000000000..18788bb68
--- /dev/null
+++ b/ui/component/or-rules/src/json-viewer/or-rule-json-viewer.ts
@@ -0,0 +1,392 @@
+import {customElement, html, LitElement, property, TemplateResult, css} from "lit-element";
+import {
+ getAssetDescriptors,
+ getAssetTypeFromQuery,
+ OrRulesRuleChangedEvent,
+ OrRulesRuleUnsupportedEvent,
+ RulesConfig,
+ RuleView
+} from "../index";
+import {
+ AssetDescriptor,
+ AssetQuery,
+ AssetQueryOperator as AQO,
+ JsonRule,
+ JsonRulesetDefinition,
+ LogicGroup,
+ RuleActionTarget,
+ RuleActionUnion,
+ RuleCondition,
+ RulesetUnion,
+ ValuePredicateUnion
+} from "@openremote/model";
+import {Util} from "@openremote/core";
+import "./or-rule-when";
+import "./or-rule-then-otherwise";
+import "@openremote/or-panel";
+import i18next from "i18next";
+import {translate} from "@openremote/or-translate";
+
+export class OrRulesJsonRuleChangedEvent extends CustomEvent<void> {
+
+ public static readonly NAME = "or-rules-json-rule-changed";
+
+ constructor() {
+ super(OrRulesJsonRuleChangedEvent.NAME, {
+ bubbles: true,
+ composed: true
+ });
+ }
+}
+
+declare global {
+ export interface HTMLElementEventMap {
+ [OrRulesJsonRuleChangedEvent.NAME]: OrRulesJsonRuleChangedEvent;
+ }
+}
+
+const style = css`
+ :host {
+ display: flex;
+ width: 100%;
+ }
+
+ :host > * {
+ flex: 1;
+ }
+`;
+
+@customElement("or-rule-json-viewer")
+export class OrRuleJsonViewer extends translate(i18next)(LitElement) implements RuleView {
+
+ static get styles() {
+ return style;
+ }
+
+ @property({attribute: false})
+ public readonly?: boolean;
+
+ @property({attribute: false})
+ public config?: RulesConfig;
+
+ @property({attribute: false})
+ protected _ruleset!: RulesetUnion;
+
+ protected _rule!: JsonRule;
+ protected _assetDescriptors?: AssetDescriptor[];
+ protected _whenAssetDescriptors?: AssetDescriptor[];
+ protected _actionAssetDescriptors?: AssetDescriptor[];
+
+ constructor() {
+ super();
+ this.addEventListener(OrRulesJsonRuleChangedEvent.NAME, this._onJsonRuleChanged);
+ }
+
+ public set ruleset(ruleset: RulesetUnion) {
+ this._ruleset = ruleset;
+
+ if (!ruleset.rules) {
+ // New ruleset so start a new rule
+ this._rule = {};
+ } else {
+ try {
+ const rules = JSON.parse(ruleset.rules) as JsonRulesetDefinition;
+ if (!rules.rules || rules.rules.length > 1) {
+ this.dispatchEvent(new OrRulesRuleUnsupportedEvent());
+ return;
+ }
+ this._rule = rules.rules[0];
+ this.requestUpdate();
+ } catch (e) {
+ console.error("Invalid JSON rules, failed to parse: " + e);
+ this.dispatchEvent(new OrRulesRuleUnsupportedEvent());
+ }
+ }
+ }
+
+ protected render(): TemplateResult | void {
+
+ if (!this._rule) {
+ return html``;
+ }
+
+ const targetTypeMap = this.getTargetTypeMap();
+ const whenDescriptors = this.getAssetDescriptors(false);
+ const actionDescriptors = this.getAssetDescriptors(true);
+
+ return html`
+ <div class="section-container">
+ <or-rule-when .rule="${this._rule}" .config="${this.config}" .assetDescriptors="${whenDescriptors}" ?readonly="${this.readonly}"></or-rule-when>
+ </div>
+
+ <div class="section-container">
+ <or-rule-then-otherwise .rule="${this._rule}" .config="${this.config}" .targetTypeMap="${targetTypeMap}" .assetDescriptors="${actionDescriptors}" ?readonly="${this.readonly}"></or-rule-then-otherwise>
+ </div>
+ `;
+ }
+
+ protected getAssetDescriptors(useActionConfig: boolean) {
+ if (useActionConfig) {
+ if (this._actionAssetDescriptors) {
+ return this._actionAssetDescriptors;
+ }
+ this._actionAssetDescriptors = getAssetDescriptors(this.config, useActionConfig);
+ return this._actionAssetDescriptors;
+ }
+
+ if (this._whenAssetDescriptors) {
+ return this._whenAssetDescriptors;
+ }
+
+ this._whenAssetDescriptors = getAssetDescriptors(this.config, useActionConfig);
+ return this._whenAssetDescriptors;
+ }
+
+ protected getTargetTypeMap(): [string, string?][] {
+ if (!this._rule.when) {
+ return [];
+ }
+
+ return this.getTypeAndTagsFromGroup(this._rule.when);
+ }
+
+ protected getTypeAndTagsFromGroup(group: LogicGroup<RuleCondition>): [string, string?][] {
+ if (!group) {
+ return [];
+ }
+
+ let typesAndTags: [string, string?][] = [];
+
+ if (group.items) {
+ for (const condition of group.items) {
+ const type = getAssetTypeFromQuery(condition.assets);
+ if (type) {
+ typesAndTags.push([type, condition.tag]);
+ }
+ }
+ }
+
+ if (group.groups) {
+ for (const condition of group.groups) {
+ typesAndTags = typesAndTags.concat(this.getTypeAndTagsFromGroup(condition));
+ }
+ }
+
+ return typesAndTags;
+ }
+
+ public beforeSave() {
+ if (!this._rule) {
+ return;
+ }
+
+ this._rule.name = this.ruleset.name;
+
+ const jsonRules: JsonRulesetDefinition = {
+ rules: [this._rule]
+ };
+
+ this.ruleset.rules = JSON.stringify(jsonRules);
+ }
+
+ public validate(): boolean {
+
+ const rule = this._rule;
+
+ if (!rule) {
+ return false;
+ }
+
+ if (!rule.when) {
+ return false;
+ }
+
+ if (!rule.then || rule.then.length === 0) {
+ return false;
+ }
+
+ if (!this._validateConditionGroup(rule.when)) {
+ return false;
+ }
+
+ if (!this._validateRuleActions(rule, rule.then)) {
+ return false;
+ }
+
+ // TODO: Validate other rule sections
+ return true;
+ }
+
+ protected _onJsonRuleChanged() {
+ let valid = this.validate();
+ this.dispatchEvent(new OrRulesRuleChangedEvent(valid));
+ }
+
+ protected _validateConditionGroup(group: LogicGroup<RuleCondition>): boolean {
+ if ((!group.items || group.items.length === 0) && (!group.groups || group.groups.length === 0)) {
+ return false;
+ }
+
+ if (group.items) {
+ for (const condition of group.items) {
+ if (!condition.assets && !condition.datetime && !condition.timer) {
+ return false;
+ }
+
+ if (condition.assets && !this._validateAssetQuery(condition.assets, true, false)) {
+ return false;
+ }
+
+ if (condition.datetime && !this._validateValuePredicate(condition.datetime)) {
+ return false;
+ }
+
+ if (condition.timer && !Util.isTimeDuration(condition.timer)) {
+ return false;
+ }
+ }
+ }
+
+ if (group.groups) {
+ for (const childGroup of group.groups) {
+ if (!this._validateConditionGroup(childGroup)) {
+ return false;
+ }
+ }
+ }
+
+ return true;
+ }
+
+ protected _validateRuleActions(rule: JsonRule, actions?: RuleActionUnion[]): boolean {
+ if (!actions) {
+ return true;
+ }
+
+ for (const action of actions) {
+ switch (action.action) {
+ case "wait":
+ if (!action.millis) {
+ return false;
+ }
+ break;
+ case "write-attribute":
+ if (!action.attributeName) {
+ return false;
+ }
+ if (!this._validateAssetTarget(rule, action.target)) {
+ return false;
+ }
+ break;
+ case "notification":
+ // TODO: validate notification rule action
+ break;
+ case "update-attribute":
+ if (!action.attributeName) {
+ return false;
+ }
+ if (!action.updateAction) {
+ return false;
+ }
+ if (!this._validateAssetTarget(rule, action.target)) {
+ return false;
+ }
+ break;
+ default:
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ protected _validateAssetTarget(rule: JsonRule, target?: RuleActionTarget): boolean {
+ if (!target) {
+ return true;
+ }
+
+ if (!target.assets && !target.ruleConditionTag) {
+ return false;
+ }
+
+ if (target.assets) {
+ return this._validateAssetQuery(target.assets, false, false);
+ }
+
+ if (target.matchedAssets) {
+ return this._validateAssetQuery(target.matchedAssets, false, true);
+ }
+
+ const typesAndTags = this.getTypeAndTagsFromGroup(rule.when!);
+ if (typesAndTags.findIndex((typeAndTag) => target.ruleConditionTag === typeAndTag[1]) < 0) {
+ return false;
+ }
+
+ return true;
+ }
+
+ protected _validateAssetQuery(query: AssetQuery, isWhen: boolean, isMatchedAssets: boolean): boolean {
+
+ if (!query.types || query.types.length === 0) {
+ return false;
+ }
+
+ if (isWhen) {
+ if (!query.attributes || !query.attributes.items || query.attributes.items.length === 0) {
+ return false;
+ }
+ } else {
+ if (!query.ids || query.ids.length === 0 && !isMatchedAssets) {
+ return false;
+ }
+ }
+
+ if (query.types) {
+ for (const type of query.types) {
+ if (!type.value || !type.predicateType) {
+ return false;
+ }
+ }
+ }
+
+ if (query.attributes && query.attributes.items) {
+ for (const attribute of query.attributes.items) {
+ if (!attribute.name || !attribute.name.match || !attribute.name.value) {
+ return false;
+ }
+ if (!attribute.value || !this._validateValuePredicate(attribute.value)) {
+ return false;
+ }
+ }
+ }
+
+ return true;
+ }
+
+ protected _validateValuePredicate(valuePredicate: ValuePredicateUnion): boolean {
+ switch (valuePredicate.predicateType) {
+ case "string":
+ return valuePredicate.match !== undefined && valuePredicate.value !== undefined;
+ case "boolean":
+ return valuePredicate.value !== undefined;
+ case "string-array":
+ return valuePredicate.predicates !== undefined && valuePredicate.predicates.length > 0 && valuePredicate.predicates.findIndex((p) => !p.match || p.value === undefined) === 0;
+ case "datetime":
+ case "number":
+ return valuePredicate.operator !== undefined && valuePredicate.value !== undefined && (valuePredicate.operator !== AQO.BETWEEN || valuePredicate.rangeValue !== undefined);
+ case "radial":
+ return valuePredicate.radius !== undefined && valuePredicate.lat !== undefined && valuePredicate.lng !== undefined;
+ case "rect":
+ return valuePredicate.lngMax !== undefined && valuePredicate.latMax !== undefined && valuePredicate.lngMin !== undefined && valuePredicate.latMin !== undefined;
+ case "object-value-key":
+ return valuePredicate.key !== undefined;
+ case "array":
+ return (valuePredicate.index && !valuePredicate.value) || valuePredicate.value || valuePredicate.lengthEquals || valuePredicate.lengthLessThan || valuePredicate.lengthGreaterThan;
+ case "value-empty":
+ case "value-not-empty":
+ return true;
+ default:
+ return false;
+ }
+ }
+}
\ No newline at end of file
diff --git a/ui/component/or-rules-editor/src/or-rule-then-otherwise.ts b/ui/component/or-rules/src/json-viewer/or-rule-then-otherwise.ts
similarity index 79%
rename from ui/component/or-rules-editor/src/or-rule-then-otherwise.ts
rename to ui/component/or-rules/src/json-viewer/or-rule-then-otherwise.ts
index 9eeebddd8..05f91c554 100644
--- a/ui/component/or-rules-editor/src/or-rule-then-otherwise.ts
+++ b/ui/component/or-rules/src/json-viewer/or-rule-then-otherwise.ts
@@ -1,25 +1,27 @@
import {css, customElement, html, LitElement, property, TemplateResult} from "lit-element";
-import {buttonStyle} from "./style";
+import {buttonStyle} from "../style";
import "./or-rule-asset-query";
import {
ActionType,
getAssetTypeFromQuery,
- getButtonWithMenuTemplate,
- OrRulesEditorRuleChangedEvent,
RulesConfig
-} from "./index";
+} from "../index";
+import {
+ OrRulesJsonRuleChangedEvent
+} from "./or-rule-json-viewer";
import {AssetDescriptor, JsonRule, RuleActionUnion} from "@openremote/model";
import i18next from "i18next";
import {InputType} from "@openremote/or-input";
-import {Menu, MenuItem} from "@openremote/or-mwc-components/dist/or-mwc-menu";
+import {MenuItem} from "@openremote/or-mwc-components/dist/or-mwc-menu";
import {getAssetDescriptorIconTemplate} from "@openremote/or-icon";
import {AssetModelUtil} from "@openremote/core";
import "./or-rule-action-attribute";
+import {getContentWithMenuTemplate} from "@openremote/or-mwc-components/dist/or-mwc-menu";
const NOTIFICATION_COLOR = "4B87EA";
const WAIT_COLOR = "EACC54";
-function getActionTypesMenu(config?: RulesConfig, assetDescriptors?: AssetDescriptor[]): Menu {
+function getActionTypesMenu(config?: RulesConfig, assetDescriptors?: AssetDescriptor[]): MenuItem[] {
let addAssetTypes = true;
let addWait = true;
@@ -31,12 +33,10 @@ function getActionTypesMenu(config?: RulesConfig, assetDescriptors?: AssetDescri
addNotification = config.controls.allowedActionTypes.indexOf(ActionType.NOTIFICATION) >= 0;
}
- const menu: Menu = {
- items: []
- };
+ const menu: MenuItem[] = [];
if (addAssetTypes && assetDescriptors) {
- menu.items.push(...assetDescriptors.map((ad) => {
+ menu.push(...assetDescriptors.map((ad) => {
const content = html`
${getAssetDescriptorIconTemplate(ad)}
&nbsp;&nbsp;<span style="white-space: nowrap; text-transform: capitalize">${i18next.t(ad.name!, {defaultValue: ad.name!.replace(/_/g, " ").toLowerCase()})}</span>
@@ -50,7 +50,7 @@ function getActionTypesMenu(config?: RulesConfig, assetDescriptors?: AssetDescri
<or-icon style="--or-icon-fill: #${NOTIFICATION_COLOR}" icon="email"></or-icon>
<span style="text-transform: capitalize">&nbsp;<or-translate value="notification"></or-translate></span>
`;
- menu.items.push({content: content, value: ActionType.NOTIFICATION} as MenuItem);
+ menu.push({content: content, value: ActionType.NOTIFICATION} as MenuItem);
}
if (addWait) {
@@ -58,7 +58,7 @@ function getActionTypesMenu(config?: RulesConfig, assetDescriptors?: AssetDescri
<or-icon style="--or-icon-fill: #${WAIT_COLOR}" icon="timer"></or-icon>
<span style="text-transform: capitalize">&nbsp;<or-translate value="wait"></or-translate></span>
`;
- menu.items.push({content: content, value: ActionType.WAIT} as MenuItem);
+ menu.push({content: content, value: ActionType.WAIT} as MenuItem);
}
return menu;
@@ -78,6 +78,7 @@ const style = css`
.rule-action {
display: flex;
margin: 10px 0;
+ align-items: center;
}
.rule-action-action {
@@ -98,6 +99,15 @@ const style = css`
#type-selector {
margin-top: 10px;
+ }
+
+ .add-button-wrapper {
+ display: flex;
+ align-items: center;
+ }
+
+ .add-button-wrapper > * {
+ margin: 0 5px;
}
`;
@@ -158,8 +168,12 @@ class OrRuleThenOtherwise extends LitElement {
}
typeTemplate = html`
- <div style="display: table; height: 100%; --or-input-color: #${buttonColor}">
- ${getButtonWithMenuTemplate(getActionTypesMenu(this.config, this.assetDescriptors), buttonIcon || "", action.action, (value: string) => this.setActionType(actions, action, value))}
+ <div style="--or-input-text-color: #${buttonColor}">
+ ${getContentWithMenuTemplate(
+ html`<or-input class="menu-button" type="${InputType.BUTTON}" .icon="${buttonIcon || ""}"></or-input>`,
+ getActionTypesMenu(this.config, this.assetDescriptors),
+ action.action,
+ (value: string) => this.setActionType(actions, action, value))}
</div>
`;
}
@@ -197,7 +211,14 @@ class OrRuleThenOtherwise extends LitElement {
${!this.rule.then ? `` : this.rule.then.map((action: RuleActionUnion) => this.ruleActionTemplate(this.rule.then!, action))}
${this.thenAllowAdd ? html`
- <or-input type="${InputType.BUTTON}" .label="${i18next.t("rulesEditorAddAction")}" @click="${() => this.addAction()}"></or-input>
+ <span class="add-button-wrapper">
+ ${getContentWithMenuTemplate(
+ html`<or-input class="menu-button" type="${InputType.BUTTON}" icon="plus"></or-input>`,
+ getActionTypesMenu(this.config, this.assetDescriptors),
+ undefined,
+ (value: string) => this.addAction(value))}
+ <span>${i18next.t("rulesEditorAddAction")}</span>
+ </span>
` : ``}
</or-panel>
</div>
@@ -271,7 +292,7 @@ class OrRuleThenOtherwise extends LitElement {
const index = actions.indexOf(action);
actions[index] = {...action};
- this.dispatchEvent(new OrRulesEditorRuleChangedEvent());
+ this.dispatchEvent(new OrRulesJsonRuleChangedEvent());
this.requestUpdate();
}
@@ -283,12 +304,12 @@ class OrRuleThenOtherwise extends LitElement {
const index = this.rule.then.indexOf(action);
if (index >= 0) {
this.rule.then.splice(index, 1);
- this.dispatchEvent(new OrRulesEditorRuleChangedEvent());
+ this.dispatchEvent(new OrRulesJsonRuleChangedEvent());
this.requestUpdate();
}
}
- protected addAction(otherwise?: boolean) {
+ protected addAction(type: string | undefined, otherwise?: boolean) {
if (!this.rule) {
return;
@@ -299,27 +320,32 @@ class OrRuleThenOtherwise extends LitElement {
action: "write-attribute"
};
let template: RuleActionUnion | undefined;
+ let templateConfig = this.config && this.config.json ? this.config.json : undefined;
if (!otherwise) {
if (!this.rule.then) {
this.rule.then = [];
}
actionArray = this.rule.then;
- template = this.config && this.config.templates && this.config.templates.then ? this.config.templates.then : undefined;
+ template = templateConfig && templateConfig.then ? templateConfig.then : undefined;
} else {
if (!this.rule.otherwise) {
this.rule.otherwise = [];
}
actionArray = this.rule.otherwise;
- template = this.config && this.config.templates && this.config.templates.otherwise ? this.config.templates.otherwise : undefined;
+ template = templateConfig && templateConfig.otherwise ? templateConfig.otherwise : undefined;
}
if (template) {
newAction = JSON.parse(JSON.stringify(template)) as RuleActionUnion;
}
+ if (type) {
+ this.setActionType(actionArray, newAction, type);
+ }
+
actionArray.push(newAction);
- this.dispatchEvent(new OrRulesEditorRuleChangedEvent());
+ this.dispatchEvent(new OrRulesJsonRuleChangedEvent());
this.requestUpdate();
}
}
diff --git a/ui/component/or-rules-editor/src/or-rule-when.ts b/ui/component/or-rules/src/json-viewer/or-rule-when.ts
similarity index 71%
rename from ui/component/or-rules-editor/src/or-rule-when.ts
rename to ui/component/or-rules/src/json-viewer/or-rule-when.ts
index 74a8520a2..9f66f2197 100644
--- a/ui/component/or-rules-editor/src/or-rule-when.ts
+++ b/ui/component/or-rules/src/json-viewer/or-rule-when.ts
@@ -1,10 +1,13 @@
import {css, customElement, html, LitElement, property, PropertyValues, TemplateResult} from "lit-element";
-import {AssetDescriptor, JsonRule, LogicGroup, LogicGroupOperator, RuleCondition, AssetType} from "@openremote/model";
-import {OrRulesEditorRuleChangedEvent, RulesConfig} from "./index";
-import {buttonStyle} from "./style";
+import {AssetDescriptor, AssetType, JsonRule, LogicGroup, LogicGroupOperator, RuleCondition} from "@openremote/model";
+import {OrRulesRuleUnsupportedEvent, RulesConfig} from "../index";
+import {buttonStyle} from "../style";
import "./or-rule-condition";
import i18next from "i18next";
import {InputType} from "@openremote/or-input";
+import {OrRulesJsonRuleChangedEvent} from "./or-rule-json-viewer";
+import {getWhenTypesMenu, updateRuleConditionType} from "./or-rule-condition";
+import {getContentWithMenuTemplate} from "@openremote/or-mwc-components/dist/or-mwc-menu";
// language=CSS
const style = css`
@@ -63,6 +66,15 @@ const style = css`
height: 24px;
transform: translate(50%, -50%);
}
+
+ .add-button-wrapper {
+ display: flex;
+ align-items: center;
+ }
+
+ .add-button-wrapper > * {
+ margin: 0 5px;
+ }
`;
@customElement("or-rule-when")
@@ -91,7 +103,6 @@ class OrRuleWhen extends LitElement {
const showAddCondition = !this.readonly && (!this.config || !this.config.controls || this.config.controls.hideWhenAddCondition !== true);
const showRemoveCondition = !this.readonly && group.items && group.items.length > 1;
const showRemoveGroup = !this.readonly;
- const showAddGroup = !this.readonly && (!this.config || !this.config.controls || this.config.controls.hideWhenAddGroup !== true);
let wrapper: (content: TemplateResult, item: LogicGroup<RuleCondition> | RuleCondition, parent: LogicGroup<RuleCondition>, isGroup: boolean, isFirst: boolean) => TemplateResult;
@@ -157,18 +168,16 @@ class OrRuleWhen extends LitElement {
isFirst = false;
}
- if (isTopLevel && showAddGroup) {
- addTemplate = html`
- <or-panel>
- <or-input type="${InputType.BUTTON}" icon="plus" @click="${() => this.addGroup(group)}"></or-input>
- <strong>${i18next.t(isFirst ? "when": "orWhen")}...</strong>
- </or-panel>
- `;
- }
-
if (!isTopLevel && showAddCondition) {
addTemplate = html`
- <or-input type="${InputType.BUTTON}" .label="${i18next.t("rulesEditorAddCondition")}" @click="${() => this.addCondition(group)}"></or-input>
+ <span class="add-button-wrapper">
+ ${getContentWithMenuTemplate(
+ html`<or-input type="${InputType.BUTTON}" icon="plus"></or-input>`,
+ getWhenTypesMenu(this.config, this.assetDescriptors),
+ undefined,
+ (value: string) => this.addCondition(group, value))}
+ <span>${i18next.t("rulesEditorAddCondition")}</span>
+ </span>
`;
}
@@ -207,10 +216,25 @@ class OrRuleWhen extends LitElement {
return html``;
}
+ const showAddGroup = !this.readonly && (!this.config || !this.config.controls || this.config.controls.hideWhenAddGroup !== true);
+
return html`
<div>
- ${this.ruleGroupTemplate(this.rule.when!)}
+ ${this.ruleGroupTemplate(this.rule.when)}
</div>
+
+ ${!showAddGroup ? `` : html`
+ <or-panel>
+ <span class="add-button-wrapper">
+ ${getContentWithMenuTemplate(
+ html`<or-input type="${InputType.BUTTON}" icon="plus"></or-input>`,
+ getWhenTypesMenu(this.config, this.assetDescriptors),
+ undefined,
+ (value: string) => this.addGroup(this.rule!.when!, value))}
+ <strong>${i18next.t(this.rule.when.groups && this.rule.when.groups.length === 0 ? "when": "orWhen")}...</strong>
+ </span>
+ </or-panel>
+ `}
`;
}
@@ -250,35 +274,45 @@ class OrRuleWhen extends LitElement {
return true;
}
- private addGroup(parent: LogicGroup<RuleCondition>) {
+ private addGroup(parent: LogicGroup<RuleCondition>, type: string | undefined) {
if (!this.rule || !this.rule.when || parent !== this.rule.when) {
return;
}
- let newGroup: LogicGroup<RuleCondition> = {};
+ let newGroup: LogicGroup<RuleCondition> = {
+ operator: LogicGroupOperator.AND
+ };
- if (this.config && this.config.templates && this.config.templates.whenGroup) {
- newGroup = JSON.parse(JSON.stringify(this.config.templates.whenGroup)) as LogicGroup<RuleCondition>;
+ if (this.config && this.config.json && this.config.json.whenGroup) {
+ newGroup = JSON.parse(JSON.stringify(this.config.json.whenGroup)) as LogicGroup<RuleCondition>;
+ }
+
+ if (newGroup.operator !== LogicGroupOperator.AND) {
+ console.warn("JSON rules editor doesn't support top level logic group with type OR");
+ this.dispatchEvent(new OrRulesRuleUnsupportedEvent());
+ return;
+ }
+
+ if (newGroup.groups && newGroup.groups.length > 0) {
+ console.warn("JSON rules editor doesn't support multiple top level logic groups");
+ this.dispatchEvent(new OrRulesRuleUnsupportedEvent());
+ return;
}
- // Force to AND as this is what the editor supports
- newGroup.operator = LogicGroupOperator.AND;
- // Clear any child groups
newGroup.groups = undefined;
// Add an item if none exist
if (!newGroup.items || newGroup.items!.length === 0) {
- this.addCondition(newGroup, true);
+ this.addCondition(newGroup, type, true);
}
- const group = parent as LogicGroup<RuleCondition>;
- if (!group.groups) {
- group.groups = [];
+ if (!parent.groups) {
+ parent.groups = [];
}
- group.groups.push(newGroup);
+ parent.groups.push(newGroup);
- this.dispatchEvent(new OrRulesEditorRuleChangedEvent());
+ this.dispatchEvent(new OrRulesJsonRuleChangedEvent());
this.requestUpdate();
}
@@ -298,13 +332,13 @@ class OrRuleWhen extends LitElement {
}
if (removed) {
- this.dispatchEvent(new OrRulesEditorRuleChangedEvent());
+ this.dispatchEvent(new OrRulesJsonRuleChangedEvent());
this.requestUpdate();
}
}
}
- private addCondition(parent: LogicGroup<RuleCondition>, silent?: boolean) {
+ private addCondition(parent: LogicGroup<RuleCondition>, type: string | undefined, silent?: boolean) {
if (!parent) {
return;
}
@@ -313,27 +347,17 @@ class OrRuleWhen extends LitElement {
parent.items = [];
}
- let newTrigger: RuleCondition = {};
-
- if (this.config && this.config.templates && this.config.templates.whenCondition) {
- newTrigger = JSON.parse(JSON.stringify(this.config.templates.whenCondition)) as RuleCondition;
- }
+ let newCondition: RuleCondition = {};
- // Populate the condition with something to help the UI
- if (!newTrigger.timer && !newTrigger.datetime && !newTrigger.assets) {
- newTrigger.assets = {
- types: [
- {
- predicateType: "string",
- value: AssetType.THING.type
- }
- ]
- };
+ if (this.config && this.config.json && this.config.json.whenCondition) {
+ newCondition = JSON.parse(JSON.stringify(this.config.json.whenCondition)) as RuleCondition;
+ } else {
+ updateRuleConditionType(newCondition, type || AssetType.THING.type, this.config);
}
- parent.items.push(newTrigger);
+ parent.items.push(newCondition);
if (!silent) {
- this.dispatchEvent(new OrRulesEditorRuleChangedEvent());
+ this.dispatchEvent(new OrRulesJsonRuleChangedEvent());
this.requestUpdate();
}
}
diff --git a/ui/component/or-rules-editor/src/or-rule-list.ts b/ui/component/or-rules/src/or-rule-list.ts
similarity index 65%
rename from ui/component/or-rules-editor/src/or-rule-list.ts
rename to ui/component/or-rules/src/or-rule-list.ts
index 14ef8cc8e..dffb738d8 100644
--- a/ui/component/or-rules-editor/src/or-rule-list.ts
+++ b/ui/component/or-rules/src/or-rule-list.ts
@@ -1,58 +1,40 @@
-import {customElement, html, LitElement, property, PropertyValues, query, TemplateResult, css} from "lit-element";
+import {css, customElement, html, LitElement, property, PropertyValues, query, TemplateResult} from "lit-element";
import {JsonRule, RuleCondition, RulesetLang, Tenant, TenantRuleset} from "@openremote/model";
import "@openremote/or-translate";
import manager, {EventCallback, OREvent} from "@openremote/core";
import moment from "moment";
+import "@openremote/or-input";
import {InputType, OrInputChangedEvent} from "@openremote/or-input";
import {style as OrAssetTreeStyle} from "@openremote/or-asset-tree";
import {
- OrRulesEditorRequestAddEvent,
- OrRulesEditorRequestCopyEvent,
- OrRulesEditorRequestDeleteEvent,
- OrRulesEditorRequestSelectEvent,
- OrRulesEditorSelectionChangedEvent,
+ OrRulesRequestAddEvent,
+ OrRulesRequestCopyEvent,
+ OrRulesRequestDeleteEvent,
+ OrRulesRequestSelectEvent,
+ OrRulesSelectionChangedEvent,
RequestEventDetail,
- RulesetNode
-} from "./index";
+ RulesConfig,
+ RulesetNode} from "./index";
+import "@openremote/or-mwc-components/dist/or-mwc-menu";
+import {MenuItem} from "@openremote/or-mwc-components/dist/or-mwc-menu";
+import {translate} from "@openremote/or-translate";
+import i18next from "i18next";
+import {getContentWithMenuTemplate} from "../../or-mwc-components/dist/or-mwc-menu";
// language=CSS
const style = css`
:host {
- overflow: auto;
flex-grow: 1;
- font-size: var(--internal-or-rules-editor-list-text-size);
+ font-size: var(--internal-or-rules-list-text-size);
+
+ /*Override asset tree styles*/
+ --internal-or-asset-tree-header-height: var(--internal-or-rules-list-header-height);
}
#wrapper[data-disabled] {
opacity: 0.3;
pointer-events: none;
}
-
- .d-flex {
- display: -webkit-box;
- display: -moz-box;
- display: -ms-flexbox;
- display: -webkit-flex;
- display: flex;
- }
-
- .flex {
- -webkit-box-flex: 1;
- -moz-box-flex: 1;
- -webkit-flex: 1;
- -ms-flex: 1;
- flex: 1;
- }
-
- .list-title {
- display: block;
- padding: 30px 30px 5px 20px;
- text-transform: uppercase;
- /*color: var(, #808080);*/
- font-size:14px;
- font-weight: bold;
- text-align: left;
- }
.list-item {
text-decoration: none;
@@ -64,13 +46,13 @@ const style = css`
}
.list-item:hover {
- border-left-color: var(--internal-or-rules-editor-list-selected-color);
- background-color: var(--internal-or-rules-editor-list-selected-color);
+ border-left-color: var(--internal-or-rules-list-selected-color);
+ background-color: var(--internal-or-rules-list-selected-color);
}
.list-item[selected] {
- border-left-color: var(--internal-or-rules-editor-button-color);
- background-color: var(--internal-or-rules-editor-list-selected-color);
+ border-left-color: var(--internal-or-rules-button-color);
+ background-color: var(--internal-or-rules-list-selected-color);
opacity: 1;
}
@@ -86,7 +68,7 @@ const style = css`
}
.bg-red {
- background-color: red
+ background-color: red;
}
.bg-blue {
@@ -99,11 +81,19 @@ const style = css`
`;
@customElement("or-rule-list")
-export class OrRulesList extends LitElement {
+export class OrRuleList extends translate(i18next)(LitElement) {
+
+ public static DEFAULT_ALLOWED_LANGUAGES = [RulesetLang.JSON, RulesetLang.GROOVY, RulesetLang.JAVASCRIPT];
+
+ @property({type: Object})
+ public config?: RulesConfig;
@property({type: String})
public realm?: string;
+ @property({type: Boolean})
+ public readonly: boolean = false;
+
@property({type: Boolean})
public disabled: boolean = false;
@@ -116,18 +106,18 @@ export class OrRulesList extends LitElement {
@property({type: String})
public sortBy?: string;
+ @property({type: String})
+ public language?: RulesetLang;
+
@property({attribute: false})
protected _realms?: Tenant[];
@property({attribute: false})
protected _nodes?: RulesetNode[];
- @property()
+ @property({attribute: false})
protected _showLoading: boolean = true;
- @query("#sort-menu")
- protected _sortMenu!: HTMLDivElement;
-
protected _selectedNodes: RulesetNode[] = [];
protected _initCallback?: EventCallback;
protected _ready = false;
@@ -143,6 +133,19 @@ export class OrRulesList extends LitElement {
this._nodes = undefined;
}
+ protected get _allowedLanguages(): RulesetLang[] | undefined {
+ return this.config && this.config.controls && this.config.controls.allowedLanguages ? this.config.controls.allowedLanguages : OrRuleList.DEFAULT_ALLOWED_LANGUAGES;
+ }
+
+ protected _updateLanguage() {
+ const rulesetLangs = this._allowedLanguages;
+ if (!rulesetLangs || rulesetLangs.length === 0) {
+ this.language = undefined;
+ } else if (!this.language || rulesetLangs.indexOf(this.language) < 0) {
+ this.language = rulesetLangs[0];
+ }
+ }
+
protected _onReady() {
this._ready = true;
this._loadRealms();
@@ -164,17 +167,15 @@ export class OrRulesList extends LitElement {
} else {
this._onReady();
}
-
- this.addEventListener("click", (evt) => {
- if (this._sortMenu.hasAttribute("data-visible") && !this._sortMenu.contains(evt.target as Node)) {
- this._sortMenu.toggleAttribute("data-visible");
- }
- });
}
- protected shouldUpdate(_changedProperties: PropertyValues): boolean {
+ public shouldUpdate(_changedProperties: PropertyValues): boolean {
const result = super.shouldUpdate(_changedProperties);
+ if (_changedProperties.has("language")) {
+ this._updateLanguage();
+ }
+
if (manager.ready) {
if (_changedProperties.has("realm")) {
this._nodes = undefined;
@@ -190,7 +191,7 @@ export class OrRulesList extends LitElement {
}
if (_changedProperties.has("sortBy")) {
- OrRulesList._updateSort(this._nodes!, this._getSortFunction());
+ OrRuleList._updateSort(this._nodes!, this._getSortFunction());
}
}
@@ -199,31 +200,52 @@ export class OrRulesList extends LitElement {
protected render() {
+ const realm = this._getRealm();
+
+ if (this.realm !== realm) {
+ this._onRealmChanged(realm);
+ }
+
+ if (!this.language) {
+ this._updateLanguage();
+ }
+
+ const allowedLanguages = this._allowedLanguages;
+ let addTemplate: TemplateResult | string = ``;
+
+ if (!this._isReadonly()) {
+ if (allowedLanguages && allowedLanguages.length > 1) {
+ addTemplate = getContentWithMenuTemplate(
+ html`<or-input type="${InputType.BUTTON}" icon="plus"></or-input>`,
+ allowedLanguages.map((l) => {
+ return {value: l, content: html`<span>${l}</span>`} as MenuItem;
+ }),
+ this.language,
+ (v) => this._onAddClicked(v as RulesetLang));
+ } else {
+ addTemplate = html`<or-input type="${InputType.BUTTON}" icon="plus" @click="${() => this._onAddClicked(this.language!)}"></or-input>`;
+ }
+ }
+
return html`
<div id="wrapper" ?data-disabled="${this.disabled}">
<div id="header">
<div id="title-container">
<or-translate id="title" value="rule_plural"></or-translate>
- ${manager.isSuperUser() ? html `<or-input id="realm-picker" type="${InputType.SELECT}" .value="${this._getRealm()}" .options="${this._realms ? this._realms.map((tenant) => [tenant.realm, tenant.displayName]) : []}" @or-input-changed="${(evt: OrInputChangedEvent) => this._onRealmChanged(evt)}"></or-input>` : ``}
+ ${manager.isSuperUser() ? html `<or-input id="realm-picker" type="${InputType.SELECT}" .value="${this._getRealm()}" .options="${this._realms ? this._realms.map((tenant) => [tenant.realm, tenant.displayName]) : []}" @or-input-changed="${(evt: OrInputChangedEvent) => this._onRealmChanged(evt.detail.value)}"></or-input>` : ``}
</div>
<div id="header-btns">
-
- <button style="display:none;" ?hidden="${!manager.hasRole("write:rules") || !this.selectedIds || this.selectedIds.length === 0}" @click="${() => this._onCopyClicked()}"><or-icon icon="content-copy"></or-icon></button>
- <button ?hidden="${!manager.hasRole("write:rules") || !this.selectedIds || this.selectedIds.length === 0}" @click="${() => this._onDeleteClicked()}"><or-icon icon="delete"></or-icon></button>
- <button ?hidden="${!manager.hasRole("write:rules")}" @click="${() => this._onAddClicked()}"><or-icon icon="plus"></or-icon></button>
- <button hidden @click="${() => this._onSearchClicked()}"><or-icon icon="magnify"></or-icon></button>
- <button @click="${() => this._onSortClicked()}"><or-icon icon="sort-variant"></or-icon></button>
- <div class="modal-container">
- <div class="modal" id="sort-menu">
- <div class="modal-content">
- <ul>
- <li @click="${() => this.sortBy = "name"}" ?data-selected="${!this.sortBy || this.sortBy === "name"}"><or-icon icon="check"></or-icon><or-translate value="name"></or-translate></li>
- <li @click="${() => this.sortBy = "created"}" ?data-selected="${this.sortBy === "created"}"><or-icon icon="check"></or-icon><or-translate value="creationDate"></or-translate></li>
- </ul>
- </div>
- </div>
- </div>
+ <or-input ?hidden="${this._isReadonly() || !this.selectedIds || this.selectedIds.length === 0}" type="${InputType.BUTTON}" icon="content-copy" @click="${() => this._onCopyClicked()}"></or-input>
+ <or-input ?hidden="${this._isReadonly() || !this.selectedIds || this.selectedIds.length === 0}" type="${InputType.BUTTON}" icon="delete" @click="${() => this._onDeleteClicked()}"></or-input>
+ ${addTemplate}
+ <or-input hidden type="${InputType.BUTTON}" icon="magnify" @click="${() => this._onSearchClicked()}"></or-input>
+
+ ${getContentWithMenuTemplate(
+ html`<or-input type="${InputType.BUTTON}" icon="sort-variant"></or-input>`,
+ ["name", "createdOn"].map((sort) => {return {value: sort, content: html`<span>${i18next.t(sort)}</span>`} as MenuItem;}),
+ this.sortBy,
+ (v) => this._onSortClicked(v))}
</div>
</div>
@@ -246,12 +268,16 @@ export class OrRulesList extends LitElement {
`;
}
+ protected _isReadonly() {
+ return this.readonly || !manager.hasRole("write:rules");
+ }
+
protected _nodeTemplate(node: RulesetNode): TemplateResult | string {
return html`
<li ?data-selected="${node.selected}" @click="${(evt: MouseEvent) => this._onNodeClicked(evt, node)}">
<div class="node-container">
<div class="node-name">
- <span class="${OrRulesList._getNodeStatusClasses(node.ruleset)}"></span>
+ <span class="${OrRuleList._getNodeStatusClasses(node.ruleset)}"></span>
<div class="flex">
<span>${node.ruleset.name}</span>
</div>
@@ -315,7 +341,7 @@ export class OrRulesList extends LitElement {
this.selectedIds = actuallySelectedIds;
this._selectedNodes = selectedNodes;
- this.dispatchEvent(new OrRulesEditorSelectionChangedEvent(this._selectedNodes.map((node) => node.ruleset)));
+ this.dispatchEvent(new OrRulesSelectionChangedEvent(this._selectedNodes.map((node) => node.ruleset)));
}
protected static _updateSort(nodes: RulesetNode[], sortFunction: (a: RulesetNode, b: RulesetNode) => number) {
@@ -360,49 +386,37 @@ export class OrRulesList extends LitElement {
}
}
- this._doRequest(new OrRulesEditorRequestSelectEvent(selectRulesets), (detail) => {
+ this._doRequest(new OrRulesRequestSelectEvent(selectRulesets), (detail) => {
this.selectedIds = detail.map((ruleset) => ruleset.id!);
});
}
protected _onCopyClicked() {
if (this._selectedNodes.length == 1) {
- this.dispatchEvent(new OrRulesEditorRequestCopyEvent(this._selectedNodes[0].ruleset));
+ this.dispatchEvent(new OrRulesRequestCopyEvent(this._selectedNodes[0].ruleset));
}
}
protected _onDeleteClicked() {
if (this._selectedNodes.length > 0) {
- this.dispatchEvent(new OrRulesEditorRequestDeleteEvent(this._selectedNodes.map((node) => node.ruleset)));
+ this.dispatchEvent(new OrRulesRequestDeleteEvent(this._selectedNodes.map((node) => node.ruleset)));
}
}
- protected _onAddClicked() {
- this.dispatchEvent(new OrRulesEditorRequestAddEvent());
+ protected _onAddClicked(lang: RulesetLang) {
+ this.dispatchEvent(new OrRulesRequestAddEvent(lang));
}
protected _onSearchClicked() {
}
- protected _onSortClicked() {
- // Do open on next task to prevent click handler closing it immediately
- if (!this._sortMenu.hasAttribute("data-visible")) {
- window.setTimeout(() => {
- this._sortMenu.toggleAttribute("data-visible");
- });
- }
+ protected _onSortClicked(sortBy: string) {
+ this.sortBy = sortBy;
}
protected _getSortFunction(): (a: RulesetNode, b: RulesetNode) => number {
-
- const nameSort = (a: RulesetNode, b: RulesetNode) => { return a.ruleset!.name! < b.ruleset!.name! ? -1 : a.ruleset!.name! > b.ruleset!.name! ? 1 : 0 };
-
- if (this.sortBy === "created") {
- return (a, b) => { return a.ruleset!.createdOn! < b.ruleset!.createdOn! ? -1 : a.ruleset!.createdOn! > b.ruleset!.createdOn! ? 1 : nameSort(a, b) };
- }
-
- return nameSort;
+ return (a, b) => { return (a.ruleset as any)![this.sortBy!] < (b.ruleset as any)![this.sortBy!] ? -1 : (a.ruleset as any)![this.sortBy!] > (b.ruleset as any)![this.sortBy!] ? 1 : 0 };
}
protected _getRealm(): string | undefined {
@@ -413,8 +427,8 @@ export class OrRulesList extends LitElement {
return manager.getRealm();
}
- protected _onRealmChanged(evt: OrInputChangedEvent) {
- this.realm = evt.detail.value;
+ protected _onRealmChanged(realm: string | undefined) {
+ this.realm = realm;
}
protected _doRequest<T>(event: CustomEvent<RequestEventDetail<T>>, handler: (detail: T) => void) {
diff --git a/ui/component/or-rules/src/or-rule-viewer.ts b/ui/component/or-rules/src/or-rule-viewer.ts
new file mode 100644
index 000000000..c409d6832
--- /dev/null
+++ b/ui/component/or-rules/src/or-rule-viewer.ts
@@ -0,0 +1,255 @@
+import {css, customElement, html, LitElement, property, PropertyValues, query, TemplateResult, unsafeCSS} from "lit-element";
+import {
+ OrRulesSaveStartEvent,
+ OrRulesRuleChangedEvent,
+ OrRulesRuleUnsupportedEvent,
+ OrRulesSaveEndEvent,
+ RulesConfig,
+ RuleView
+} from "./index";
+import {RulesetLang, RulesetUnion} from "@openremote/model";
+import manager, {DefaultBoxShadow} from "@openremote/core";
+import "./json-viewer/or-rule-json-viewer";
+import "@openremote/or-input";
+import {translate} from "@openremote/or-translate";
+import {InputType, OrInputChangedEvent} from "@openremote/or-input";
+import i18next from "i18next";
+
+// language=CSS
+export const style = css`
+
+ :host {
+ display: block;
+ height: 100%;
+ width: 100%;
+ }
+
+ .wrapper {
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ height: 100%;
+ }
+
+ #rule-name {
+ width: 400px;
+ }
+
+ #rule-header {
+ display: flex;
+ align-items: center;
+ width: 100%;
+ box-sizing: border-box;
+ min-height: var(--internal-or-rules-header-height);
+ height: var(--internal-or-rules-header-height);
+ z-index: 1;
+ padding: 0 20px;
+ background-color: var(--internal-or-rules-header-background-color);
+ --or-icon-fill: var(--internal-or-rules-panel-color);
+ box-shadow: ${unsafeCSS(DefaultBoxShadow)};
+ }
+
+ #rule-header-controls {
+ margin-left: auto;
+ display: flex;
+ align-items: center;
+ }
+
+ #rule-header-controls > * {
+ margin: 0 10px;
+ }
+
+ #active-wrapper {
+ display: flex;
+ align-items: center;
+ }
+
+ #active-wrapper > or-translate {
+ margin-right: 10px;
+ }
+
+ #rule-viewer {
+ flex-grow: 1;
+ background-color: var(--internal-or-rules-background-color);
+ }
+`;
+
+@customElement("or-rule-viewer")
+export class OrRuleViewer extends translate(i18next)(LitElement) {
+
+ constructor() {
+ super();
+
+ this.addEventListener(OrRulesRuleChangedEvent.NAME, this._onRuleChanged);
+ this.addEventListener(OrRulesRuleUnsupportedEvent.NAME, this._onRuleUnsupported);
+ }
+
+ static get styles() {
+ return [
+ style
+ ];
+ }
+
+ @property({type: Object})
+ public ruleset?: RulesetUnion;
+
+ @property({type: Boolean})
+ public readonly: boolean = false;
+
+ @property({type: Boolean})
+ public disabled: boolean = false;
+
+ @property({type: Object})
+ public config?: RulesConfig;
+
+ @property({attribute: false})
+ public modified = false;
+
+ @property({attribute: false})
+ protected _ruleValid = false;
+
+ @property({attribute: false})
+ protected _supported = true;
+
+ @query("#rule-viewer")
+ public view?: RuleView;
+
+ public get valid() {
+ return this.ruleset && this.view && this._ruleValid && this.ruleset.name && this.ruleset.name.length >= 3 && this.ruleset.name.length > 255;
+ }
+
+ public shouldUpdate(_changedProperties: PropertyValues): boolean {
+ if (_changedProperties.has("ruleset")) {
+ this._supported = true;
+
+ if (!this.ruleset) {
+ this.modified = false;
+ this._ruleValid = false;
+ }
+ }
+ return super.shouldUpdate(_changedProperties);
+ }
+
+ protected render(): TemplateResult | void {
+
+ if (!this.ruleset) {
+ return html`<div class="wrapper"><or-translate value="noRuleSelected"></or-translate></div>`;
+ }
+
+ let viewer: TemplateResult | string = ``;
+ if (!this._supported) {
+ viewer = html`
+ <div>TEXT EDITOR</div>
+ `;
+ } else {
+ switch (this.ruleset.lang!) {
+ case RulesetLang.JSON:
+ viewer = html`<or-rule-json-viewer id="rule-viewer" .ruleset="${this.ruleset}" .config="${this.config}" .readonly="${this.readonly}"></or-rule-json-viewer>`;
+ break;
+ case RulesetLang.GROOVY:
+ case RulesetLang.JAVASCRIPT:
+ break;
+ default:
+ viewer = html`<div class="wrapper"><or-translate value="notSupported"></or-translate></div>`;
+ }
+ }
+
+ // TODO: load the appropriate viewer depending on state and ruleset language
+ return html`
+ <div class="wrapper">
+ <div id="rule-header">
+ <or-input id="rule-name" .type="${InputType.TEXT}" .value="${this.ruleset ? this.ruleset.name : null}" ?disabled="${this._isReadonly()}" fullwidth required minlength="3" maxlength="255" @or-input-changed="${(e: OrInputChangedEvent) => this._changeName(e.detail.value)}"></or-input>
+
+ <div id="rule-header-controls">
+ <span id="active-wrapper">
+ <or-translate value="active"></or-translate>
+
+ <or-input .type="${InputType.SWITCH}" .value="${this.ruleset && this.ruleset.enabled}" ?disabled="${this._cannotSave()}" @or-input-changed="${this._toggleEnabled}"></or-input>
+ </span>
+
+ <or-input .type="${InputType.BUTTON}" id="save-btn" .label="${i18next.t("save")}" raised ?disabled="${this._cannotSave()}" @or-input-changed="${this._doSave}"></or-input>
+ </div>
+ </div>
+
+ ${viewer}
+ </div>
+ `;
+ }
+
+ protected updated(_changedProperties: PropertyValues): void {
+ if (_changedProperties.has("ruleset")) {
+ if (this.ruleset && this.view) {
+ this._ruleValid = this.view.validate();
+ }
+ }
+ }
+
+ protected _isReadonly() {
+ return this.readonly || !manager.hasRole("write:rules");
+ }
+
+ protected _cannotSave() {
+ return this._isReadonly() || !this.ruleset || !this.modified || !this.valid;
+ }
+
+ protected _changeName(name: string) {
+ if (this.ruleset && this.ruleset.name !== name) {
+ this.ruleset.name = name;
+ this.requestUpdate();
+ }
+ }
+
+ protected _onRuleChanged(e: OrRulesRuleChangedEvent) {
+ this.modified = true;
+ this._ruleValid = e.detail;
+ }
+
+ protected _doSave() {
+ if (!this.ruleset || !this.view) {
+ return;
+ }
+
+ this.disabled = true;
+ this.view.beforeSave();
+ this.dispatchEvent(new OrRulesSaveStartEvent());
+
+ if (this.ruleset.type === "tenant") {
+ if (this.ruleset.id) {
+ manager.rest.api.RulesResource.updateTenantRuleset(this.ruleset.id!, this.ruleset).then((response) => {
+ this.disabled = false;
+ this.modified = false;
+ this.dispatchEvent(new OrRulesSaveEndEvent(true));
+ }).catch(reason => {
+ console.error("Failed to save ruleset: " + reason);
+ this.disabled = false;
+ this.dispatchEvent(new OrRulesSaveEndEvent(false));
+ });
+ } else {
+ manager.rest.api.RulesResource.createTenantRuleset(this.ruleset).then((response) => {
+ if (this.ruleset) {
+ this.ruleset.id = response.data;
+ }
+ this.disabled = false;
+ this.modified = false;
+ this.dispatchEvent(new OrRulesSaveEndEvent(true));
+ }).catch(reason => {
+ console.error("Failed to save ruleset: " + reason);
+ this.disabled = false;
+ this.dispatchEvent(new OrRulesSaveEndEvent(false));
+ });
+ }
+ }
+ }
+
+ protected _onRuleUnsupported() {
+ this._supported = false;
+ }
+
+ protected _toggleEnabled() {
+ if (this.ruleset) {
+ this.ruleset.enabled = !this.ruleset.enabled;
+ this.requestUpdate();
+ }
+ }
+}
\ No newline at end of file
diff --git a/ui/component/or-rules/src/style.ts b/ui/component/or-rules/src/style.ts
new file mode 100644
index 000000000..7978f6fee
--- /dev/null
+++ b/ui/component/or-rules/src/style.ts
@@ -0,0 +1,57 @@
+import {css} from "lit-element";
+
+// language=CSS
+export const invalidStyle = css`
+ *:invalid {
+ border-bottom: 2px solid var(--internal-or-rules-invalid-color);
+ }
+`;
+
+// language=CSS
+export const buttonStyle = css`
+ .button-clear {
+ background: none;
+ color: var(--internal-or-rules-button-color);
+ --or-icon-fill: var(--internal-or-rules-button-color);
+ border: none;
+ padding: 0;
+ display: inline-block;
+ cursor: pointer;
+ }
+
+ .button-clear:focus {
+ outline: 0;
+ }
+
+ .add-button {
+ display: inline-block;
+ font-weight: bold;
+ font-size: 15px;
+ line-height: 24px;
+ }
+
+ .add-buttons-container {
+ display: flex;
+ flex-direction: column;
+ margin-top: 10px;
+ margin-bottom: -10px;
+ padding-top: 5px;
+ border-top-width: 1px;
+ border-top-style: solid;
+ border-color: var(--internal-or-rules-line-color);
+ }
+
+ .add-buttons-container.hidden {
+ border: none;
+ margin: 0;
+ padding: 0;
+ }
+
+ .add-buttons-container > button {
+ display: inline-flex;
+ }
+
+ .add-buttons-container > button > or-icon {
+ margin-right: 5px;
+ }
+`;
diff --git a/ui/component/or-rules-editor/tsconfig.json b/ui/component/or-rules/tsconfig.json
similarity index 100%
rename from ui/component/or-rules-editor/tsconfig.json
rename to ui/component/or-rules/tsconfig.json
diff --git a/ui/component/or-rules-editor/webpack.config.js b/ui/component/or-rules/webpack.config.js
similarity index 100%
rename from ui/component/or-rules-editor/webpack.config.js
rename to ui/component/or-rules/webpack.config.js