Skip to content

armgit / core

Public Imported from GitHub
0

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

Rules grouping support, with tree dragging functionality (#1680)

Martin Peeters923c4bc510d3
diff --git a/ui/app/shared/locales/en/or.json b/ui/app/shared/locales/en/or.json
index d83d803dd..21e976503 100644
--- a/ui/app/shared/locales/en/or.json
+++ b/ui/app/shared/locales/en/or.json
@@ -83,6 +83,8 @@
"deleteRulesets": "Delete rule(s)",
"deleteRulesetsConfirm": "Are you sure you want to delete the selected rule(s)? {{ruleNames}}",
"deleteRulesetsFailed": "Failed to delete one or more requested rules",
+ "deleteRulesetGroups": "Delete group(s)",
+ "deleteRulesetGroupsConfirm": "Are you sure you want to delete the selected group(s)? {{groupNames}}",
"saveRulesetFailed": "Failed to save rule",
"confirmContinueRulesetModified": "Rule has been modified, discard changes?",
"when": "When",
@@ -265,6 +267,12 @@
"info": "Info",
"notSupported": "Not supported",
"ruleName": "Rule name",
+ "ruleGroupName": "Group name",
+ "ruleGroupNameDefault": "New Group",
+ "ruleGroupExistsError": "This group already exists.",
+ "ruleGroupDragError": "You cannot move a group.",
+ "ruleDragSuccess": "Moved successfully!",
+ "ruleDragFailed": "Failed to move. Please try again.",
"value": "Value",
"values": "Values",
"and": "and",
@@ -345,6 +353,8 @@
"GROOVY": "Groovy",
"JAVASCRIPT": "JavaScript"
},
+ "group": "Group",
+ "newGroup": "New group",
"gatewayConnection": "Manager interconnect",
"gateway": {
"": "Manager interconnect",
diff --git a/ui/app/shared/locales/nl/or.json b/ui/app/shared/locales/nl/or.json
index 17ceb3920..db3ef46e2 100644
--- a/ui/app/shared/locales/nl/or.json
+++ b/ui/app/shared/locales/nl/or.json
@@ -82,6 +82,8 @@
"deleteRulesets": "Regels verwijderen",
"deleteRulesetsConfirm": "Weet je zeker dat je de volgende regels wil verwijderen? {{ruleNames}}",
"deleteRulesetsFailed": "Het verwijderen van een of meerdere regels is niet gelukt",
+ "deleteRulesetGroups": "Groepen verwijderen",
+ "deleteRulesetGroupsConfirm": "Weet je zeker dat je de volgende groepen wilt verwijderen? {{groupNames}}",
"saveRulesetFailed": "Het opslaan van de regel is niet gelukt",
"confirmContinueRulesetModified": "De regel is aangepast, wijzigingen weggooien?",
"when": "Als",
@@ -264,6 +266,12 @@
"info": "Info",
"notSupported": "Niet ondersteund",
"ruleName": "Regel naam",
+ "ruleGroupName": "Groep naam",
+ "ruleGroupNameDefault": "Nieuwe Groep",
+ "ruleGroupExistsError": "Deze groep bestaat al.",
+ "ruleGroupDragError": "Je kunt geen groep verplaatsen.",
+ "ruleDragSuccess": "Regel verplaatst!",
+ "ruleDragFailed": "Kon regel niet verplaatsen! Probeer opnieuw.",
"value": "Waarde",
"values": "Waardes",
"and": "en",
@@ -344,6 +352,8 @@
"GROOVY": "Groovy",
"JAVASCRIPT": "JavaScript"
},
+ "group": "Groep",
+ "newGroup": "Nieuwe groep",
"gatewayConnection": "Manager interconnect",
"gateway": {
"": "Manager interconnect",
diff --git a/ui/component/or-rules/package.json b/ui/component/or-rules/package.json
index 75352cd6a..6bb0f45c4 100644
--- a/ui/component/or-rules/package.json
+++ b/ui/component/or-rules/package.json
@@ -23,6 +23,7 @@
"@openremote/or-icon": "workspace:*",
"@openremote/or-mwc-components": "workspace:*",
"@openremote/or-translate": "workspace:*",
+ "@openremote/or-tree-menu": "workspace:*",
"@openremote/rest": "workspace:*",
"ace-builds": "^1.4.13",
"iso-639-1": "^3.1.3",
diff --git a/ui/component/or-rules/src/index.ts b/ui/component/or-rules/src/index.ts
index 78f30ebc6..799e1cc77 100644
--- a/ui/component/or-rules/src/index.ts
+++ b/ui/component/or-rules/src/index.ts
@@ -1,5 +1,24 @@
-import {css, html, LitElement, TemplateResult, unsafeCSS} from "lit";
-import {customElement, property, query} from "lit/decorators.js";
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+import {css, html, LitElement, PropertyValues, TemplateResult, unsafeCSS} from "lit";
+import {customElement, property, query, state} from "lit/decorators.js";
import manager, {
DefaultBoxShadow,
DefaultColor1,
@@ -34,14 +53,18 @@ import {
import "@openremote/or-translate";
import "@openremote/or-mwc-components/or-mwc-drawer";
import {translate} from "@openremote/or-translate";
-import "./or-rule-list";
import "./or-rule-viewer";
+import "./or-rule-group-viewer";
+import "./or-rule-tree";
import "./flow-viewer/flow-viewer";
-import {OrRuleList} from "./or-rule-list";
import {OrRuleViewer} from "./or-rule-viewer";
import {RecurrenceOption} from "./json-viewer/or-rule-then-otherwise";
import {ValueInputProviderGenerator} from "@openremote/or-mwc-components/or-mwc-input";
import {showOkCancelDialog} from "@openremote/or-mwc-components/or-mwc-dialog";
+import {showSnackbar} from "@openremote/or-mwc-components/or-mwc-snackbar";
+import {OrRuleTree, RuleTreeNode} from "./or-rule-tree";
+import {OrTreeDragEvent} from "@openremote/or-tree-menu";
+import {when} from "lit/directives/when.js";
export {buttonStyle} from "./style";
@@ -170,11 +193,21 @@ export interface RulesConfigAsset {
export interface RulesConfigAttribute extends AttributeDescriptor {
}
+export interface RulesetBaseNode {
+ type: "rule" | "group";
+}
+
export interface RulesetNode {
+ type: "rule",
ruleset: RulesetUnion;
selected: boolean;
}
+export interface RulesetGroupNode extends RulesetBaseNode {
+ type: "group",
+ groupId: string;
+}
+
export interface RequestEventDetail<T> {
allow: boolean;
detail: T;
@@ -561,11 +594,11 @@ export class OrRulesRuleUnsupportedEvent extends CustomEvent<void> {
}
export interface NodeSelectEventDetail {
- oldNodes: RulesetNode[];
- newNodes: RulesetNode[];
+ oldNodes: RulesetBaseNode[];
+ newNodes: RulesetBaseNode[];
}
-export class OrRulesRequestSelectionEvent extends CustomEvent<RequestEventDetail<NodeSelectEventDetail>> {
+export class OrRulesRequestSelectionEvent extends CustomEvent<NodeSelectEventDetail> {
public static readonly NAME = "or-rules-request-selection";
@@ -573,10 +606,8 @@ export class OrRulesRequestSelectionEvent extends CustomEvent<RequestEventDetail
super(OrRulesRequestSelectionEvent.NAME, {
bubbles: true,
composed: true,
- detail: {
- detail: request,
- allow: true
- }
+ cancelable: true,
+ detail: request
});
}
}
@@ -615,6 +646,22 @@ export class OrRulesRequestAddEvent extends CustomEvent<RequestEventDetail<AddEv
}
}
+export class OrRulesRequestGroupEvent extends CustomEvent<{ value: string }> {
+
+ public static readonly NAME = "or-rules-request-group";
+
+ constructor(name: string) {
+ super(OrRulesRequestGroupEvent.NAME, {
+ bubbles: true,
+ composed: true,
+ detail: {
+ value: name,
+ }
+ });
+ }
+}
+
+
export class OrRulesAddEvent extends CustomEvent<AddEventDetail> {
public static readonly NAME = "or-rules-add";
@@ -692,6 +739,22 @@ export class OrRulesDeleteEvent extends CustomEvent<RulesetUnion[]> {
}
}
+export class OrRulesGroupNameChangeEvent extends CustomEvent<{ value: string }> {
+
+ public static readonly NAME = "or-rules-group-name-change";
+
+ constructor(name: string) {
+ super(OrRulesGroupNameChangeEvent.NAME, {
+ bubbles: true,
+ composed: true,
+ cancelable: true,
+ detail: {
+ value: name
+ }
+ });
+ }
+}
+
declare global {
export interface HTMLElementEventMap {
[OrRulesRuleUnsupportedEvent.NAME]: OrRulesRuleUnsupportedEvent;
@@ -704,6 +767,9 @@ declare global {
[OrRulesRequestSaveEvent.NAME]: OrRulesRequestSaveEvent;
[OrRulesSaveEvent.NAME]: OrRulesSaveEvent;
[OrRulesDeleteEvent.NAME]: OrRulesDeleteEvent;
+ [OrTreeDragEvent.NAME]: OrTreeDragEvent;
+ [OrRulesRequestGroupEvent.NAME]: OrRulesRequestGroupEvent;
+ [OrRulesGroupNameChangeEvent.NAME]: OrRulesGroupNameChangeEvent;
}
}
@@ -738,7 +804,7 @@ export const style = css`
--or-panel-background-color: var(--internal-or-rules-panel-color);
}
- or-rule-list {
+ or-rule-tree {
min-width: 300px;
width: 300px;
z-index: 2;
@@ -749,7 +815,7 @@ export const style = css`
box-shadow: ${unsafeCSS(DefaultBoxShadow)};
}
- or-rule-viewer {
+ or-rule-viewer, or-rule-group-viewer {
z-index: 1;
}
`;
@@ -777,17 +843,21 @@ export class OrRules extends translate(i18next)(LitElement) {
@property({type: String})
public language?: RulesetLang;
- @property({type: Array})
- public selectedIds?: number[];
-
@property({attribute: false})
private _isValidRule?: boolean;
- @query("#rule-list")
- private _rulesList!: OrRuleList;
+ /**
+ * Represents the selected group name. (groupId in rules meta)
+ * Will be undefined once something else is selected
+ */
+ @state()
+ protected _selectedGroup?: string;
+
+ @query("#rule-tree")
+ private _rulesTree?: OrRuleTree;
@query("#rule-viewer")
- private _viewer!: OrRuleViewer;
+ private _viewer?: OrRuleViewer;
constructor() {
super();
@@ -796,75 +866,322 @@ export class OrRules extends translate(i18next)(LitElement) {
this.addEventListener(OrRulesSelectionEvent.NAME, this._onRuleSelectionChanged);
this.addEventListener(OrRulesAddEvent.NAME, this._onRuleAdd);
this.addEventListener(OrRulesSaveEvent.NAME, this._onRuleSave);
+ this.addEventListener(OrTreeDragEvent.NAME, this._onRuleDrag);
+ this.addEventListener(OrRulesRequestGroupEvent.NAME, this._onGroupAddRequest);
+ this.addEventListener(OrRulesGroupNameChangeEvent.NAME, this._onGroupNameChange);
}
protected render() {
-
return html`
- <or-rule-list id="rule-list" .config="${this.config}" .language="${this.language}" .selectedIds="${this.selectedIds}"></or-rule-list>
- <or-rule-viewer id="rule-viewer" .config="${this.config}" .readonly="${this.isReadonly()}"></or-rule-viewer>
+ <or-rule-tree id="rule-tree" ?readonly=${this._isReadonly()} .config=${this.config}></or-rule-tree>
+ ${when(this._selectedGroup, () => html`
+ <or-rule-group-viewer .group="${this._selectedGroup}" .readonly="${this._isReadonly()}"></or-rule-group-viewer>
+ `, () => html`
+ <or-rule-viewer id="rule-viewer" .config="${this.config}" .readonly="${this._isReadonly()}"></or-rule-viewer>
+ `)}
`;
}
public refresh() {
- this._viewer.ruleset = undefined;
- this._rulesList.refresh();
+ console.debug("Refreshing the rules content...")
+ if(this._viewer) {
+ this._viewer.ruleset = undefined;
+ }
+ this._rulesTree?.refresh();
}
- protected isReadonly(): boolean {
+ protected _isReadonly(): boolean {
return this.readonly || !manager.hasRole(ClientRole.WRITE_RULES);
}
- protected _confirmContinue(action: () => void) {
- if (this._viewer.modified) {
+ protected _confirmContinue(action: (ok: boolean) => void) {
+ if (this._viewer?.modified) {
showOkCancelDialog(i18next.t("loseChanges"), i18next.t("confirmContinueRulesetModified"), i18next.t("discard"))
- .then((ok) => {
- if (ok) {
- action();
- }
- });
+ .then((ok) => action(ok));
} else {
- action();
+ action(true);
}
}
+ /**
+ * HTML event callback on when a "rule (or group) selection is requested".
+ * It is a cancellable event that can prompt a user "to discard changes" if they have been made.
+ * @param event - The cancellable selection event
+ */
protected _onRuleSelectionRequested(event: OrRulesRequestSelectionEvent) {
- const isModified = this._viewer.modified;
+ const isModified = this._viewer?.modified;
if (!isModified) {
return;
}
- // Prevent the request and check if user wants to lose changes
- event.detail.allow = false;
+ // Prevent the initial request
+ event.preventDefault();
+ console.debug("Prevented new rule selection; prompting user changes have been made.");
- this._confirmContinue(() => {
- const nodes = event.detail.detail.newNodes;
- if (Util.objectsEqual(nodes, event.detail.detail.oldNodes)) {
- // User has clicked the same node so let's force reload it
- this._viewer.ruleset = {...nodes[0].ruleset};
+ // Prompt user to "discard changes", and continue the selection afterwards
+ this._confirmContinue((ok) => {
+ if(ok) {
+ this._onNodeSelectionChanged(event.detail);
+ event.detail.newNodes.filter(n => n.type === "rule")
+ .forEach(n => this._rulesTree?.selectRuleset((n as RulesetNode).ruleset, true));
} else {
- this.selectedIds = nodes.map((node) => node.ruleset.id!);
- this._viewer.ruleset = nodes.length === 1 ? nodes[0].ruleset : undefined;
+ event.detail.oldNodes.filter(n => n.type === "rule")
+ .forEach(n => this._rulesTree?.selectRuleset((n as RulesetNode).ruleset, true));
}
});
}
+ /**
+ * HTML event callback on when a new rule (or group) has been selected.
+ * @param event - The selection event
+ */
protected _onRuleSelectionChanged(event: OrRulesSelectionEvent) {
- const nodes = event.detail.newNodes;
- this.selectedIds = nodes.map((node) => node.ruleset.id!);
- this._viewer.ruleset = nodes.length === 1 ? {...nodes[0].ruleset} : undefined;
+ this._onNodeSelectionChanged(event.detail);
+ }
+
+ /**
+ * Utility event callback function called by {@link _onRuleSelectionRequested} and {@link _onRuleSelectionChanged},
+ * when a new node in the {@link OrRuleTree} element is selected. It processes the event, and updates the {@link OrRuleViewer} with the new rule.
+ * Alternatively, if a group is selected, it updates {@link _selectedGroup} instead.
+ * @param payload - Event payload of the {@link RulesetBaseNode} selection
+ */
+ protected _onNodeSelectionChanged(payload: NodeSelectEventDetail) {
+ const selectedNodes = payload.newNodes;
+ const groupNodes = selectedNodes.filter(n => n.type === "group") as RulesetGroupNode[]; // list of selected group nodes
+
+ // If any group has been selected
+ if(groupNodes.length === 1) {
+ if(this._viewer) this._viewer.ruleset = undefined; // clear viewer, since a group is selected instead
+ this._selectedGroup = groupNodes[0].groupId;
+ return;
+ }
+
+ // If the user has clicked the same node so let's force reload it
+ else if (Util.objectsEqual(selectedNodes, payload.oldNodes)) {
+ console.debug("Force reloading rule viewer...");
+ const node = (selectedNodes[0] as any)?.ruleset as RulesetNode | undefined;
+ this._viewer!.ruleset = node ? {...node.ruleset} : undefined;
+
+ // Otherwise, select the new rule or group.
+ } else {
+ const groupNodes = selectedNodes.filter(n => n.type === "group") as RulesetGroupNode[]; // list of selected group nodes
+ const rulesetNodes = selectedNodes.filter(n => n.type === "rule") as RulesetNode[]; // list of selected rule nodes
+ const selectedIds = rulesetNodes.map((node) => node.ruleset.id!);
+ console.debug(`Selecting rule IDs ${selectedIds}`);
+
+ // Deselect the group, and select either a new rule or group after that.
+ this._deselectGroup().then(() => {
+ if(rulesetNodes.length === 1) {
+ this.getUpdateComplete().then(() => {
+ console.debug("Ruleset viewer is now showing", rulesetNodes[0].ruleset.name)
+ this._viewer!.ruleset = {...rulesetNodes[0].ruleset};
+ })
+ } else {
+ this._viewer!.ruleset = undefined; // clear viewer, since a group is selected instead
+ if(groupNodes.length === 1) {
+ this._selectedGroup = groupNodes[0].groupId;
+ }
+ }
+ })
+ }
}
+ /**
+ * HTML callback event for when a new rule is added.
+ * @param event - A {@link CustomEvent} with the new ruleset as payload.
+ */
protected _onRuleAdd(event: OrRulesAddEvent) {
// Load the ruleset into the viewer
- this._viewer.ruleset = event.detail.ruleset;
+ this._deselectGroup().then(() => {
+ this._viewer!.ruleset = event.detail.ruleset;
+ })
}
+ /**
+ * HTML callback event for when a rule has been saved by the user.
+ * @param event - A {@link CustomEvent} with a {@link SaveResult} payload.
+ */
protected async _onRuleSave(event: OrRulesSaveEvent) {
- await this._rulesList.refresh();
- if (event.detail.success && event.detail.isNew) {
- this.selectedIds = [event.detail.ruleset.id!];
+ if(event.detail.success) {
+
+ // Reset the modified state, which disables the "save" button
+ if(this._viewer) this._viewer.modified = false;
+
+ // Fetch the updated rules, and change the viewer to the latest version
+ const newRulesets = await this._rulesTree?.refresh();
+ this._checkForViewerUpdate(undefined, newRulesets);
+
+ // Select the ruleset if it's new
+ if (event.detail.isNew) {
+ const ruleset = newRulesets?.find(r => r.id && r.id === event.detail.ruleset.id);
+ if(ruleset) {
+ this._rulesTree?.deselectAllNodes();
+ this._rulesTree?.selectRuleset(ruleset);
+ } else {
+ console.warn("Could not select the new ruleset.")
+ }
+ }
+ }
+ }
+
+ /**
+ * Utility function that updates the viewer with the latest changes.
+ * @param viewer - The or-rule-viewer HTML element
+ * @param updatedRulesets - List of new rulesets that have been changed
+ */
+ protected _checkForViewerUpdate(viewer = this._viewer, updatedRulesets?: RulesetUnion[]) {
+ const current = viewer?.ruleset;
+ if(current) {
+ const found = updatedRulesets?.find(r => r.id === viewer?.ruleset?.id);
+ if(found) viewer!.ruleset = found;
+ }
+ }
+
+ /**
+ * HTML callback for {@link OrTreeDragEvent}, for when a rule is dragged into (or outside) a group.
+ * It handles updating of the 'meta groupId' in a rule, and persists the changes with the HTTP API.
+ * @param ev - Tree drag event with a payload of the moved nodes
+ */
+ protected _onRuleDrag(ev: OrTreeDragEvent) {
+ const isModified = this._viewer?.modified;
+ const groupId = ev.detail.groupNode?.label;
+
+ const moveAndSave = (ruleset: RulesetUnion, groupId?: string) => {
+ move(ruleset, groupId);
+ return this._saveRuleset(ruleset);
+ };
+ const move = (ruleset: RulesetUnion, groupId?: string) => {
+ if (!ruleset.meta) ruleset.meta = {};
+ (ruleset.meta as any).groupId = groupId;
+ if(Object.keys(ruleset.meta).length === 0) {
+ delete ruleset.meta;
+ }
+ };
+
+ // If the ruleset viewer has no changes, continue dragging the node, and apply changes.
+ if (!isModified) {
+ const promises = (ev.detail.nodes as RuleTreeNode[]).map(node => {
+ if(node.ruleset) {
+ return moveAndSave(node.ruleset, groupId);
+ }
+ });
+ Promise.all(promises)
+ .then(() => showSnackbar(undefined, "ruleDragSuccess"))
+ .catch(() => showSnackbar(undefined, "ruleDragFailed"))
+ .finally(() => this._rulesTree?.refresh().then(rulesets => this._checkForViewerUpdate(undefined, rulesets)));
+
+ return;
+ }
+
+ console.debug("Prevented the default tree drag behavior.")
+ ev.preventDefault(); // prevent the initial rule dragging
+
+ // Prompt the user to "discard changes"
+ this._confirmContinue((ok) => {
+ if(ok) {
+ (ev.detail.nodes as RuleTreeNode[]).forEach(node => {
+ if (node.ruleset) {
+ moveAndSave(node.ruleset, groupId)?.then(() => {
+ this._rulesTree?.moveNodesToGroup([node], ev.detail.groupNode); // move the nodes again, as the initial event got cancelled.
+ showSnackbar(undefined, "ruleDragSuccess!");
+ }).catch(() => {
+ showSnackbar(undefined, "ruleDragFailed");
+ });
+ } else if (node.ruleset) {
+ console.warn("Could not add rule to group; could not find ruleset.");
+ } else if (groupId) {
+ console.warn("Could not add rule to group; could not find group ID.");
+ }
+ });
+ }
+ });
+ }
+
+ /**
+ * Utility function that deselects the group by clearing {@link _selectedGroup}.
+ */
+ protected _deselectGroup(): Promise<boolean> {
+ this._selectedGroup = undefined;
+ return this.getUpdateComplete();
+ }
+
+ /**
+ * HTML callback for when a new group is added to the {@link OrRuleTree}.
+ * @param ev - Callback event
+ */
+ protected _onGroupAddRequest(ev: OrRulesRequestGroupEvent) {
+ this._selectedGroup = ev.detail.value;
+ }
+
+ /**
+ * HTML callback for when the selected group name has changed.
+ * This function handles renaming the groupId of the rules within that group,
+ * together with persisting the changes using the HTTP API.
+ * @param ev - Callback event
+ */
+ protected _onGroupNameChange(ev: OrRulesGroupNameChangeEvent) {
+ const oldValue = this._selectedGroup;
+ const newValue = ev.detail.value;
+
+ // If the group name already exists, we should prevent the event from happening
+ if(this._rulesTree?.nodes.find(n => n.label === newValue)) {
+ console.warn(`The group '${newValue}' already exists. Please try again.`);
+ ev.preventDefault();
+ return;
+ }
+
+ console.debug(`Renaming group '${oldValue}' to '${newValue}'`)
+
+ // Change the groupId for each child rule, and prepare an HTTP API update
+ const promises: Promise<any>[] = [];
+ const groupRules = this._rulesTree?.rules?.filter(r => r.meta?.groupId === oldValue);
+ groupRules?.forEach((r) => {
+ r.meta!.groupId = newValue;
+ promises.push(this._saveRuleset(r));
+ });
+
+ // If a rule has changed, execute the HTTP requests.
+ // After that, we fetch the list of rules again using .refresh();
+ if(promises.length > 0) {
+ Promise.all(promises)
+ .then(() => showSnackbar(undefined, "Saved!"))
+ .catch(() => showSnackbar(undefined, "Failed!"))
+ .finally(() => this._rulesTree?.refresh());
+
+ // Otherwise, only update the group name in the tree.
+ } else {
+ if(this._rulesTree) {
+ const nodes = [...this._rulesTree.nodes];
+ const node = nodes.find(n => n.label === oldValue);
+ if(node) {
+ node.label = newValue;
+ this._rulesTree.nodes = nodes;
+ } else {
+ this._rulesTree.nodes = [...nodes, {id: newValue, label: newValue, children: []}];
+ }
+ }
}
+ this._selectedGroup = newValue;
}
+
+ /**
+ * Utility function that returns a promise for saving the ruleset, based on its type.
+ * @param ruleset - The ruleset to be saved
+ */
+ protected async _saveRuleset(ruleset: RulesetUnion){
+ let promise;
+ switch (ruleset.type) {
+ case "asset": {
+ promise = manager.rest.api.RulesResource.updateAssetRuleset(ruleset.id!, ruleset); break;
+ } case "global": {
+ promise = manager.rest.api.RulesResource.updateGlobalRuleset(ruleset.id!, ruleset); break;
+ } case "realm": {
+ promise = manager.rest.api.RulesResource.updateRealmRuleset(ruleset.id!, ruleset); break;
+ } default: {
+ break;
+ }
+ }
+ return promise;
+ };
}
diff --git a/ui/component/or-rules/src/or-rule-group-viewer.ts b/ui/component/or-rules/src/or-rule-group-viewer.ts
new file mode 100644
index 000000000..c6d8507cb
--- /dev/null
+++ b/ui/component/or-rules/src/or-rule-group-viewer.ts
@@ -0,0 +1,98 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+import {i18next, translate} from "@openremote/or-translate";
+import {html, LitElement, PropertyValues } from "lit";
+import { customElement, property, query, state } from "lit/decorators.js";
+import {style} from "./or-rule-viewer";
+import { InputType, OrMwcInput } from "@openremote/or-mwc-components/or-mwc-input";
+import {OrRulesGroupNameChangeEvent} from "./index";
+import { showSnackbar } from "@openremote/or-mwc-components/or-mwc-snackbar";
+
+@customElement("or-rule-group-viewer")
+export class OrRuleGroupViewer extends translate(i18next)(LitElement) {
+
+ /**
+ * Name of the group
+ */
+ @property({type: String})
+ public group?: string;
+
+ @property({type: Boolean})
+ public readonly = false;
+
+ @state()
+ protected _lastSaved?: string;
+
+ @query("#rule-name")
+ protected _groupNameInput?: OrMwcInput;
+
+ static get styles() {
+ return [style];
+ }
+
+ willUpdate(changedProps: PropertyValues) {
+ if(changedProps.has("group")) {
+ this._groupNameInput?.focus(); // regain focus on the input (if lost)
+ }
+ return super.willUpdate(changedProps);
+ }
+
+ render() {
+ return html`
+ <div id="main-wrapper" class="wrapper">
+ <div id="rule-header">
+ <or-mwc-input id="rule-name" outlined .type="${InputType.TEXT}" .label="${i18next.t("ruleGroupName")}" focused
+ .value="${this.group}" ?disabled="${this.readonly}" required minlength="1" maxlength="255" @input="${this._onGroupNameInput}"
+ ></or-mwc-input>
+ <div id="rule-header-controls">
+ <or-mwc-input .type="${InputType.BUTTON}" id="save-btn" label="save" raised ?disabled="${this._cannotSave()}" @or-mwc-input-changed="${this._onSaveClicked}"></or-mwc-input>
+ </div>
+ </div>
+ </div>
+ `
+ }
+
+ protected _onGroupNameInput(ev: InputEvent) {
+ const value = this._groupNameInput?.nativeValue;
+ if(value) this._changeName(value);
+ this.requestUpdate();
+ }
+
+ protected _changeName(name: string) {
+ if(name.length >= 3 && name.length <= 255) {
+ this.group = name;
+ }
+ }
+
+ protected _cannotSave() {
+ return this.readonly || !this._groupNameInput?.nativeValue || !this._groupNameInput?.valid || (this._groupNameInput?.nativeValue || "") === this._lastSaved;
+ }
+
+ protected _onSaveClicked(): void {
+ if(this.group && !this._cannotSave()) {
+ const success = this.dispatchEvent(new OrRulesGroupNameChangeEvent(this.group));
+ if(success) {
+ this._lastSaved = this.group;
+ } else {
+ showSnackbar(undefined, 'ruleGroupExistsError');
+ }
+ }
+ }
+}
diff --git a/ui/component/or-rules/src/or-rule-list.ts b/ui/component/or-rules/src/or-rule-list.ts
deleted file mode 100644
index b2f9f47a8..000000000
--- a/ui/component/or-rules/src/or-rule-list.ts
+++ /dev/null
@@ -1,696 +0,0 @@
-import {css, html, LitElement, PropertyValues, TemplateResult} from "lit";
-import {customElement, property} from "lit/decorators.js";
-import {CalendarEvent, ClientRole, RulesetLang, RulesetUnion, RealmRuleset, GlobalRuleset} from "@openremote/model";
-import "@openremote/or-translate";
-import manager, {Util} from "@openremote/core";
-import "@openremote/or-mwc-components/or-mwc-input";
-import {InputType, OrInputChangedEvent} from "@openremote/or-mwc-components/or-mwc-input";
-import {style as OrAssetTreeStyle} from "@openremote/or-asset-tree";
-import {
- OrRules,
- OrRulesAddEvent,
- OrRulesRequestAddEvent,
- OrRulesRequestDeleteEvent,
- OrRulesRequestSelectionEvent,
- OrRulesSelectionEvent,
- RulesConfig,
- RulesetNode, RuleViewInfoMap
-} from "./index";
-import "@openremote/or-mwc-components/or-mwc-menu";
-import {getContentWithMenuTemplate} from "@openremote/or-mwc-components/or-mwc-menu";
-import {ListItem} from "@openremote/or-mwc-components/or-mwc-list";
-import {translate} from "@openremote/or-translate";
-import i18next from "i18next";
-import {showErrorDialog, showOkCancelDialog} from "@openremote/or-mwc-components/or-mwc-dialog";
-import {GenericAxiosResponse} from "@openremote/rest";
-
-// language=CSS
-const style = css`
- :host {
- flex-grow: 1;
- 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 {
- display: flex;
- flex-direction: column;
- height: 100%;
- width: 100%;
- }
-
- #wrapper[data-disabled] {
- opacity: 0.3;
- pointer-events: none;
- }
-
- .node-container {
- align-items: center;
- padding-left: 10px;
- }
-
- .header-ruleset-type {
- display: flex;
- align-items: center;
- height: var(--internal-or-asset-tree-header-height);
- line-height: var(--internal-or-asset-tree-header-height);
- color: var(--internal-or-rules-panel-color);
- background-color: var(--internal-or-rules-header-background-color);
- }
-
- #header-btns {
- --or-mwc-input-color: var(--internal-or-rules-text-color);
- }
-
- .header-ruleset-type p {
- margin: 0 15px;
- }
-
- .node-status {
- --or-icon-width: 18px;
- margin-right: 8px;
- }
-
- .node-language{
- padding-left: 10px;
- opacity: 50%;
- }
-
- .iconfill-gray {
- --or-icon-fill: var(--internal-or-rules-list-icon-color-ok);
- }
-
- .iconfill-red {
- --or-icon-fill: var(--internal-or-rules-list-icon-color-error);
- }
-`;
-
-@customElement("or-rule-list")
-export class OrRuleList extends translate(i18next)(LitElement) {
-
- public static DEFAULT_ALLOWED_LANGUAGES = [RulesetLang.JSON, RulesetLang.GROOVY, RulesetLang.JAVASCRIPT, RulesetLang.FLOW];
-
- @property({type: Object})
- public config?: RulesConfig;
-
- @property({type: Boolean})
- public readonly: boolean = false;
-
- @property({type: Boolean})
- public disabled: boolean = false;
-
- @property({type: Boolean})
- public multiSelect: boolean = true;
-
- @property({type: Array})
- public selectedIds?: number[];
-
- @property({type: String})
- public sortBy?: string;
-
- @property({type: String})
- public language?: RulesetLang;
-
- @property({attribute: false})
- protected _nodes?: RulesetNode[];
-
- @property({attribute: false})
- protected _showLoading: boolean = true;
-
- @property({type: Boolean})
- protected _globalRulesets: boolean = false;
-
- protected _selectedNodes: RulesetNode[] = [];
- protected _rulesetPromises: Map<string, Promise<any[]>> = new Map<string, Promise<any[]>>();
- protected _ready = false;
-
- static get styles() {
- return [
- OrAssetTreeStyle,
- style
- ];
- }
-
- public async refresh() {
- this._nodes = undefined;
- // reloading rulesets is automatically done in shouldUpdate()
- }
-
- protected get _allowedLanguages(): RulesetLang[] | undefined {
- const languages = this.config && this.config.controls && this.config.controls.allowedLanguages ? [...this.config.controls.allowedLanguages] : OrRuleList.DEFAULT_ALLOWED_LANGUAGES;
- const groovyIndex = languages.indexOf(RulesetLang.GROOVY);
- const flowIndex = languages.indexOf(RulesetLang.FLOW);
- if(!manager.isSuperUser()) {
- if(groovyIndex > 0) languages.splice(groovyIndex,1);
- } else if (groovyIndex < 0) {
- languages.push(RulesetLang.GROOVY);
- }
- if(this._globalRulesets) {
- if(flowIndex > 0) languages.splice(flowIndex, 1);
- }
- return 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._loadRulesets();
- }
-
- protected firstUpdated(_changedProperties: PropertyValues): void {
- super.firstUpdated(_changedProperties);
- if (manager.ready) {
- this._onReady();
- }
- }
-
- public shouldUpdate(_changedProperties: PropertyValues): boolean {
- const result = super.shouldUpdate(_changedProperties);
-
- if (!this.sortBy) {
- this.sortBy = "name";
- }
-
- if (_changedProperties.has("language")) {
- this._updateLanguage();
- }
-
- if (_changedProperties.has("_globalRulesets")) {
- this._updateLanguage();
- this.refresh();
- }
-
- if (manager.ready) {
- if (!this._nodes) {
- this._loadRulesets();
- return true;
- }
-
- if (_changedProperties.has("selectedIds")) {
- let changed = true;
- const oldValue = _changedProperties.get("selectedIds") as number[];
- if (this.selectedIds && oldValue && this.selectedIds.length === oldValue.length) {
- changed = !!this.selectedIds.find((oldSelected) => oldValue.indexOf(oldSelected) < 0);
- }
- if (changed) {
- this._updateSelectedNodes();
- }
- }
-
- if (_changedProperties.has("sortBy")) {
- OrRuleList._updateSort(this._nodes!, this._getSortFunction());
- }
- }
-
- return result;
- }
-
- protected render() {
- if (!this.language) {
- this._updateLanguage();
- }
-
- const allowedLanguages = this._allowedLanguages;
- const sortOptions = ["name", "createdOn", "status"]
- if (allowedLanguages && allowedLanguages.length > 1) sortOptions.push("lang")
-
- let addTemplate: TemplateResult | string = ``;
-
- if (!this._isReadonly()) {
- if (allowedLanguages && allowedLanguages.length > 1) {
- addTemplate = getContentWithMenuTemplate(
- html`<or-mwc-input type="${InputType.BUTTON}" icon="plus"></or-mwc-input>`,
- allowedLanguages.map((l) => {
- return {value: l, text: i18next.t("rulesLanguages." + l)} as ListItem;
- }),
- this.language,
- (v) => this._onAddClicked(v as RulesetLang));
- } else {
- addTemplate = html`<or-mwc-input type="${InputType.BUTTON}" icon="plus" @or-mwc-input-changed="${() => this._onAddClicked(this.language!)}"></or-mwc-input>`;
- }
- }
- return html`
- <div id="wrapper" ?data-disabled="${this.disabled}">
- ${manager.isSuperUser() ? html`
- <div class="header-ruleset-type">
- <p>${i18next.t("realmRules")}</p>
-
- <div style="flex: 1 1 0; display: flex;">
- <or-mwc-input style="margin: auto;" type="${InputType.SWITCH}" @or-mwc-input-changed="${(evt: OrInputChangedEvent) => this._globalRulesets = evt.detail.value}"></or-mwc-input>
- </div>
-
- <p>${i18next.t("globalRules")}</p>
- </div>
- ` : ``}
-
- <div id="header">
- <div id="title-container">
- <or-translate id="title" value="rule_plural"></or-translate>
- </div>
-
- <div id="header-btns">
- <or-mwc-input ?hidden="${this._isReadonly() || !this.selectedIds || this.selectedIds.length === 0}" type="${InputType.BUTTON}" icon="content-copy" @or-mwc-input-changed="${() => this._onCopyClicked()}"></or-mwc-input>
- <or-mwc-input ?hidden="${this._isReadonly() || !this.selectedIds || this.selectedIds.length === 0}" type="${InputType.BUTTON}" icon="delete" @or-mwc-input-changed="${() => this._onDeleteClicked()}"></or-mwc-input>
- ${addTemplate}
- <or-mwc-input hidden type="${InputType.BUTTON}" icon="magnify" @or-mwc-input-changed="${() => this._onSearchClicked()}"></or-mwc-input>
-
- ${getContentWithMenuTemplate(
- html`<or-mwc-input type="${InputType.BUTTON}" icon="sort-variant" ></or-mwc-input>`,
- sortOptions.map((sort) => { return { value: sort, text: i18next.t(sort) } as ListItem; }),
- this.sortBy,
- (v) => this._onSortClicked(v as string))}
- </div>
- </div>
-
- ${!this._nodes || this._showLoading
- ? html`
- <span id="loading"><or-translate value="loading"></or-translate></span>`
- : html`
- <div id="list-container">
- <ol id="list">
- ${this._nodes.map((treeNode) => this._nodeTemplate(treeNode))}
- </ol>
- </div>
- `
- }
-
- <div id="footer">
-
- </div>
- </div>
- `;
- }
-
- protected _isReadonly() {
- return this.readonly || !manager.hasRole(ClientRole.WRITE_RULES);
- }
-
- protected _nodeTemplate(node: RulesetNode): TemplateResult | string {
-
- let statusIcon: string = "help";
- let statusClass: string = "iconfill-gray";
- let nodeIcon: string = "mdi-state-machine";
- let nodeTitle: string = "Unknown language";
- switch (node.ruleset.status){
- case "DEPLOYED":
- statusIcon = "";
- statusClass = "iconfill-gray";
- break;
- case "READY":
- statusIcon = "check";
- statusClass = "iconfill-gray";
- break;
- case "COMPILATION_ERROR":
- case "LOOP_ERROR":
- case "EXECUTION_ERROR":
- statusIcon = "alert-octagon";
- statusClass = "iconfill-red";
- break;
- case "DISABLED":
- statusIcon = "minus-circle";
- statusClass = "iconfill-gray";
- break;
- case "PAUSED":
- statusIcon = "calendar-arrow-right";
- statusClass = "iconfill-gray";
- break;
- case "EXPIRED":
- statusIcon = "calendar-remove";
- statusClass = "iconfill-gray";
- break;
- case "REMOVED":
- statusIcon = "close";
- statusClass = "iconfill-gray";
- break;
- default:
- statusIcon = "stop";
- statusClass = "iconfill-gray";
- }
-
- switch (node.ruleset.lang) {
- case (RulesetLang.JSON):
- nodeIcon = "ray-start-arrow";
- nodeTitle = "rulesLanguages.JSON";
- break;
- case (RulesetLang.FLOW):
- nodeIcon = "transit-connection-variant";
- nodeTitle = "rulesLanguages.FLOW";
- break;
- case (RulesetLang.GROOVY):
- nodeIcon = "alpha-g-box-outline";
- nodeTitle = "rulesLanguages.GROOVY";
- break;
- case (RulesetLang.JAVASCRIPT):
- nodeIcon = "language-javascript";
- nodeTitle = "rulesLanguages.JAVASCRIPT";
- break;
- default:
- nodeIcon = "mdi-state-machine";
- nodeTitle = "Unknown language";
- }
-
- return html`
- <li ?data-selected="${node.selected}" @click="${(evt: MouseEvent) => this._onNodeClicked(evt, node)}">
- <div class="node-container">
- <or-icon style="--or-icon-width: 18px; margin-right: 8px;" icon="${nodeIcon}" title="${i18next.t(nodeTitle)}"></or-icon>
- <span class="node-name">${node.ruleset.name}</span>
- <or-icon class="node-status ${statusClass}" title="${i18next.t("rulesetStatus." + (node.ruleset.status ? node.ruleset.status : "NOSTATUS"))}" icon="${statusIcon}"></or-icon>
- </div>
- </li>
- `;
- }
-
- protected static _getNodeStatusClasses(ruleset: RulesetUnion): string {
- let status = ruleset.enabled ? "bg-green" : "bg-red";
-
- if (ruleset.enabled) {
-
- // Look at validity meta
- if (ruleset.meta && ruleset.meta["validity"]) {
- const calendarEvent = ruleset.meta["validity"] as CalendarEvent;
- const now = new Date().getTime();
-
- if (calendarEvent.start) {
- if (now < calendarEvent.start) {
- // before startDate, show blue
- status = "bg-blue";
- } else if (calendarEvent.end && now > calendarEvent.end) {
- // after endDate, show grey
- status = "bg-grey";
- } else if (calendarEvent.recurrence) {
- // TODO: Implement RRule support
- }
- }
- }
- }
-
- return status;
- }
-
- protected _updateSelectedNodes() {
- const actuallySelectedIds: number[] = [];
- const selectedNodes: RulesetNode[] = [];
- if (this._nodes) {
- this._nodes.forEach((node) => {
- if (this.selectedIds && this.selectedIds.indexOf(node.ruleset!.id!) >= 0) {
- actuallySelectedIds.push(node.ruleset!.id!);
- selectedNodes.push(node);
- node.selected = true;
- } else {
- node.selected = false;
- }
- });
- }
-
- this.selectedIds = actuallySelectedIds;
- const oldSelection = this._selectedNodes;
- this._selectedNodes = selectedNodes;
- this.dispatchEvent(new OrRulesSelectionEvent({
- oldNodes: oldSelection,
- newNodes: selectedNodes
- }));
- }
-
- protected static _updateSort(nodes: RulesetNode[], sortFunction: (a: RulesetNode, b: RulesetNode) => number) {
- if (!nodes) {
- return;
- }
-
- nodes.sort(sortFunction);
- }
-
- protected _onNodeClicked(evt: MouseEvent, node: RulesetNode) {
- if (evt.defaultPrevented) {
- return;
- }
-
- evt.preventDefault();
-
- let selectedNodes: RulesetNode[] = [];
- const index = this._selectedNodes.indexOf(node);
- let select = true;
- let deselectOthers = true;
- const multiSelect = !this._isReadonly() && this.multiSelect && (!this.config || !this.config.controls || !this.config.controls.multiSelect);
-
- if (multiSelect && (evt.ctrlKey || evt.metaKey)) {
- deselectOthers = false;
- if (index >= 0 && this._selectedNodes && this._selectedNodes.length > 1) {
- select = false;
- }
- }
-
- if (deselectOthers) {
- selectedNodes = [node];
- } else if (select) {
- if (index < 0) {
- selectedNodes = [...this._selectedNodes];
- selectedNodes.push(node);
- }
- } else if (index >= 0) {
- selectedNodes = [...this._selectedNodes];
- selectedNodes.splice(index, 1);
- }
-
- Util.dispatchCancellableEvent(this, new OrRulesRequestSelectionEvent({
- oldNodes: this._selectedNodes,
- newNodes: selectedNodes
- })).then((detail) => {
- if (detail.allow) {
- this.selectedIds = detail.detail.newNodes.map((node) => node.ruleset.id!);
- }
- });
- }
-
- protected _onCopyClicked() {
- if (this._selectedNodes.length !== 1) {
- return;
- }
-
- const node = this._selectedNodes[0];
- const ruleset = JSON.parse(JSON.stringify(node.ruleset)) as RulesetUnion;
- delete ruleset.lastModified;
- delete ruleset.createdOn;
- delete ruleset.status;
- delete ruleset.error;
- delete ruleset.id;
- ruleset.name = ruleset.name + " copy";
-
- if (this.config && this.config.rulesetCopyHandler && !this.config.rulesetCopyHandler(ruleset)) {
- return;
- }
-
- Util.dispatchCancellableEvent(this, new OrRulesRequestAddEvent({
- ruleset: ruleset,
- sourceRuleset: node.ruleset
- })).then((detail) => {
- if (detail.allow) {
- this.dispatchEvent(new OrRulesAddEvent(detail.detail));
- }
- });
- }
-
- protected _onAddClicked(lang: RulesetLang) {
- const type = this._globalRulesets ? "global": "realm";
- const realm = manager.isSuperUser() ? manager.displayRealm : manager.config.realm;
- const ruleset: RulesetUnion = {
- id: 0,
- type: type,
- name: OrRules.DEFAULT_RULESET_NAME,
- lang: lang,
- realm: realm,
- rules: undefined
- };
-
- if (this.config && this.config.rulesetAddHandler && !this.config.rulesetAddHandler(ruleset)) {
- return;
- }
-
- if (this.config && this.config.rulesetTemplates && this.config.rulesetTemplates[lang]) {
- ruleset.rules = this.config.rulesetTemplates[lang];
- } else {
- ruleset.rules = RuleViewInfoMap[lang].viewRulesetTemplate;
- }
-
- // Ensure config hasn't messed with certain values
- if (type === "realm") {
- (ruleset as RealmRuleset).realm = realm;
- }
-
- const detail = {
- ruleset: ruleset,
- isCopy: false
- };
-
- Util.dispatchCancellableEvent(this, new OrRulesRequestAddEvent(detail))
- .then((detail) => {
- if (detail.allow) {
- this.dispatchEvent(new OrRulesAddEvent(detail.detail));
- }
- });
- }
-
- protected _onDeleteClicked() {
- if (this._selectedNodes.length > 0) {
- Util.dispatchCancellableEvent(this, new OrRulesRequestDeleteEvent(this._selectedNodes))
- .then((detail) => {
- if (detail.allow) {
- this._doDelete();
- }
- });
- }
- }
-
- protected _doDelete() {
-
- if (!this._selectedNodes || this._selectedNodes.length === 0) {
- return;
- }
-
- const rulesetsToDelete = this._selectedNodes.map((rulesetNode) => rulesetNode.ruleset);
- const rulesetNamesToDelete = rulesetsToDelete.map(ruleset => "\n- " + ruleset.name);
-
- const doDelete = async () => {
- this.disabled = true;
- let fail = false;
-
- for (const ruleset of rulesetsToDelete) {
-
- if (this.config && this.config.rulesetDeleteHandler && !this.config.rulesetDeleteHandler(ruleset)) {
- continue;
- }
-
- try {
- let response: GenericAxiosResponse<void>;
-
- switch (ruleset.type) {
- case "asset":
- response = await manager.rest.api.RulesResource.deleteAssetRuleset(ruleset.id!);
- break;
- case "realm":
- response = await manager.rest.api.RulesResource.deleteRealmRuleset(ruleset.id!);
- break;
- case "global":
- response = await manager.rest.api.RulesResource.deleteGlobalRuleset(ruleset.id!);
- break;
- }
-
- if (response.status !== 204) {
- console.error("Delete ruleset returned unexpected status '" + response.status + "': " + JSON.stringify(ruleset, null, 2));
- fail = true;
- }
- } catch (e) {
- console.error("Failed to delete ruleset: " + JSON.stringify(ruleset, null, 2), e);
- fail = true;
- }
- }
-
- if (fail) {
- showErrorDialog(i18next.t("deleteAssetsFailed"));
- }
-
- this.disabled = false;
- this.refresh();
- };
-
- // Confirm deletion request
- showOkCancelDialog(i18next.t("deleteRulesets"), i18next.t("deleteRulesetsConfirm", { ruleNames: rulesetNamesToDelete}), i18next.t("delete"))
- .then((ok) => {
- if (ok) {
- doDelete();
- }
- });
- }
-
- protected _onSearchClicked() {
-
- }
-
- protected _onSortClicked(sortBy: string) {
- this.sortBy = sortBy;
- }
-
- protected _getSortFunction(): (a: RulesetNode, b: RulesetNode) => number {
- switch (this.sortBy) {
- case "createdOn":
- return Util.sortByNumber((node: RulesetNode) => (node.ruleset as any)![this.sortBy!]);
- case "status":
- return Util.sortByString((node: RulesetNode) => (node.ruleset as any)![this.sortBy!]);
- default:
- return Util.sortByString((node: RulesetNode) => (node.ruleset as any)![this.sortBy!]);
- }
- }
-
- protected _getRealm(): string | undefined {
- if (manager.isSuperUser()) {
- return manager.displayRealm;
- }
-
- return manager.getRealm();
- }
-
- protected async _loadRulesets() {
- const sortFunction = this._getSortFunction();
- let data;
-
- // Global rulesets
- if (this._globalRulesets) {
- if (this._rulesetPromises.size == 0 && !this._rulesetPromises.has("global")) {
- this._rulesetPromises.set("global", new Promise<GlobalRuleset[]>(async (resolve) => {
- const response = await manager.rest.api.RulesResource.getGlobalRulesets({fullyPopulate: true});
- resolve(response.data);
- }));
- }
- data = await this._rulesetPromises.get("global");
- this._rulesetPromises.delete("global");
- }
-
- // Realm rulesets
- else {
- const ruleRealm: string = this._getRealm() || manager.displayRealm;
- if (this._rulesetPromises.size == 0 && !this._rulesetPromises.has(ruleRealm)) {
- this._rulesetPromises.set(ruleRealm, new Promise<RealmRuleset[]>(async (resolve) => {
- const params = {fullyPopulate: true, language: this._allowedLanguages}
- const response = await manager.rest.api.RulesResource.getRealmRulesets(ruleRealm, params);
- resolve(response.data);
- }));
- }
- data = await this._rulesetPromises.get(ruleRealm);
- this._rulesetPromises.delete(ruleRealm);
- }
-
- // ... building the nodes
- if (data) {
- this._buildTreeNodes(data, sortFunction);
- }
- }
-
- protected _buildTreeNodes(rulesets: RealmRuleset[], sortFunction: (a: RulesetNode, b: RulesetNode) => number) {
- if (!rulesets || rulesets.length === 0) {
- this._nodes = [];
- } else {
-
- const nodes = rulesets.map((ruleset) => {
- return {
- ruleset: ruleset
- } as RulesetNode;
- });
-
- nodes.sort(sortFunction);
- this._nodes = nodes;
- }
- if (this.selectedIds && this.selectedIds.length > 0) {
- this._updateSelectedNodes();
- }
- this._showLoading = false;
- }
-}
diff --git a/ui/component/or-rules/src/or-rule-text-viewer.ts b/ui/component/or-rules/src/or-rule-text-viewer.ts
index ff7a4052f..f76cd5fef 100644
--- a/ui/component/or-rules/src/or-rule-text-viewer.ts
+++ b/ui/component/or-rules/src/or-rule-text-viewer.ts
@@ -1,3 +1,22 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
import {OrRulesRuleChangedEvent, RulesConfig, RuleView} from "./index";
import {css, html, LitElement, TemplateResult} from "lit";
import {customElement, property} from "lit/decorators.js";
diff --git a/ui/component/or-rules/src/or-rule-tree.ts b/ui/component/or-rules/src/or-rule-tree.ts
new file mode 100644
index 000000000..17b80bb82
--- /dev/null
+++ b/ui/component/or-rules/src/or-rule-tree.ts
@@ -0,0 +1,613 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+import {OrTreeMenu, TreeMenuSelection, TreeMenuSorting, TreeNode} from "@openremote/or-tree-menu";
+import {customElement, property, state} from "lit/decorators.js";
+import {RealmRuleset, RulesetLang, RulesetStatus, RulesetUnion} from "@openremote/model";
+import {css, html, PropertyValues, TemplateResult} from "lit";
+import manager, {Util} from "@openremote/core";
+import {i18next} from "@openremote/or-translate";
+import {getContentWithMenuTemplate} from "@openremote/or-mwc-components/or-mwc-menu";
+import {InputType, OrInputChangedEvent} from "@openremote/or-mwc-components/or-mwc-input";
+import {showOkCancelDialog} from "@openremote/or-mwc-components/or-mwc-dialog";
+import {ListItem} from "@openremote/or-mwc-components/or-mwc-list";
+import {
+ OrRules,
+ OrRulesAddEvent,
+ OrRulesRequestAddEvent,
+ OrRulesRequestDeleteEvent,
+ OrRulesRequestGroupEvent,
+ OrRulesRequestSelectionEvent,
+ OrRulesSelectionEvent,
+ RulesConfig,
+ RulesetGroupNode,
+ RulesetNode,
+ RuleViewInfoMap
+} from "./index";
+import {ifDefined} from "lit/directives/if-defined.js";
+import {when} from "lit/directives/when.js";
+
+const styling = css`
+ .iconfill-gray {
+ --or-icon-fill: var(--internal-or-rules-list-icon-color-ok);
+ }
+
+ .iconfill-red {
+ --or-icon-fill: var(--internal-or-rules-list-icon-color-error);
+ }
+
+ #rules-tree-global-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: 0 15px;
+ min-height: 48px;
+ background: var(--or-app-color3, #4c4c4c);
+ color: var(--or-app-color7, white);
+ --or-icon-fill: var(--or-app-color7, white);
+ }
+`;
+
+export interface RuleTreeNode extends TreeNode {
+ ruleset?: RulesetUnion;
+}
+
+export enum RuleTreeSorting {
+ NAME = "name", CREATED_ON = "createdOn", LANGUAGE = "language", STATUS = "status"
+}
+
+@customElement("or-rule-tree")
+export class OrRuleTree extends OrTreeMenu {
+
+ public static DEFAULT_ALLOWED_LANGUAGES = [RulesetLang.JSON, RulesetLang.GROOVY, RulesetLang.JAVASCRIPT, RulesetLang.FLOW];
+
+ /**
+ * List of rules visible in the tree menu
+ */
+ @property({type: Array})
+ public rules?: RulesetUnion[];
+
+ /**
+ * Rules configuration object, for example to only allow certain ruleset types
+ */
+ @property({type: Object})
+ public config?: RulesConfig;
+
+ /**
+ * Defines whether only global rulesets should be visible.
+ */
+ @property({type: Boolean})
+ public global = false;
+
+ /**
+ * Sets every element in the tree to readonly mode
+ */
+ @property({type: Boolean})
+ public readonly = false;
+
+ nodes: RuleTreeNode[] = [];
+ draggable = true;
+ selection = TreeMenuSelection.MULTI;
+ sortOptions: any[] = [RuleTreeSorting.NAME, RuleTreeSorting.CREATED_ON, RuleTreeSorting.STATUS, RuleTreeSorting.LANGUAGE];
+ sortBy: any = RuleTreeSorting.NAME;
+ groupFirst = true;
+ menuTitle = "rules";
+
+ @state()
+ protected _loadingPromises: Promise<boolean>[] = [];
+
+ @state()
+ protected _selectedTypes: Set<('group' | 'ruleset')> = new Set();
+
+ // Cache of empty groups (when no rule has this groupId), so they stay during refreshes.
+ protected _cachedEmptyGroupNodes: RuleTreeNode[] = [];
+
+ static get styles(): any[] {
+ return [...super.styles, styling];
+ }
+
+ protected willUpdate(changedProps: PropertyValues) {
+ if (changedProps.has("rules")) {
+ if (!this.rules) {
+ this._loadRulesets(this.global).then(rulesets => this.rules = rulesets);
+ } else {
+ this.nodes = [...this._getRuleNodes(this.rules), ...this._cachedEmptyGroupNodes];
+ }
+ }
+ if (changedProps.has("nodes")) {
+ this._cachedEmptyGroupNodes = this.nodes?.filter(n => !!n.children && n.children.length === 0) || [];
+ }
+ if (changedProps.has("config") && this.config) {
+ if(this.config.controls?.multiSelect !== undefined) {
+ this.selection = this.config.controls?.multiSelect ? TreeMenuSelection.MULTI : TreeMenuSelection.LEAF;
+ }
+ }
+ return super.willUpdate(changedProps);
+ }
+
+ protected firstUpdated(changedProps: PropertyValues) {
+ if (!this.rules) {
+ this._loadRulesets(this.global).then(rulesets => {
+ this.rules = rulesets;
+ });
+ }
+ }
+
+ protected _getSingleNodeSlotTemplate(node: RuleTreeNode): TemplateResult {
+ return html`
+ <or-icon slot="prefix" icon="${this._getRulesetLangIcon(node.ruleset?.lang)}"></or-icon>
+ <span>${node.label}</span>
+ <or-icon slot="suffix" icon=${ifDefined(this._getRulesetStatusIcon(node.ruleset?.status))}
+ class=${this._getRulesetStatusColorClass(node.ruleset?.status)}
+ ></or-icon>
+ `;
+ }
+
+ protected _getGroupNodeSlotTemplate(node: RuleTreeNode): TemplateResult {
+ let icon;
+ const childrenStatus = (node.children as RuleTreeNode[] | undefined)?.map(child => child.ruleset?.status).filter(status => status) as RulesetStatus[];
+ const hasError = childrenStatus?.find(c => [RulesetStatus.LOOP_ERROR, RulesetStatus.EXECUTION_ERROR, RulesetStatus.COMPILATION_ERROR].includes(c)) || false;
+ if (hasError) {
+ const errorCounts = [RulesetStatus.LOOP_ERROR, RulesetStatus.EXECUTION_ERROR, RulesetStatus.COMPILATION_ERROR].map(err => [err, childrenStatus.filter(s => s === err).length] as [RulesetStatus, number]);
+ const mostCommonError = errorCounts.reduce((prev, curr) => curr[1] > prev[1] ? curr : prev)[0];
+ icon = this._getRulesetStatusIcon(mostCommonError);
+ }
+ return html`
+ <or-icon slot="prefix" icon="folder"></or-icon>
+ <span>${node.label}</span>
+ <or-icon slot="suffix" icon=${ifDefined(icon)} class="iconfill-red"></or-icon>
+ `;
+ }
+
+ protected _getHeaderTemplate(): TemplateResult {
+ return html`
+ ${when(manager.isSuperUser(), () => html`
+ <div id="rules-tree-global-header">
+ <or-translate value="realmRules"></or-translate>
+ <or-mwc-input type=${InputType.SWITCH} @or-mwc-input-changed=${this._onGlobalSwitch}></or-mwc-input>
+ <or-translate value="globalRules"></or-translate>
+ </div>
+ `)}
+ <div id="tree-header">
+ <h3 id="tree-header-title">
+ <or-translate value=${this.menuTitle}></or-translate>
+ </h3>
+ <div id="tree-header-actions">
+ ${when((this._selectedTypes.size === 1 && this._selectedTypes.has('ruleset')) && !this.readonly, () => html`
+ ${when(this._findSelectedTreeNodes().length === 1, () => html`
+ <or-mwc-input type=${InputType.BUTTON} icon="content-copy" @or-mwc-input-changed=${this._onCopyClicked}></or-mwc-input>
+ `)}
+ <or-mwc-input type=${InputType.BUTTON} icon="delete" @or-mwc-input-changed=${this._onDeleteClicked}></or-mwc-input>
+ `)}
+ ${when((this._selectedTypes.size === 1 && this._selectedTypes.has('group')) && !this.readonly, () => html`
+ <or-mwc-input type=${InputType.BUTTON} icon="delete" @or-mwc-input-changed=${this._onDeleteClicked}></or-mwc-input>
+ `)}
+ ${this._getAddActionTemplate()}
+ ${this._getSortActionTemplate(this.sortBy, this.sortOptions)}
+ </div>
+ </div>
+ `;
+ }
+
+ /**
+ * HTML callback on when the global switch is toggled.
+ * It normally toggles between 'global' and 'realm' rulesets when the user is a superuser.
+ */
+ protected _onGlobalSwitch(ev: OrInputChangedEvent) {
+ this.global = ev.detail.value;
+ this.refresh();
+ }
+
+ /**
+ * HTML callback on when the 'copy' menu option is pressed.
+ * The function duplicates the current selected rule, and shows it inside the viewer window.
+ */
+ protected _onCopyClicked(_ev: OrInputChangedEvent) {
+ const selected = this._findSelectedTreeNodes() as RuleTreeNode[];
+ if (selected.length !== 1) {
+ return;
+ }
+
+ const node = selected[0];
+ const ruleset = JSON.parse(JSON.stringify(node.ruleset)) as RulesetUnion;
+ delete ruleset.lastModified;
+ delete ruleset.createdOn;
+ delete ruleset.status;
+ delete ruleset.error;
+ delete ruleset.id;
+ ruleset.name = ruleset.name + " copy";
+
+ if (this.config && this.config.rulesetCopyHandler && !this.config.rulesetCopyHandler(ruleset)) {
+ return;
+ }
+
+ Util.dispatchCancellableEvent(this, new OrRulesRequestAddEvent({
+ ruleset: ruleset,
+ sourceRuleset: node.ruleset
+ })).then((detail) => {
+ if (detail.allow) {
+ this.dispatchEvent(new OrRulesAddEvent(detail.detail));
+ }
+ });
+ }
+
+ /**
+ * HTML callback on when the 'delete' menu option is pressed.
+ * The function deletes the rule that is affiliated with selected tree node,
+ * after prompting a modal that the user confirms this action.
+ */
+ protected _onDeleteClicked(_ev: OrInputChangedEvent) {
+ const selected = this._findSelectedTreeNodes() as RuleTreeNode[];
+ if (selected.length > 0) {
+ const selectedRules = selected.map(node => node.ruleset).filter(x => x) as RulesetUnion[];
+
+ // If groups are selected, loop through the children, and add them to the selectedRules;
+ const groupNodes = selected.filter(group => group.children);
+ const groupNames = groupNodes.map(node => node.label);
+ const selectedChildNodes = groupNodes.flatMap(group => group.children as RuleTreeNode[]);
+ const selectedChildRules = selectedChildNodes.flatMap(node => node.ruleset ? [node.ruleset] : [])
+ selectedRules.push(...selectedChildRules);
+
+ // Transform rules into RulesetNode for consumers of the or-rule-tree
+ const selectedRuleNodes = selectedRules.map(ruleset => ({ ruleset: ruleset, selected: true }) as RulesetNode);
+
+ // If only groups are selected without any rules, prompt "delete groups" dialog.
+ if(selectedRuleNodes.length === 0 && groupNodes.length > 0) {
+ showOkCancelDialog(i18next.t("deleteRulesetGroups"), i18next.t("deleteRulesetGroupsConfirm", { groupNames: groupNames }), i18next.t("delete"))
+ .then((ok) => {
+ if(ok) {
+ this.deselectAllNodes();
+ this.nodes = this.nodes.filter(n => !groupNames.includes(n.label));
+ }
+ })
+ return;
+ }
+
+ // Request deletion of rulesets, and prompt dialog.
+ Util.dispatchCancellableEvent(this, new OrRulesRequestDeleteEvent(selectedRuleNodes))
+ .then((detail) => {
+ if (detail.allow) {
+ const names = selectedRules.map(r => r.name);
+ showOkCancelDialog(i18next.t("deleteRulesets"), i18next.t("deleteRulesetsConfirm", { ruleNames: names }), i18next.t("delete"))
+ .then((ok) => {
+ if (ok) {
+ this.deselectAllNodes();
+ this._deleteRulesets(selectedRules)
+ .catch(e => console.error(e))
+ .finally(() => {
+ this.nodes = this.nodes.filter(n => !groupNames.includes(n.label));
+ this.refresh()
+ });
+ }
+ });
+ }
+ });
+ }
+ }
+
+ /**
+ * Utility function that returns a promise for deleting a list of rulesets, based on their type.
+ * @param rulesets - List of rulesets to delete.
+ */
+ protected async _deleteRulesets(rulesets: RulesetUnion[]) {
+ const promises: Promise<any>[] = [];
+ rulesets.forEach(ruleset => {
+ switch (ruleset.type) {
+ case "asset":
+ promises.push(manager.rest.api.RulesResource.deleteAssetRuleset(ruleset.id!))
+ break;
+ case "realm":
+ promises.push(manager.rest.api.RulesResource.deleteRealmRuleset(ruleset.id!));
+ break;
+ case "global":
+ promises.push(manager.rest.api.RulesResource.deleteGlobalRuleset(ruleset.id!));
+ break;
+ }
+ });
+ return Promise.all(promises);
+ }
+
+ /**
+ * Public function that allows consumers to select a ruleset in the tree.
+ * It finds the tree node in the UI, and selects it.
+ * @param ruleset - ruleset in the tree to be selected
+ * @param silent - skips the modal of 'discard changes' and does not dispatch an event
+ */
+ public selectRuleset(ruleset: RulesetUnion, silent = false) {
+ const rulesetNode = this.nodes.find(n => n.ruleset === ruleset);
+ if(rulesetNode) {
+ const uiNode = this._getUiNodeFromTree(rulesetNode);
+ if(uiNode) this._selectNode(uiNode, !silent);
+ } else {
+ console.warn("Could not select ruleset; it was not found.")
+ }
+ }
+
+ protected _dispatchSelectEvent(nodes?: RuleTreeNode[]): boolean {
+
+ const lastSelected = this._lastSelectedNode ? this._getTreeNodeFromTree(this._lastSelectedNode) as RuleTreeNode : undefined;
+
+ // Only select if ONE is selected
+ const newSelected = (!nodes || nodes.length > 1) ? undefined : nodes[0];
+
+ const isGroupNode = (node?: RuleTreeNode) => !!node?.children;
+ const oldNodes = lastSelected ? isGroupNode(lastSelected) ? [{type: "group", groupId: lastSelected.id} as RulesetGroupNode] : [{type: "rule", ruleset: lastSelected.ruleset!, selected: false} as RulesetNode] : [];
+ const newNodes = newSelected ? isGroupNode(newSelected) ? [{type: "group", groupId: newSelected.id} as RulesetGroupNode] : [{type: "rule", ruleset: newSelected.ruleset!, selected: true} as RulesetNode] : [];
+
+ // Ask for consumers if selection is allowed. If event.preventDefault() is called, we cancel the selection
+ const success = this.dispatchEvent(new OrRulesRequestSelectionEvent({oldNodes: oldNodes, newNodes: newNodes}));
+ if(!success) return false;
+
+ // If succeeded, actually sent the "select" event.
+ this.dispatchEvent(new OrRulesSelectionEvent({oldNodes: oldNodes, newNodes: newNodes}));
+
+ // and update the selected types in cache
+ const selectedTypes = new Set<'group' | 'ruleset'>();
+ if(nodes?.find(n => isGroupNode(n))) selectedTypes.add('group');
+ if(nodes?.find(n => !isGroupNode(n))) selectedTypes.add('ruleset');
+ this._selectedTypes = selectedTypes;
+
+ return super._dispatchSelectEvent(nodes);
+ }
+
+ public deselectAllNodes() {
+ super.deselectAllNodes();
+ this._selectedTypes = new Set();
+ }
+
+ /**
+ * Gets the list of {@link RuleTreeNode[]} (tree nodes) based on a list of rulesets.
+ * It maps the ruleset to the correct tree node format. For example, when a groupId is set in the Ruleset meta,
+ * we group them together as children of a new group node.
+ * @param rules - List of rulesets
+ */
+ protected _getRuleNodes(rules: RulesetUnion[]): RuleTreeNode[] {
+ const groupList = new Set(rules.map(r => r.meta?.groupId).filter(x => x)) as Set<string>;
+ const groupedNodes = Array.from(groupList).map(group => ({
+ id: group,
+ label: group,
+ children: rules.filter(r => (r.meta as any)?.groupId === group).map(rule => ({
+ id: rule.id?.toString(),
+ ruleset: rule,
+ label: rule.name
+ }) as RuleTreeNode)
+ }) as RuleTreeNode);
+
+ const ungroupedRules = rules.filter(r => !r.meta?.groupId);
+ const ungroupedNodes = ungroupedRules.map(rule => ({
+ id: rule.id?.toString(),
+ ruleset: rule,
+ label: rule.name
+ } as RuleTreeNode));
+
+ return [...ungroupedNodes, ...groupedNodes];
+ }
+
+ /**
+ * Utility function that returns a promise for loading the rulesets, based on the {@link global} and {@link realm} parameters
+ * @param global - Whether only global rulesets should be loaded instead.
+ * @param realm - Name of the realm to load (if global is `false` or `undefined`)
+ */
+ protected async _loadRulesets(global = false, realm = manager.displayRealm): Promise<RulesetUnion[]> {
+ if (global) {
+ const promise = manager.rest.api.RulesResource.getGlobalRulesets({ fullyPopulate: true });
+ return (await promise).data;
+ } else {
+ const promise = manager.rest.api.RulesResource.getRealmRulesets(realm, { fullyPopulate: true });
+ return (await promise).data;
+ }
+ }
+
+ /**
+ * Refreshes the tree content, and re-fetches the list of rules.
+ */
+ public async refresh() {
+ this._cachedEmptyGroupNodes = this.nodes.filter(n => !!n.children && n.children.length === 0);
+ await this.getUpdateComplete();
+ const promise = this._loadRulesets(this.global);
+ promise.then(rulesets => {
+ this.rules = rulesets;
+ });
+ return promise;
+ }
+
+ /**
+ * Generates a HTML {@link TemplateResult} for the "add" button in the controls menu.
+ */
+ protected _getAddActionTemplate(): TemplateResult {
+ const menuOptions: (ListItem | null)[] = (this._getAllowedLanguages() || []).map(l =>
+ ({value: l, text: i18next.t("rulesLanguages." + l)} as ListItem)
+ );
+ menuOptions.push(null);
+ menuOptions.push({value: "group", text: i18next.t("group")} as ListItem);
+
+ const onValueChange = (value: string) => {
+ value === "group" ? this._onGroupAddClick() : this._onRulesetAddClick(value as RulesetLang);
+ };
+
+ return getContentWithMenuTemplate(
+ html`
+ <or-mwc-input type=${InputType.BUTTON} icon="plus"></or-mwc-input>`,
+ menuOptions,
+ undefined,
+ value => onValueChange(String(value))
+ );
+ }
+
+ /**
+ * HTML callback function for clicking a ruleset language in the "add rule" menu.
+ * @param lang - The language to be used for adding a rule.
+ * @param global - Whether to create a global ruleset or not.
+ */
+ protected _onRulesetAddClick(lang: RulesetLang, global = this.global) {
+ const type = global ? "global" : "realm";
+ const realm = manager.isSuperUser() ? manager.displayRealm : manager.config.realm;
+ const ruleset: RulesetUnion = {
+ id: 0,
+ type: type,
+ name: OrRules.DEFAULT_RULESET_NAME,
+ lang: lang,
+ realm: realm,
+ rules: undefined
+ };
+
+ if (this.config && this.config.rulesetAddHandler && !this.config.rulesetAddHandler(ruleset)) {
+ return;
+ }
+
+ if (this.config && this.config.rulesetTemplates && this.config.rulesetTemplates[lang]) {
+ ruleset.rules = this.config.rulesetTemplates[lang];
+ } else {
+ ruleset.rules = RuleViewInfoMap[lang].viewRulesetTemplate;
+ }
+
+ // Ensure config hasn't messed with certain values
+ if (type === "realm") {
+ (ruleset as RealmRuleset).realm = realm;
+ }
+
+ const detail = {
+ ruleset: ruleset,
+ isCopy: false
+ };
+
+ Util.dispatchCancellableEvent(this, new OrRulesRequestAddEvent(detail))
+ .then((detail) => {
+ if (detail.allow) {
+ this.dispatchEvent(new OrRulesAddEvent(detail.detail));
+ }
+ });
+ }
+
+ /**
+ * HTML callback function for clicking "add group" in the controls menu.
+ */
+ protected _onGroupAddClick() {
+ this.deselectAllNodes();
+ const groupName = i18next.t('ruleGroupNameDefault') || "Group name"
+ this.dispatchEvent(new OrRulesRequestGroupEvent(groupName));
+ }
+
+ protected _getSortFunction(sortBy?: TreeMenuSorting): (a: RuleTreeNode, b: RuleTreeNode) => number {
+ const sorting = sortBy as RuleTreeSorting | undefined;
+ switch (sorting) {
+ case RuleTreeSorting.LANGUAGE: {
+ return Util.sortByString(node => node.ruleset?.lang || node.label);
+ }
+ case RuleTreeSorting.CREATED_ON: {
+ return Util.sortByNumber(node => node.ruleset?.createdOn || 0);
+ }
+ case RuleTreeSorting.STATUS: {
+ return Util.sortByString(node => node.ruleset?.status || node.label);
+ }
+ default: {
+ return super._getSortFunction(sortBy);
+ }
+ }
+ }
+
+ /**
+ * Utility function for getting the list of allowed languages based on {@link config} and {@link global} parameters.
+ * @param config - Rules configuration to use
+ * @param global - Whether only to include global rulesets
+ */
+ protected _getAllowedLanguages(config = this.config, global = this.global): RulesetLang[] | undefined {
+ const languages = config?.controls?.allowedLanguages ? [...config.controls.allowedLanguages] : OrRuleTree.DEFAULT_ALLOWED_LANGUAGES;
+ const groovyIndex = languages.indexOf(RulesetLang.GROOVY);
+ const flowIndex = languages.indexOf(RulesetLang.FLOW);
+ if (!manager.isSuperUser()) {
+ if (groovyIndex > 0) languages.splice(groovyIndex, 1);
+ } else if (groovyIndex < 0) {
+ languages.push(RulesetLang.GROOVY);
+ }
+ if (global) {
+ if (flowIndex > 0) languages.splice(flowIndex, 1);
+ }
+ return languages;
+ }
+
+ /**
+ * Utility function that gets a Material Design icon based on the ruleset language
+ * @param lang - The ruleset language to get an icon of.
+ */
+ protected _getRulesetLangIcon(lang?: RulesetLang): string {
+ switch (lang) {
+ case (RulesetLang.JSON):
+ return "ray-start-arrow";
+ case (RulesetLang.FLOW):
+ return "transit-connection-variant";
+ case (RulesetLang.GROOVY):
+ return "alpha-g-box-outline";
+ case (RulesetLang.JAVASCRIPT):
+ return "language-javascript";
+ default:
+ return "mdi-state-machine";
+ }
+ }
+
+ /**
+ * Utility function that gets a Material Design icon based on the ruleset status
+ * @param status - The ruleset status to get an icon of.
+ */
+ protected _getRulesetStatusIcon(status?: RulesetStatus): string | undefined {
+ switch (status) {
+ case RulesetStatus.DEPLOYED:
+ return;
+ case RulesetStatus.READY:
+ return "check";
+ case RulesetStatus.COMPILATION_ERROR:
+ case RulesetStatus.LOOP_ERROR:
+ case RulesetStatus.EXECUTION_ERROR:
+ return "alert-octagon";
+ case RulesetStatus.DISABLED:
+ return "minus-circle";
+ case RulesetStatus.PAUSED:
+ return "calendar-arrow-right";
+ case RulesetStatus.EXPIRED:
+ return "calendar-remove";
+ case RulesetStatus.REMOVED:
+ return "close";
+ default:
+ return "stop";
+ }
+ }
+
+ /**
+ * Utility function that returns a CSS class for the icon element, based on the ruleset status
+ * @param status - The ruleset status to get a CSS class of.
+ */
+ protected _getRulesetStatusColorClass(status?: RulesetStatus): string {
+ switch (status) {
+ case RulesetStatus.DEPLOYED:
+ case RulesetStatus.READY:
+ return "iconfill-gray";
+ case RulesetStatus.COMPILATION_ERROR:
+ case RulesetStatus.LOOP_ERROR:
+ case RulesetStatus.EXECUTION_ERROR:
+ return "iconfill-red";
+ case RulesetStatus.DISABLED:
+ case RulesetStatus.PAUSED:
+ case RulesetStatus.EXPIRED:
+ case RulesetStatus.REMOVED:
+ return "iconfill-gray";
+ default:
+ return "iconfill-gray";
+ }
+ }
+}
diff --git a/ui/component/or-rules/src/or-rule-validity.ts b/ui/component/or-rules/src/or-rule-validity.ts
index 05dacdb1d..502cc3a17 100644
--- a/ui/component/or-rules/src/or-rule-validity.ts
+++ b/ui/component/or-rules/src/or-rule-validity.ts
@@ -1,3 +1,22 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
import {css, html, LitElement, PropertyValues, TemplateResult} from "lit";
import {customElement, property, query} from "lit/decorators.js";
import {CalendarEvent, RulesetUnion, WellknownRulesetMetaItems} from "@openremote/model";
diff --git a/ui/component/or-rules/src/or-rule-viewer.ts b/ui/component/or-rules/src/or-rule-viewer.ts
index e7f0ffe71..eb10f1477 100644
--- a/ui/component/or-rules/src/or-rule-viewer.ts
+++ b/ui/component/or-rules/src/or-rule-viewer.ts
@@ -1,3 +1,22 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
import {css, html, LitElement, PropertyValues, TemplateResult} from "lit";
import {customElement, property, query} from "lit/decorators.js";
import {
@@ -149,7 +168,7 @@ export class OrRuleViewer extends translate(i18next)(LitElement) {
}
public get valid() {
- return this.ruleset && this.view && this._ruleValid && this.ruleset.name && this.ruleset.name.length >= 3 && this.ruleset.name.length < 255;
+ return this.ruleset && this.view && this._ruleValid && this.ruleset.name && this.ruleset.name.length >= 1 && this.ruleset.name.length < 255;
}
public shouldUpdate(_changedProperties: PropertyValues): boolean {
@@ -220,7 +239,7 @@ export class OrRuleViewer extends translate(i18next)(LitElement) {
return html`
<div id="main-wrapper" class="wrapper">
<div id="rule-header">
- <or-mwc-input id="rule-name" outlined .type="${InputType.TEXT}" .label="${i18next.t("ruleName")}" ?focused="${this._focusName}" .value="${this.ruleset ? this.ruleset.name : null}" ?disabled="${this._isReadonly()}" required minlength="3" maxlength="255" @or-mwc-input-changed="${(e: OrInputChangedEvent) => this._changeName(e.detail.value)}"></or-mwc-input>
+ <or-mwc-input id="rule-name" outlined .type="${InputType.TEXT}" .label="${i18next.t("ruleName")}" ?focused="${this._focusName}" .value="${this.ruleset ? this.ruleset.name : null}" ?disabled="${this._isReadonly()}" required minlength="1" maxlength="255" @or-mwc-input-changed="${(e: OrInputChangedEvent) => this._changeName(e.detail.value)}"></or-mwc-input>
<or-icon class="${statusClass}" title="${i18next.t("rulesetStatus." + statusText)}" icon="${statusIcon}"></or-icon>
<span id="rule-id">${this.ruleset.id ? "ID: " + this.ruleset.id : ""}</span>
<div id="rule-header-controls">
diff --git a/ui/component/or-rules/src/style.ts b/ui/component/or-rules/src/style.ts
index 00e6ce7d4..137cbcaa3 100644
--- a/ui/component/or-rules/src/style.ts
+++ b/ui/component/or-rules/src/style.ts
@@ -1,3 +1,22 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
import {DefaultColor5} from "@openremote/core";
import {css, unsafeCSS} from "lit";
diff --git a/ui/component/or-rules/tsconfig.json b/ui/component/or-rules/tsconfig.json
index 274f1a869..43175577c 100644
--- a/ui/component/or-rules/tsconfig.json
+++ b/ui/component/or-rules/tsconfig.json
@@ -15,6 +15,7 @@
{ "path": "../or-mwc-components" },
{ "path": "../or-attribute-input" },
{ "path": "../or-attribute-picker" },
- { "path": "../or-asset-tree" }
+ { "path": "../or-asset-tree" },
+ { "path": "../or-tree-menu" }
]
}
diff --git a/ui/component/or-tree-menu/.npmignore b/ui/component/or-tree-menu/.npmignore
new file mode 100644
index 000000000..e4d5a449c
--- /dev/null
+++ b/ui/component/or-tree-menu/.npmignore
@@ -0,0 +1,8 @@
+build/
+build.gradle
+test/
+src/
+webpack.config.js
+tsconfig.json
+dist/*.map
+*.tsbuildinfo
diff --git a/ui/component/or-tree-menu/README.md b/ui/component/or-tree-menu/README.md
new file mode 100644
index 000000000..cc19cabba
--- /dev/null
+++ b/ui/component/or-tree-menu/README.md
@@ -0,0 +1 @@
+# @openremote/or-tree-menu \<or-tree-menu\>
diff --git a/ui/component/or-tree-menu/build.gradle b/ui/component/or-tree-menu/build.gradle
new file mode 100644
index 000000000..98cdcb8e2
--- /dev/null
+++ b/ui/component/or-tree-menu/build.gradle
@@ -0,0 +1,15 @@
+buildDir = "dist"
+
+task clean() {
+ doLast {
+ delete "dist"
+ }
+}
+
+task prepareUi() {
+ dependsOn clean, npmPrepare
+}
+
+task publishUi() {
+ dependsOn clean, npmPublish
+}
\ No newline at end of file
diff --git a/ui/component/or-tree-menu/package.json b/ui/component/or-tree-menu/package.json
new file mode 100644
index 000000000..e044bbec3
--- /dev/null
+++ b/ui/component/or-tree-menu/package.json
@@ -0,0 +1,31 @@
+{
+ "name": "@openremote/or-tree-menu",
+ "version": "1.3.3",
+ "description": "Web Component for displaying a tree menu of items with a predefined hierarchy",
+ "main": "dist/umd/index.bundle.js",
+ "module": "lib/index.js",
+ "exports": {
+ ".": "./lib/index.js",
+ "./*": "./lib/*.js"
+ },
+ "types": "lib/index.d.ts",
+ "scripts": {
+ "test": "echo \"No tests\" && exit 0",
+ "prepack": "npx webpack"
+ },
+ "author": "OpenRemote",
+ "license": "AGPL-3.0-or-later",
+ "dependencies": {
+ "@mdi/js": "^5.9.55",
+ "@openremote/core": "workspace:*",
+ "@openremote/or-mwc-components": "workspace:*",
+ "@openremote/or-translate": "workspace:*",
+ "lit": "^3.2.1"
+ },
+ "devDependencies": {
+ "@openremote/util": "workspace:*"
+ },
+ "publishConfig": {
+ "access": "public"
+ }
+}
diff --git a/ui/component/or-tree-menu/src/index.ts b/ui/component/or-tree-menu/src/index.ts
new file mode 100644
index 000000000..0b647b16a
--- /dev/null
+++ b/ui/component/or-tree-menu/src/index.ts
@@ -0,0 +1,738 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+import {css, html, LitElement, PropertyValues, TemplateResult} from "lit";
+import {customElement, property, queryAll} from "lit/decorators.js";
+import {map} from "lit/directives/map.js";
+import {when} from "lit/directives/when.js";
+import {InputType} from "@openremote/or-mwc-components/or-mwc-input";
+import {getContentWithMenuTemplate} from "@openremote/or-mwc-components/or-mwc-menu";
+import {ListItem} from "@openremote/or-mwc-components/or-mwc-list";
+import {Util} from "@openremote/core";
+import {OrTreeNode} from "./or-tree-node";
+import {OrTreeGroup} from "./or-tree-group";
+import {moveNodesToGroupNode} from "./util";
+import {OrTreeDragEvent, OrTreeSelectEvent, TreeMenuSelection, TreeMenuSorting, TreeNode} from "./model";
+
+import "./or-tree-group";
+import "./or-tree-node";
+
+export * from "./or-tree-group";
+export * from "./or-tree-node";
+export * from "./model";
+
+const styles = css`
+ * {
+ box-sizing: border-box;
+ }
+
+ #tree-container {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ }
+
+ #tree-list {
+ flex: 1;
+ overflow: hidden auto;
+ list-style: none;
+ padding: 0;
+ margin: 0;
+ }
+
+ or-tree-node > or-tree-node > * {
+ pointer-events: none;
+ }
+
+ or-tree-node {
+ transition: background-color 80ms;
+ }
+
+ or-tree-node[drophover] {
+ background: #e9ecef;
+ }
+
+ #tree-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: 0 15px;
+ min-height: 48px;
+ background: var(--or-app-color4, #4d9d2a);
+ color: var(--or-app-color7, white);
+ --or-icon-fill: var(--or-app-color7, white);
+ }
+
+ #tree-header-title {
+ margin: 0;
+ font-weight: 500;
+ font-size: 16px;
+ }
+
+ #tree-header-actions {
+ display: flex;
+ align-items: center;
+ }
+`;
+
+/**
+ * @event {OrTreeSelectEvent} or-tree-select - Triggers upon selecting a node, and dispatches a list of the nodes selected.
+ * @event {OrTreeDragEvent} or-tree-drag - Triggers upon dragging a node to a new group, and dispatches a list of dragged nodes, the group node, and the updated list of all nodes.
+ */
+@customElement("or-tree-menu")
+export class OrTreeMenu extends LitElement {
+
+ /**
+ * List of node items in the menu.
+ * Uses the TreeNode format for rendering the OrTreeNode elements.
+ */
+ @property({type: Array})
+ public nodes: TreeNode[] = [];
+
+ /**
+ * Changes the allowed selection method within the tree.
+ * Common options are `LEAF`, `SINGLE` and `MULTI`.
+ */
+ @property({type: String})
+ public selection: TreeMenuSelection = TreeMenuSelection.LEAF;
+
+ /**
+ * Disables and enables dragging of nodes into groups.
+ */
+ @property({type: Boolean})
+ public draggable = false;
+
+ /**
+ * Removes the header from the tree menu.
+ */
+ @property({type: Boolean, attribute: "no-header"})
+ public noHeader = false;
+
+ /**
+ * Adjusts the title in the menu header.
+ */
+ @property({type: String, attribute: "menu-title"})
+ public menuTitle = "Tree Menu";
+
+ /**
+ * List of options available to sort the object with
+ */
+ @property({type: Array, attribute: "sort-options"})
+ public sortOptions?: TreeMenuSorting[];
+
+ /**
+ * Represents the selected sorting option
+ */
+ @property({type: String, attribute: "sort-by", reflect: true})
+ public sortBy: TreeMenuSorting = TreeMenuSorting.A_TO_Z;
+
+ /**
+ * Automatically prioritizes the groups, and positions these on top.
+ */
+ @property({type: Boolean, attribute: "group-first"})
+ public groupFirst = false;
+
+ @queryAll("or-tree-node")
+ protected _uiNodes?: NodeListOf<OrTreeNode>;
+
+ @queryAll("or-tree-group")
+ protected _uiGroups?: NodeListOf<OrTreeGroup>;
+
+ // A Map<TreeNode, unique generated ID> to easily identify which TreeNode has been used to render a TreeNodeComponent.
+ protected _treeNodeCache: Map<TreeNode, string> = new Map<TreeNode, string>();
+
+ // Caches the last selected component for use in multi select.
+ protected _lastSelectedNode?: OrTreeNode;
+
+ static get styles() {
+ return [styles];
+ }
+
+ protected willUpdate(changedProps: PropertyValues) {
+ if((changedProps.has("nodes") || changedProps.has("sortBy") || changedProps.has("groupFirst")) && this.nodes) {
+ this.nodes = this._sortNodes(this.nodes, this.sortBy, this.groupFirst);
+ }
+ // If the selection method has been changed, for example from LEAF to SINGLE, we deselect everything
+ if(changedProps.has("selection") && changedProps.get("selection") && this.selection) {
+ this.deselectAllNodes();
+ }
+ return super.willUpdate(changedProps);
+ }
+
+ render(): TemplateResult {
+ return html`
+ <div id="tree-container">
+ ${when(!this.noHeader, () => this._getHeaderTemplate())}
+ ${this._getTreeTemplate(this.nodes)}
+ ${this._getErrorTemplate()}
+ </div>
+ `;
+ }
+
+ /* ------------------------------------------------------------- */
+ //region Public functions for or-tree-menu
+ /* ------------------------------------------------------------- */
+
+ /**
+ * Function that moves an array of {@link TreeNode} into another {@link TreeNode}, by adding them to their children.
+ * The function takes care of removing the nodes from the former group, and makes sure no duplicates end up in the list.
+ *
+ * @param nodesToMove - The array of nodes that are moved into a group.
+ * @param groupNode - The group node to insert nodesToMove in.
+ */
+ public moveNodesToGroup(nodesToMove: TreeNode[], groupNode?: TreeNode) {
+ this.nodes = moveNodesToGroupNode(nodesToMove, groupNode, this.nodes);
+ }
+
+ //endregion
+
+ /* ------------------------------------------------------------- */
+ //region HTML Templates functions
+ /* ------------------------------------------------------------- */
+
+ /**
+ * Returns a HTML template that displays the tree menu.
+ * @param nodes - List of nodes to be rendered
+ */
+ protected _getTreeTemplate(nodes: TreeNode[]): TemplateResult {
+ this._treeNodeCache = new Map(); // clear cache on every new render of the tree
+ return html`
+ <ol id="tree-list" @dragover=${this._onDragOverList} @drop=${this._onDragDropList}>
+ ${map(nodes, node => this._getNodeTemplate(node))}
+ </ol>
+ `;
+ }
+
+ /**
+ * Returns an HTML template for displaying a single node within a tree menu. This can both be a group or a solo node.
+ * @param node - Node to be rendered
+ * @param parent - Optional parent (group node) if the node is placed inside a group
+ */
+ protected _getNodeTemplate(node: TreeNode, parent?: TreeNode): TemplateResult {
+ const isGroup = node.children;
+ if (isGroup) {
+ return this._getGroupNodeTemplate(node, parent);
+ } else {
+ return this._getSingleNodeTemplate(node, parent);
+ }
+ }
+
+ /**
+ * Returns an HTML template for displaying a single node
+ * @param node - Node to be rendered
+ * @param parent - Optional parent (group node) if the node is placed inside a group
+ */
+ protected _getSingleNodeTemplate(node: TreeNode, parent?: TreeNode): TemplateResult {
+ const randomId = this._setTreeNodeId(node);
+ return html`
+ <li draggable=${this.draggable}
+ @dragstart=${(ev: DragEvent) => this._onDragStart(ev, node)}
+ @dragover=${(ev: DragEvent) => this._onDragOverSingleNode(ev, node, parent)}
+ @dragleave=${(ev: DragEvent) => this._onDragLeaveSingleNode(ev, node, parent)}
+ @drop=${(ev: DragEvent) => this._onDragDropSingleNode(ev, node, parent)}>
+ <or-tree-node id=${randomId} ?selected=${node.selected} ?readonly=${node.readonly} @click="${this._onTreeNodeClick}">
+ ${this._getSingleNodeSlotTemplate(node)}
+ </or-tree-node>
+ </li>
+ `;
+ }
+
+ /**
+ * Returns an HTML template for the slot element inside <or-tree-node>.
+ * It allows customization such as a prefix icon, adjusting the label, etc.
+ * @param node - Node to be rendered
+ */
+ protected _getSingleNodeSlotTemplate(node: TreeNode): TemplateResult {
+ return html`
+ <or-icon slot="prefix" icon="flag"></or-icon>
+ <span>${node.label}</span>
+ <span slot="suffix"></span>
+ `;
+ }
+
+ /**
+ * Returns a HTML template for rendering a group node (aka a node with children)
+ * @param node - Node to be rendered
+ * @param _parent - Optional parent (group node) if the node is placed inside a group
+ */
+ protected _getGroupNodeTemplate(node: TreeNode, _parent?: TreeNode): TemplateResult {
+ const leaf = this.selection === TreeMenuSelection.LEAF;
+ const randomId = this._setTreeNodeId(node);
+ return html`
+ <li>
+ <or-tree-group ?leaf=${leaf} ?expanded=${node.expanded}>
+ <or-tree-node slot="parent" id=${randomId} ?readonly=${leaf}
+ @click=${this._onTreeGroupClick}
+ @dragover=${(ev: DragEvent) => this._onDragOverGroup(ev, node)}
+ @dragleave=${(ev: DragEvent) => this._onDragLeaveGroup(ev, node)}
+ @drop=${(ev: DragEvent) => this._onDragDropGroup(ev, node)}>
+ ${this._getGroupNodeSlotTemplate(node)}
+ </or-tree-node>
+ ${map(node.children, n => this._getNodeTemplate(n, node))}
+ </or-tree-group>
+ </li>
+ `;
+ }
+
+ /**
+ * Returns an HTML template for the parent slot element inside <or-tree-group>.
+ * It allows customization such as a prefix icon, adjusting the label, etc.
+ * @param node - Node to be rendered
+ */
+ protected _getGroupNodeSlotTemplate(node: TreeNode): TemplateResult {
+ return html`
+ <or-icon slot="prefix" icon="folder"></or-icon>
+ <span>${node.label}</span>
+ <span slot="suffix"></span>
+ `;
+ }
+
+ /**
+ * Returns a HTML template for the header
+ */
+ protected _getHeaderTemplate(): TemplateResult {
+ return html`
+ <div id="tree-header">
+ <h3 id="tree-header-title">
+ <or-translate value=${this.menuTitle}></or-translate>
+ </h3>
+ <div id="tree-header-actions">
+ ${this._getSortActionTemplate(this.sortBy, this.sortOptions)}
+ </div>
+ </div>
+ `;
+ }
+
+ /**
+ * Returns a HTML template for the sorting options menu.
+ * @param value - The selected sorting option
+ * @param options - The available sorting options
+ */
+ protected _getSortActionTemplate(value?: string, options?: TreeMenuSorting[]): TemplateResult {
+ return getContentWithMenuTemplate(
+ html`<or-mwc-input type=${InputType.BUTTON} icon="sort-variant"></or-mwc-input>`,
+ (options || []).map(sort => ({ value: sort, text: sort } as ListItem)),
+ value,
+ value => this._onSortClick(String(value))
+ );
+ }
+
+ /**
+ * Returns a HTML template for displaying errors
+ */
+ protected _getErrorTemplate(): TemplateResult {
+ return html``;
+ }
+
+ //endregion
+
+ /* ------------------------------------------------------------- */
+ //region Event callback functions
+ /* ------------------------------------------------------------- */
+
+ /**
+ * HTML callback event for selecting a sort option in the dropdown menu,.
+ * @param value - The new selected sort option
+ */
+ protected _onSortClick(value: string) {
+ this.sortBy = value as TreeMenuSorting;
+ }
+
+ /**
+ * HTML callback event for clicking on a group node. (aka a node with children)
+ * Based on the configured TreeMenuSelection, it single- or multi selects the nodes.
+ */
+ protected _onTreeGroupClick(ev: PointerEvent) {
+ const elem = ev.currentTarget as OrTreeNode;
+ const group = elem.parentElement as OrTreeGroup;
+ const select = (treeGroup: OrTreeGroup, nodeElem: OrTreeNode) => {
+ treeGroup.select();
+ this._lastSelectedNode = nodeElem;
+ this._notifyNodesSelect()
+ }
+
+ switch (this.selection) {
+ case TreeMenuSelection.LEAF: {
+ return; // Group node cannot be selected when in leaf
+ }
+ case TreeMenuSelection.MULTI: {
+
+ // Shift selects all nodes between the previous selected, and this one.
+ if(ev.shiftKey && this._lastSelectedNode) {
+ const nodes = Array.from(this._uiNodes || []);
+ const parentNode = group.getGroupNode();
+ if(parentNode) {
+ const indexOfClickedNode = nodes.indexOf(parentNode);
+ const indexOfPreviousNode = nodes.indexOf(this._lastSelectedNode);
+ this._selectNodesBetween(nodes, indexOfClickedNode, indexOfPreviousNode);
+ return;
+ }
+
+ // Ctrl multi selects without deselecting the previous one.
+ } else if(ev.ctrlKey) {
+ select(group, elem);
+ return;
+ }
+ // Otherwise, select node like normal
+ this.deselectAllNodes();
+ select(group, elem);
+ return;
+ }
+
+ case TreeMenuSelection.SINGLE: {
+ this.deselectAllNodes();
+ select(group, elem);
+ return;
+ }
+ }
+ }
+
+ /** HTML callback event for when a child node of the tree gets clicked on. */
+ protected _onTreeNodeClick(ev: PointerEvent) {
+ const node = ev.currentTarget as OrTreeNode;
+ if (node) {
+ switch (this.selection) {
+ case TreeMenuSelection.MULTI: {
+
+ // Shift selects all nodes between the previous selected, and this one.
+ if(ev.shiftKey && this._lastSelectedNode) {
+ const nodes = Array.from(this._uiNodes || []);
+ const prevIndex = nodes.indexOf(this._lastSelectedNode);
+ const clickedIndex = nodes.indexOf(node);
+ if (prevIndex > -1 && clickedIndex > -1) {
+ this._selectNodesBetween(nodes, prevIndex, clickedIndex);
+ return;
+ }
+
+ // Ctrl multi selects without deselecting the previous one.
+ } else if(ev.ctrlKey) {
+ this._selectNode(node);
+ return;
+ }
+ // Otherwise select the node like normal
+ this.deselectAllNodes();
+ this._selectNode(node);
+ return;
+ }
+
+ default: {
+ this.deselectAllNodes();
+ this._selectNode(node);
+ return;
+ }
+ }
+ }
+ }
+
+ //endregion
+
+ /* ------------------------------------------------------------- */
+ //region Drag-and-drop callback functions
+ /* ------------------------------------------------------------- */
+
+ /** HTML callback event for 'dragstart' (the moment when a drag gesture is started) */
+ protected _onDragStart(ev: DragEvent, node: TreeNode) {
+ if(ev.target) {
+ ev.dataTransfer?.setData("treeNode", JSON.stringify(node));
+ } else {
+ ev.preventDefault();
+ }
+ }
+
+ /** HTML callback event for 'dragover' on the list element */
+ protected _onDragOverList(ev: DragEvent) {
+ if(this.draggable) ev.preventDefault();
+ }
+
+ /** HTML callback event for 'dragover', so while a node is dragged over a single node */
+ protected _onDragOverSingleNode(ev: DragEvent, node: TreeNode, parent?: TreeNode) {
+ if(this.draggable) {
+ ev.preventDefault(); // allows dropping the node on this node
+ if(parent) {
+ const elem = this._getUiNodeFromTree(parent);
+ elem?.setAttribute("drophover", "true");
+ }
+ }
+ }
+
+ /** HTML callback event for 'dragover', so while a node is dragged over a group node */
+ protected _onDragOverGroup(ev: DragEvent, groupNode: TreeNode) {
+ if(this.draggable) {
+ ev.preventDefault(); // allows dropping the node on the group
+ (ev.currentTarget as HTMLElement).setAttribute("drophover", "true");
+ }
+ }
+
+ /** HTML callback event for 'dragover', so while a node is dragged over a single node */
+ protected _onDragLeaveSingleNode(ev: DragEvent, node: TreeNode, parent?: TreeNode) {
+ if(parent && this.draggable) {
+ ev.preventDefault(); // allows dropping the node on this node
+ const elem = this._getUiNodeFromTree(parent);
+ elem?.removeAttribute("drophover");
+ }
+ }
+
+ /** HTML callback event for 'dragleave', so after a node has been dragged over a group node */
+ protected _onDragLeaveGroup(ev: DragEvent, groupNode: TreeNode) {
+ if(this.draggable) (ev.currentTarget as HTMLElement).removeAttribute("drophover");
+ }
+
+ /** HTML callback event for when a node is dropped on the list level. */
+ protected _onDragDropList(ev: DragEvent) {
+ this._onDragDropGroup(ev);
+ }
+
+ /** HTML callback event for when a node is dropped onto a single node, after dragging it over. */
+ protected _onDragDropSingleNode(ev: DragEvent, groupNode?: TreeNode, parent?: TreeNode) {
+ this._onDragDropGroup(ev, parent);
+ }
+
+ /** HTML callback event for when a node is dropped onto a group node, after dragging it over. */
+ protected _onDragDropGroup(ev: DragEvent, groupNode?: TreeNode) {
+ if(this.draggable) {
+ ev.preventDefault(); // allows dropping the node on this node
+ ev.stopPropagation();
+
+ // Remove "hover background" from the group node in the UI
+ if(groupNode) this._getUiNodeFromTree(groupNode)?.removeAttribute("drophover");
+
+ let nodesToMove: TreeNode[] = [];
+
+ // Get the dragged element from the event payload data
+ const data = ev.dataTransfer?.getData("treeNode");
+ if(data) {
+ const node = JSON.parse(data) as TreeNode;
+ if(node) nodesToMove.push(node);
+ }
+ // If selection is multi, also add all selected ones
+ if(this.selection === TreeMenuSelection.MULTI) {
+ let selected = this._findSelectedTreeNodes();
+
+ // Filter out groups
+ selected = selected.filter(n => !n.children);
+
+ if(selected.length > 0) {
+ this.deselectAllNodes();
+ nodesToMove.push(...selected.filter(node => !nodesToMove.find(n => JSON.stringify(n) === JSON.stringify(node))));
+ }
+ }
+
+ // Filter out "nodes to move" that are already in that group
+ if(groupNode?.children) {
+ nodesToMove = nodesToMove.filter(node =>
+ !groupNode.children?.find(child => child.id === node.id)
+ )
+ }
+
+ // Finally, move the nodes
+ if(nodesToMove.length > 0) {
+ this._dispatchCancellableDragEvent(nodesToMove, groupNode, this.nodes).then(() => {
+ this.nodes = moveNodesToGroupNode(nodesToMove, groupNode, this.nodes);
+ }).catch(ignored => {});
+ }
+ }
+ }
+
+ /**
+ * Dispatches a cancellable tree drag event.
+ */
+ protected _dispatchCancellableDragEvent(nodes: TreeNode[], groupNode?: TreeNode, allNodes: TreeNode[] = []): Promise<void> {
+ return new Promise((resolve, reject) => {
+ const success = this.dispatchEvent(new OrTreeDragEvent(nodes, groupNode, allNodes));
+ success ? resolve() : reject();
+ });
+ }
+
+ //endregion
+
+ /* ------------------------------------------------------------- */
+
+ /**
+ * Selects the node using the HTML attribute 'selected' of OrTreeNode
+ * @param node - Node to be selected
+ * @param notify - Boolean whether to notify the HTML parents of an or-tree-select.
+ */
+ protected _selectNode(node?: OrTreeNode, notify = true) {
+ if(node) {
+ if(notify) {
+ const selected = [...this._findSelectedTreeNodes()];
+ const treeNode = this._getTreeNodeFromTree(node);
+ if(treeNode) selected.push(treeNode);
+ const success = this._dispatchSelectEvent(selected); // Dispatch a "select" event, and return when cancelled by a consumer
+ if(!success) return;
+ }
+ node.selected = true;
+ this._lastSelectedNode = node;
+ }
+ }
+
+ /**
+ * Multi-selects the nodes between two indexes in a list of OrTreeNode.
+ * @param nodes - List of nodes in the tree menu
+ * @param index1 - Start index of the nodes to select
+ * @param index2 - End index of the nodes to select
+ * @param notify - Boolean whether to notify the HTML parents of an or-tree-select.
+ */
+ protected _selectNodesBetween(nodes: OrTreeNode[], index1: number, index2: number, notify = true) {
+ const selectedNodes: OrTreeNode[] = [];
+ if(index1 < index2) {
+ for(let x = index1; x <= index2; x++) {
+ selectedNodes.push(nodes[x]);
+ }
+ } else if(index1 > index2) {
+ for(let x = index2; x <= index1; x++) {
+ selectedNodes.push(nodes[x]);
+ }
+ }
+ // Dispatch a "select" event with the new nodes. If cancelled, we will not select the nodes.
+ if(notify) {
+ const nodes = selectedNodes.map(n => this._getTreeNodeFromTree(n)).filter(n => n) as TreeNode[];
+ const success = this._notifyNodesSelect(nodes);
+ if(!success) return;
+ }
+ // Select the nodes
+ selectedNodes.forEach((node) => this._selectNode(node));
+ }
+
+ /**
+ * Function that notifies parent HTMLElements that a tree node got selected.
+ * It dispatches the OrTreeSelectEvent, which includes a list of the selected nodes.
+ * @returns a 'success' boolean whether the event was cancelled or not
+ */
+ protected async _notifyNodesSelect(selectedNodes?: TreeNode[]) {
+ await this.getUpdateComplete(); // await render to include the latest changes.
+ if(!selectedNodes) {
+ selectedNodes = this._findSelectedTreeNodes();
+ }
+ return this._dispatchSelectEvent(selectedNodes);
+ }
+
+ /**
+ * Utility function to detect the selected tree nodes.
+ * @param uiNodes - List of <or-tree-node> UI elements
+ * @param cache - Optionally, supply the cache for retrieving a {@link TreeNode} object from a <or-tree-node> element.
+ */
+ protected _findSelectedTreeNodes(uiNodes = Array.from(this._uiNodes || []), cache = this._treeNodeCache): TreeNode[] {
+
+ // Get the list of selected TreeNodeComponent elements in the UI.
+ const selectedUiNodes = uiNodes.filter(n => n.selected);
+
+ // Get the list of cached generated IDs (for tracking which TreeNode belongs to which TreeNodeComponent)
+ const treeNodeEntries = Array.from(cache.entries());
+
+ // Find the generated IDs in the list of TreeNodeComponents, and compare the element ID
+ return selectedUiNodes.map(component => treeNodeEntries
+ .find(v => v[1] === component.id))
+ .map(x => x?.[0])
+ .filter(n => n !== undefined) as TreeNode[];
+ }
+
+ /**
+ * Utility function that gets a {@link TreeNode} based on an {@link OrTreeNode} HTML element in the menu.
+ * @param uiNode - The tree node HTML element
+ * @param cache - Optional cache to get the TreeNode from
+ */
+ protected _getTreeNodeFromTree(uiNode: OrTreeNode, cache = this._treeNodeCache): TreeNode | undefined {
+ const treeNodeEntries = Array.from(cache.entries()); // Get the list of cached generated IDs (for tracking which TreeNode belongs to which TreeNodeComponent)
+ return treeNodeEntries.find(entry => entry[1] === uiNode.id)?.[0];
+ }
+
+ /**
+ * Utility function that gets an {@link OrTreeNode} HTML element based on the {@link TreeNode} input object.
+ * @param treeNode - The tree node object
+ * @param cache - Optional cache to get the HTML element from
+ */
+ protected _getUiNodeFromTree(treeNode: TreeNode, cache = this._treeNodeCache): OrTreeNode | undefined {
+ const treeNodeEntries = Array.from(cache.entries()); // Get the list of cached generated IDs (for tracking which TreeNode belongs to which TreeNodeComponent)
+ const treeNodeJSON = JSON.stringify(treeNode);
+
+ const elementId = treeNodeEntries.find(entry => JSON.stringify(entry[0]) === treeNodeJSON)?.[1];
+ return elementId ? this.shadowRoot!.getElementById(elementId) as OrTreeNode : undefined;
+ }
+
+ /**
+ * Utility function for sending a "select" event, so consumers of this component are aware a new node has been selected.
+ * @param selectedNodes - List of selected nodes to include in the event payload.
+ * @returns a 'success' boolean whether the event was cancelled or not.
+ */
+ protected _dispatchSelectEvent(selectedNodes?: TreeNode[]): boolean {
+ return this.dispatchEvent(new OrTreeSelectEvent(selectedNodes || []));
+ }
+
+ /**
+ * Public function that deselects all tree nodes.
+ */
+ public deselectAllNodes() {
+ (this._uiGroups || []).forEach(uiGroup => uiGroup.deselect());
+ (this._uiNodes || []).forEach(uiNode => uiNode.selected = false);
+ }
+
+ /**
+ * Utility function that sorts the list of {@link nodes} based on the given {@link sortBy} method.
+ * @param nodes - List of nodes to be sorted
+ * @param sortBy - Sorting option
+ * @param groupFirst - Whether to prioritize group nodes, and place them on the top of the list.
+ */
+ protected _sortNodes(nodes: TreeNode[], sortBy?: TreeMenuSorting, groupFirst = false): TreeNode[] {
+ console.debug(`Sorting nodes in the tree menu using '${sortBy}'`);
+
+ const grouped = nodes.filter(node => node.children !== undefined);
+
+ // TODO: Apply recursive sorting if nested deeper inside the tree
+ grouped.forEach(g => g.children?.sort(this._getSortFunction(sortBy)));
+
+ // Optionally, prioritize group nodes, and place all groups on top of the menu
+ if(groupFirst) {
+ const ungrouped = nodes.filter(node => node.children === undefined);
+ grouped.sort(this._getSortFunction(sortBy));
+ ungrouped.sort(this._getSortFunction(sortBy));
+ return [...grouped, ...ungrouped];
+ }
+
+ return nodes.sort(this._getSortFunction(sortBy));
+ }
+
+ /**
+ * Function that caches a random ID into a key-value storage, linking the TreeNode with a generated ID.
+ * This generated ID can be used somewhere else, for example in an HTMLElement ID as a unique identifier.
+ * @param node - The TreeNode object to cache
+ * @param randomId - Optionally you can supply an ID to use for caching
+ */
+ protected _setTreeNodeId(node: TreeNode, randomId = Math.random().toString(36).substring(2, 11)): string {
+ if(this._treeNodeCache.get(node)) {
+ return this._treeNodeCache.get(node)!;
+ }
+ this._treeNodeCache.set(node, randomId);
+ return randomId;
+ }
+
+ /**
+ * Function for retrieving the sorting for TreeNodes based on a sortBy parameter.
+ * The sortBy parameter represents a key in the TreeNode object like 'label'.
+ * @param sortBy - Sorting option to use, such as "a_to_z"
+ */
+ protected _getSortFunction(sortBy?: TreeMenuSorting): (a: TreeNode, b: TreeNode) => number {
+ switch (sortBy) {
+ case TreeMenuSorting.Z_TO_A:
+ return (a, b) => b.label.localeCompare(a.label);
+ default:
+ return Util.sortByString(node => node.label);
+ }
+ }
+}
diff --git a/ui/component/or-tree-menu/src/model.ts b/ui/component/or-tree-menu/src/model.ts
new file mode 100644
index 000000000..62b7064f6
--- /dev/null
+++ b/ui/component/or-tree-menu/src/model.ts
@@ -0,0 +1,101 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/**
+ * The TreeNode model for constructing a node within the tree.
+ */
+export interface TreeNode {
+ id: string;
+ children?: TreeNode[];
+ label: string;
+ hidden?: boolean;
+ readonly?: boolean;
+ selected?: boolean; // Only acts as initial state
+ expandable?: boolean;
+ expanded?: boolean;
+}
+
+/**
+ * List of possible options for tree menu selection.
+ * The order within the enum is based on restrictiveness.
+ *
+ * - **LEAF** - only allows a single node to be selected, and forbids the selection of any parent node.
+ * - **SINGLE** - only allows a single node to be selected, but does allow the selection of the parent node.
+ * - **MULTI** - allows selecting multiple nodes using keyboard controls. (control and shift)
+ */
+export enum TreeMenuSelection {
+ LEAF = "leaf", SINGLE = "single", MULTI = "multi"
+}
+
+/**
+ * List of sorting options in the header of the tree menu.
+ * By default, we include alphabetically sorting, but can be expanded by class inheritors.
+ */
+export enum TreeMenuSorting {
+ A_TO_Z = "a_to_z", Z_TO_A = "z_to_a"
+}
+
+/**
+ * Model for the SELECT event that {@link OrTreeMenu} can dispatch.
+ * Once a node is selected, a list of all the selected nodes will be shared with the consumer elements.
+ */
+export class OrTreeSelectEvent extends CustomEvent<TreeNode[]> {
+
+ public static readonly NAME = "or-tree-select";
+
+ constructor(nodes: TreeNode[]) {
+ super(OrTreeSelectEvent.NAME, {
+ bubbles: true,
+ composed: true,
+ detail: nodes
+ });
+ }
+}
+
+/**
+ * Payload object of the {@link OrTreeDragEvent}.
+ */
+export interface OrTreeGroupEventDetail {
+ nodes: TreeNode[];
+ groupNode?: TreeNode;
+ newNodes: TreeNode[];
+}
+
+/**
+ * Model for the DRAG event that {@link OrTreeMenu} can dispatch.
+ * Once a node is dragged into (or outside) a group, we send details to consumer elements.
+ */
+export class OrTreeDragEvent extends CustomEvent<OrTreeGroupEventDetail> {
+
+ public static readonly NAME = "or-tree-drag";
+
+ constructor(nodes: TreeNode[], groupNode?: TreeNode, newNodes: TreeNode[] = []) {
+ super(OrTreeDragEvent.NAME, {
+ bubbles: true,
+ composed: true,
+ cancelable: true,
+ detail: {
+ nodes: nodes,
+ groupNode: groupNode,
+ newNodes: newNodes
+ } as OrTreeGroupEventDetail
+ });
+ }
+}
diff --git a/ui/component/or-tree-menu/src/or-tree-group.ts b/ui/component/or-tree-menu/src/or-tree-group.ts
new file mode 100644
index 000000000..fa9154f52
--- /dev/null
+++ b/ui/component/or-tree-menu/src/or-tree-group.ts
@@ -0,0 +1,226 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+import {css, html, LitElement, PropertyValues, TemplateResult} from "lit";
+import {customElement, property, query, queryAssignedElements} from "lit/decorators.js";
+import { when } from "lit/directives/when.js";
+import {OrTreeNode} from "./or-tree-node";
+
+const getStyles = () => css`
+ * {
+ box-sizing: border-box;
+ }
+
+ :host {
+ position: relative;
+ }
+
+ ol {
+ list-style: none;
+ padding: 0;
+ margin: 0;
+ }
+
+ ::slotted(*[slot="parent"]) {
+ cursor: pointer;
+ }
+
+ #chevron {
+ position: absolute;
+ height: 44px;
+ display: flex;
+ align-items: center;
+ aspect-ratio: 1/1.25;
+ padding-left: 4px;
+ font-size: 18px;
+ color: #cccccc;
+ z-index: 10;
+ }
+
+ #chevron:hover {
+ color: unset;
+ }
+
+ :host(:not([readonly])) > #chevron {
+ cursor: pointer;
+ }
+`;
+
+/**
+ * @slot - Default slot for child nodes within the group
+ * @slot parent - Slot for inserting a parent node
+ * @csspart chevron - The chevron icon element for expanding/collapsing the group.
+ */
+@customElement("or-tree-group")
+export class OrTreeGroup extends LitElement {
+
+ /**
+ * Determines the visibility of child nodes.
+ * Setting this to `false` hides them, and acts as a 'collapsed' state.
+ */
+ @property({type: Boolean, reflect: true})
+ public expanded = false;
+
+ /**
+ * Only allows child nodes to be selected, making the expander (parent node) readonly.
+ * If this is set to false, only the chevron icon can be used to collapse/expand the list.
+ */
+ @property({type: Boolean})
+ public readonly leaf = false;
+
+ /**
+ * Makes the group readonly
+ */
+ @property({type: Boolean})
+ public readonly readonly = false;
+
+ @queryAssignedElements({slot: undefined})
+ protected _childNodes?: Array<HTMLLIElement>;
+
+ @queryAssignedElements({slot: "parent"})
+ protected _parentNodes?: Array<OrTreeNode>;
+
+ /** A click event listener on the component, used for selecting, expanding, and collapsing the group */
+ protected _slotClickListener = (e: MouseEvent) => this.leaf ? this._onExpandToggle(e) : null;
+
+ /** A click event listener on the chevron, used for expanding/collapsing the group */
+ protected _chevronClickListener = (e: MouseEvent) => this._onExpandToggle(e);
+
+ static get styles() {
+ return [getStyles()];
+ }
+
+ /** Selects the group (parent) node. */
+ public select() {
+ const groupNode = this.getGroupNode();
+ if(!this.leaf && groupNode) {
+ groupNode.selected = true;
+ }
+ }
+
+ /** Selects the group node itself, and all children nodes within that group. */
+ public selectAll() {
+ this.select();
+ this.getChildNodes().forEach(node => node.selected = true);
+ }
+
+ /** Deselects the group (parent) node. */
+ public deselect() {
+ const groupNode = this.getGroupNode();
+ if(groupNode) {
+ groupNode.selected = false;
+ }
+ }
+
+ /** Deselects the group node itself, and all children nodes within that group. */
+ public deselectAll() {
+ this.deselect();
+ this.getChildNodes().forEach(node => node.selected = false);
+ }
+
+ /** Returns the group (parent) node ({@link OrTreeNode}) using a query selector. */
+ public getGroupNode(): OrTreeNode | undefined {
+ return this._parentNodes?.[0];
+ }
+
+ /** Returns a list of all children nodes ({@link OrTreeNode}) within the group, using a query selector. */
+ public getChildNodes(): OrTreeNode[] {
+ return Array.from(this._childNodes || [])
+ .map(n => n.querySelector('or-tree-node') as OrTreeNode | null)
+ .filter(n => n != null) as OrTreeNode[];
+ }
+
+ firstUpdated(changedProps: PropertyValues) {
+ this._parentNodes?.forEach(elem => {
+ elem.addEventListener("click", this._slotClickListener);
+ });
+ return super.firstUpdated(changedProps);
+ }
+
+ disconnectedCallback() {
+ this._parentNodes?.forEach(elem => {
+ elem.removeEventListener("click", this._slotClickListener);
+ });
+ super.disconnectedCallback();
+ }
+
+ render(): TemplateResult {
+ return html`
+ ${when(!this.readonly, () => this._getIconTemplate(this.expanded))}
+ <slot name="parent"></slot>
+ <ol ?hidden=${!this.expanded}>
+ <slot @slotchange=${this._onSlotChange}></slot>
+ </ol>
+ `;
+ }
+
+ /**
+ * Returns an HTML template that represents the icon for this group.
+ * @param expanded State of the group
+ */
+ protected _getIconTemplate(expanded = false): TemplateResult {
+ return html`
+ <or-icon id="chevron" part="chevron" icon="${expanded ? "chevron-down" : "chevron-right"}"
+ @click="${this._chevronClickListener}"
+ ></or-icon>
+ `;
+ }
+
+ /**
+ * Function that expands/collapses the group, changing the visibility of the child nodes.
+ */
+ protected _onExpandToggle(_ev: MouseEvent) {
+ this.expanded = !this.expanded;
+ }
+
+ /**
+ * Event listener for 'slotchange' of the default slot.
+ * Normally triggers when <or-tree-node> elements are added or removed.
+ */
+ protected _onSlotChange(_ev: Event) {
+ this._applyIndentToChildren();
+ }
+
+ /**
+ * Function that applies CSS to TreeNode based on the group indentation.
+ * It loops through all parent elements, and detects the amount of or-tree-group elements it is in.
+ * The more nested in the tree, the more left handed padding is applied.
+ * @param children Node elements to apply padding to.
+ */
+ protected _applyIndentToChildren(children = this.getChildNodes()) {
+ const countGroups = (elem: HTMLElement | null) => {
+ let count = 0;
+ while(elem) {
+ if(elem.tagName.toLowerCase() === "or-tree-group") {
+ count++;
+ }
+ elem = elem.parentElement;
+ }
+ return count;
+ };
+ children.forEach(child => {
+ let groupAmount = countGroups(child);
+ if(child.slot === "parent") {
+ groupAmount--; // Parent slot is the group itself, so remove 1
+ }
+ // Apply indent as padding to the node
+ child.style.setProperty("--or-tree-node-indent", `${24 + (groupAmount * 12)}px`);
+ });
+ }
+}
diff --git a/ui/component/or-tree-menu/src/or-tree-node.ts b/ui/component/or-tree-menu/src/or-tree-node.ts
new file mode 100644
index 000000000..d4fb5728d
--- /dev/null
+++ b/ui/component/or-tree-menu/src/or-tree-node.ts
@@ -0,0 +1,103 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+import {css, html, LitElement, TemplateResult} from "lit";
+import {customElement, property} from "lit/decorators.js";
+
+const styles = css`
+ * {
+ box-sizing: border-box;
+ }
+ :host {
+ width: 100%;
+ height: var(--or-tree-node-height, 44px);
+ padding: 6px 12px 6px var(--or-tree-node-indent, 24px);
+ background: var(--or-tree-node-background, transparent);
+ border-left: 4px solid transparent;
+ display: flex;
+ align-items: center;
+ gap: var(--or-tree-node-gap, 8px);
+ overflow: hidden;
+ user-select: none;
+ --or-icon-width: 20px;
+ }
+
+ :host(:not([readonly])) {
+ cursor: pointer;
+ }
+
+ :host([readonly]) {
+ cursor: not-allowed;
+ }
+
+ :host(:not([readonly]):hover) {
+ background: var(--or-tree-node-backgrond--hovered, #f8f9fa);
+ }
+
+ :host([selected]) {
+ background: var(--or-tree-node-background--selected, #f1f3f5);
+ border-left: 4px solid var(--or-tree-node-color--selected, var(--or-app-color4, #4d9d2a));
+ }
+
+ ::slotted(*:not([slot])) {
+ flex: 1;
+ }
+`;
+
+/**
+ * @slot prefix - Appends elements to the left hand side of the node, commonly used for icons.
+ * @slot - Default slot for the main content, commonly used for text.
+ * @slot suffix - Appends elements to the right hand side of the node.
+ *
+ * @cssprop --or-tree-node-height - Controls the height of the node
+ * @cssprop --or-tree-node-indent - Controls the left padding of the node
+ *
+ * @cssprop --or-tree-node-background - Sets the default background
+ * @cssprop --or-tree-node-background--hovered - Sets the background while hovering
+ * @cssprop --or-tree-node-background--selected - Sets the background when selected
+ *
+ * @cssprop --or-tree-node-color--selected - Sets the primary color of the node when selected
+ */
+@customElement("or-tree-node")
+export class OrTreeNode extends LitElement {
+
+ /**
+ * HTML attribute that only applies CSS, showing this node cannot be interacted with.
+ */
+ @property({type: Boolean, reflect: true})
+ public readonly = false;
+
+ /**
+ * HTML attribute that only applies CSS, marking the node as 'selected'.
+ */
+ @property({type: Boolean, reflect: true})
+ public selected = false;
+
+ static get styles() {
+ return [styles];
+ }
+
+ protected render(): TemplateResult {
+ return html`
+ <slot name="prefix"></slot>
+ <slot></slot>
+ <slot name="suffix"></slot>
+ `;
+ }
+}
diff --git a/ui/component/or-tree-menu/src/util.ts b/ui/component/or-tree-menu/src/util.ts
new file mode 100644
index 000000000..cbf83037d
--- /dev/null
+++ b/ui/component/or-tree-menu/src/util.ts
@@ -0,0 +1,68 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+import {TreeNode} from "./model";
+
+/**
+ * Utility function that moves an array of {@link TreeNode} into another {@link TreeNode}, by adding them to their children.
+ * The function takes care of removing the nodes from the former group, and makes sure no duplicates end up in the list.
+ *
+ * @param nodesToMove - The array of nodes that are moved into a group.
+ * @param groupNode - The group node to insert nodesToMove in.
+ * @param treeNodes - Full list of nodes in the tree menu.
+ */
+export function moveNodesToGroupNode(nodesToMove: TreeNode[], groupNode?: TreeNode, treeNodes: TreeNode[] = []): TreeNode[] {
+ console.debug(`Moving nodes '${nodesToMove.map(node => node.label).join(', ')}' into group '${groupNode?.label}'. Tree nodes are`, groupNode);
+
+ function filterAndAdd(nodes: TreeNode[]): TreeNode[] {
+ return nodes.map(node => {
+
+ if (nodesToMove.some(nodeToMove => node.id === nodeToMove.id)) {
+ console.debug("Removed the node from original position.")
+ return null; // Removes the node from its original position
+ }
+
+ const newNode: TreeNode = { ...node };
+
+ // Recursively loop through children
+ if (newNode.children) {
+ newNode.children = filterAndAdd(newNode.children).filter(child => child !== null);
+ }
+
+ // If the currently looped node is the target group node, add the nodes to its children
+ if (groupNode && node.id === groupNode?.id) {
+ nodesToMove.forEach(nodeToMove => {
+ newNode.children = newNode.children ? [...newNode.children, nodeToMove] : [nodeToMove];
+ });
+ }
+ return newNode;
+
+ }).filter(node => node !== null) as TreeNode[];
+ }
+
+ // Start the recursive function
+ const newNodes = filterAndAdd(treeNodes);
+
+ // If no groupNode is provided, add the nodesToMove to the top level
+ if (!groupNode) {
+ newNodes.push(...nodesToMove);
+ }
+ return newNodes;
+}
+
diff --git a/ui/component/or-tree-menu/tsconfig.json b/ui/component/or-tree-menu/tsconfig.json
new file mode 100644
index 000000000..b9811bcfc
--- /dev/null
+++ b/ui/component/or-tree-menu/tsconfig.json
@@ -0,0 +1,17 @@
+{
+ "extends": "../../tsconfig",
+ "compilerOptions": {
+ "outDir": "./lib",
+ "rootDir": "src"
+ },
+ "include": [
+ "./src"
+ ],
+ "references": [
+ { "path": "../core" },
+ { "path": "../rest" },
+ { "path": "../model" },
+ { "path": "../or-mwc-components" },
+ { "path": "../or-translate" }
+]
+}
diff --git a/ui/component/or-tree-menu/webpack.config.js b/ui/component/or-tree-menu/webpack.config.js
new file mode 100644
index 000000000..8d24333fc
--- /dev/null
+++ b/ui/component/or-tree-menu/webpack.config.js
@@ -0,0 +1,13 @@
+const util = require("@openremote/util");
+
+bundles = {
+ "index": {
+ excludeOr: true
+ },
+ "index.bundle": {
+ excludeOr: true,
+ },
+ "index.orbundle": undefined
+};
+
+module.exports = util.generateExports(__dirname);
diff --git a/yarn.lock b/yarn.lock
index 81952301f..511b515e6 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -1549,7 +1549,7 @@ __metadata:
languageName: node
linkType: hard
-"@lit/reactive-element@npm:^1.0.0 || ^2.0.0":
+"@lit/reactive-element@npm:^1.0.0 || ^2.0.0, @lit/reactive-element@npm:^2.0.4":
version: 2.0.4
resolution: "@lit/reactive-element@npm:2.0.4"
dependencies:
@@ -2754,6 +2754,7 @@ __metadata:
"@openremote/or-icon": "workspace:*"
"@openremote/or-mwc-components": "workspace:*"
"@openremote/or-translate": "workspace:*"
+ "@openremote/or-tree-menu": "workspace:*"
"@openremote/rest": "workspace:*"
"@openremote/util": "workspace:*"
"@types/shortid": "npm:^0.0.29"
@@ -2840,6 +2841,19 @@ __metadata:
languageName: unknown
linkType: soft
+"@openremote/or-tree-menu@workspace:*, @openremote/or-tree-menu@workspace:ui/component/or-tree-menu":
+ version: 0.0.0-use.local
+ resolution: "@openremote/or-tree-menu@workspace:ui/component/or-tree-menu"
+ dependencies:
+ "@mdi/js": "npm:^5.9.55"
+ "@openremote/core": "workspace:*"
+ "@openremote/or-mwc-components": "workspace:*"
+ "@openremote/or-translate": "workspace:*"
+ "@openremote/util": "workspace:*"
+ lit: "npm:^3.2.1"
+ languageName: unknown
+ linkType: soft
+
"@openremote/rest@workspace:*, @openremote/rest@workspace:ui/component/rest":
version: 0.0.0-use.local
resolution: "@openremote/rest@workspace:ui/component/rest"
@@ -6958,6 +6972,17 @@ __metadata:
languageName: node
linkType: hard
+"lit-element@npm:^4.1.0":
+ version: 4.1.1
+ resolution: "lit-element@npm:4.1.1"
+ dependencies:
+ "@lit-labs/ssr-dom-shim": "npm:^1.2.0"
+ "@lit/reactive-element": "npm:^2.0.4"
+ lit-html: "npm:^3.2.0"
+ checksum: 10c0/b3c6c77d60a8239134d7c7e7c002be48414074f5b42f9ad026216749101a4f948266a4db9110a536fb23914044d584dbe4185c87064a4fa98baa4045ba2bbb46
+ languageName: node
+ linkType: hard
+
"lit-html@npm:^2.8.0":
version: 2.8.0
resolution: "lit-html@npm:2.8.0"
@@ -6967,6 +6992,15 @@ __metadata:
languageName: node
linkType: hard
+"lit-html@npm:^3.2.0":
+ version: 3.2.1
+ resolution: "lit-html@npm:3.2.1"
+ dependencies:
+ "@types/trusted-types": "npm:^2.0.2"
+ checksum: 10c0/31c02df2148bf9a73545570cbe57aae01c4de1d9b44060b6ff13641837d38e39e6b1abcf92e13882cc84f5fee37605ed79602b91ad479728549014462808118e
+ languageName: node
+ linkType: hard
+
"lit@npm:^2.0.2":
version: 2.8.0
resolution: "lit@npm:2.8.0"
@@ -6978,6 +7012,17 @@ __metadata:
languageName: node
linkType: hard
+"lit@npm:^3.2.1":
+ version: 3.2.1
+ resolution: "lit@npm:3.2.1"
+ dependencies:
+ "@lit/reactive-element": "npm:^2.0.4"
+ lit-element: "npm:^4.1.0"
+ lit-html: "npm:^3.2.0"
+ checksum: 10c0/064a31459fe54ad052c0685d058dd5aef089ddc97a247888ef91a0356dfef60c8cc531e48077bbd2cb4e9f48cb86f0ff0951bb535f1d9f144d2351f253291f66
+ languageName: node
+ linkType: hard
+
"loader-runner@npm:^4.2.0":
version: 4.3.0
resolution: "loader-runner@npm:4.3.0"