Skip to content

armgit / core

Public Imported from GitHub
0

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

Merged flow rules

Rich Turner53f043159949
diff --git a/deployment/manager/shared/locales/en/or.json b/deployment/manager/shared/locales/en/or.json
index 1d3a4a51b..a40b8933c 100644
--- a/deployment/manager/shared/locales/en/or.json
+++ b/deployment/manager/shared/locales/en/or.json
@@ -71,6 +71,7 @@
"sortBy": "Sort by",
"assetType": "Asset type",
"creationDate": "Creation date",
+ "lang": "Language",
"status": "Status",
"name": "Name",
"deleteAssetsNoChildrenAllowed": "Only assets that have no descendants can be deleted, please remove descendents first.",
@@ -93,6 +94,39 @@
"year": "Year",
"period": "Period",
"ending": "Ending",
+ "EQUALS_COMPARATOR": "Equals",
+ "GREATER_THAN": "Greater than",
+ "LESS_THAN": "Less than",
+ "READ_ATTRIBUTE": "Read attribute",
+ "WRITE_ATTRIBUTE": "Write attribute",
+ "BOOLEAN_INPUT": "Boolean",
+ "NUMBER_INPUT": "Number",
+ "TEXT_INPUT": "Text",
+ "ADD_OPERATOR": "Add",
+ "SUBTRACT_OPERATOR": "Subtract",
+ "COMBINE_TEXT": "Combine text",
+ "MULTIPLY_OPERATOR": "Multiply",
+ "DIVIDE_OPERATOR": "Divide",
+ "AND_GATE": "And gate",
+ "OR_GATE": "Or gate",
+ "NOT_GATE": "Not gate",
+ "NUMBER_SWITCH": "Number switch",
+ "TEXT_SWITCH": "Text switch",
+ "ROUND_NODE": "Round",
+ "input": "Input",
+ "processors": "Processors",
+ "output": "Output",
+ "selectAsset": "Select asset",
+ "noRuleStateAttributes": "No rule state attributes",
+ "copy": "Copy",
+ "paste": "Paste",
+ "delete": "Delete",
+ "fitViewToSelectedNodes": "Fit view to selected nodes",
+ "resetView": "Reset view",
+ "fitView": "Fit view",
+ "areYouSure": "Are you sure?",
+ "flowEditor": "Flow editor",
+ "else": "else",
"english": "English",
"dutch": "Dutch",
"french": "French",
diff --git a/deployment/manager/shared/locales/nl/or.json b/deployment/manager/shared/locales/nl/or.json
index 91218547d..eb954761f 100644
--- a/deployment/manager/shared/locales/nl/or.json
+++ b/deployment/manager/shared/locales/nl/or.json
@@ -71,6 +71,7 @@
"sortBy": "Sorteren op",
"assetType": "Asset type",
"creationDate": "Aangemaakt op",
+ "lang": "Taal",
"status": "Status",
"name": "Naam",
"deleteAssetsNoChildrenAllowed": "Kan deze asset niet verwijderen. Verwijder de onderliggende assets eerst.",
@@ -89,10 +90,43 @@
"hour": "Uur",
"day": "Dag",
"week": "Week",
- "month": "Maand",
- "year": "Jaar",
- "period": "Periode",
- "ending": "Einde",
+ "month": "Month",
+ "year": "Year",
+ "period": "Period",
+ "ending": "Ending",
+ "EQUALS_COMPARATOR": "Gelijk aan",
+ "GREATER_THAN": "Groter dan",
+ "LESS_THAN": "Kleiner dan",
+ "READ_ATTRIBUTE": "Lees attribuut",
+ "WRITE_ATTRIBUTE": "Schrijf attribuut",
+ "BOOLEAN_INPUT": "Boolean",
+ "NUMBER_INPUT": "Nummer",
+ "TEXT_INPUT": "Tekst",
+ "ADD_OPERATOR": "Optellen",
+ "SUBTRACT_OPERATOR": "Aftrekken",
+ "COMBINE_TEXT": "Combineer tekst",
+ "MULTIPLY_OPERATOR": "Vermenigvuldigen",
+ "DIVIDE_OPERATOR": "Delen door",
+ "AND_GATE": "En-poort",
+ "OR_GATE": "Of-poort",
+ "NOT_GATE": "Niet-poort",
+ "NUMBER_SWITCH": "Nummer schakeling",
+ "TEXT_SWITCH": "Tekst schakeling",
+ "ROUND_NODE": "Afronden",
+ "input": "Input",
+ "processors": "Processors",
+ "output": "Output",
+ "selectAsset": "Selecteer asset",
+ "noRuleStateAttributes": "Geen rule state attributes",
+ "copy": "Kopiëren",
+ "paste": "Plakken",
+ "delete": "Verwijderen",
+ "fitViewToSelectedNodes": "Pas beeld aan op selectie",
+ "resetView": "Reset beeld",
+ "fitView": "Pas beeld aan op project",
+ "areYouSure": "Weet je het zeker?",
+ "flowEditor": "Flow editor",
+ "else": "anders",
"english": "Engels",
"dutch": "Nederlands",
"french": "Frans",
diff --git a/manager/src/main/java/org/openremote/manager/rules/FlowRulesBuilder.java b/manager/src/main/java/org/openremote/manager/rules/FlowRulesBuilder.java
new file mode 100644
index 000000000..6983601c3
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/rules/FlowRulesBuilder.java
@@ -0,0 +1,126 @@
+package org.openremote.manager.rules;
+
+import org.jeasy.rules.api.Rule;
+import org.jeasy.rules.core.RuleBuilder;
+import org.openremote.container.timer.TimerService;
+import org.openremote.manager.asset.AssetStorageService;
+import org.openremote.manager.rules.facade.NotificationsFacade;
+import org.openremote.manager.rules.flow.*;
+import org.openremote.model.rules.Assets;
+import org.openremote.model.rules.Notifications;
+import org.openremote.model.rules.Users;
+import org.openremote.model.rules.flow.*;
+
+import java.util.*;
+import java.util.stream.Collectors;
+
+public class FlowRulesBuilder {
+ private AssetStorageService assetStorageService;
+ private Map<String, Long> triggerMap = new LinkedHashMap<>();
+ private List<NodeCollection> nodeCollections = new ArrayList<>();
+ private Assets assetsFacade;
+ private Users usersFacade;
+ private Notifications notificationFacade;
+
+ private TimerService timerService;
+
+ public FlowRulesBuilder(
+ TimerService timerService,
+ AssetStorageService assetStorageService,
+ Assets assetsFacade,
+ Users usersFacade,
+ NotificationsFacade notificationFacade) {
+ this.timerService = timerService;
+ this.assetStorageService = assetStorageService;
+ this.assetsFacade = assetsFacade;
+ this.usersFacade = usersFacade;
+ this.notificationFacade = notificationFacade;
+ }
+
+ public void add(NodeCollection nodeCollection) {
+ nodeCollections.add(nodeCollection);
+ }
+
+ public Rule[] build() {
+ int count = 0;
+ List<Rule> rules = new ArrayList<>();
+ for (NodeCollection collection : nodeCollections) {
+ for (Node node : collection.getNodes()) {
+ if (node.getType() != NodeType.OUTPUT) continue;
+ try {
+ RulesEngine.RULES_LOG.info("Flow rule created");
+ rules.add(createRule(collection.getName() + " - " + count, collection, node));
+ count++;
+ } catch (Exception e) {
+ RulesEngine.RULES_LOG.severe("Flow rule error: " + e.getMessage());
+ }
+ }
+ }
+ return rules.toArray(new Rule[0]);
+ }
+
+ private Rule createRule(String name, NodeCollection collection, Node outputNode) throws Exception {
+ Object implementationResult = NodeModel.getImplementationFor(outputNode.getName()).execute(new NodeExecutionRequestInfo(collection, outputNode, null, null, assetsFacade, usersFacade, notificationFacade));
+
+ if (implementationResult == null)
+ throw new NullPointerException(outputNode.getName() + " node returns null");
+
+ if (!(implementationResult instanceof RulesBuilder.Action))
+ throw new Exception(outputNode.getName() + " node does not return an action");
+
+ RulesBuilder.Action action = (RulesBuilder.Action) implementationResult;
+
+ RulesBuilder.Condition condition = facts -> {
+ List<Node> connectedTree = backtrackFrom(collection, outputNode);
+
+ return connectedTree.stream().anyMatch(node -> {
+ NodeTriggerFunction function = NodeModel.getTriggerFunctionFor(node.getName());
+ return function.satisfies(new NodeTriggerParameters(name, facts, this, collection, node));
+ });
+ };
+
+ triggerMap.put(name, -1L);
+
+ return new RuleBuilder().
+ name(name).
+ description(collection.getDescription()).
+ when(facts -> {
+ Object result;
+ try {
+ result = condition.evaluate((RulesFacts) facts);
+ } catch (Exception ex) {
+ throw new RuntimeException("Error evaluating condition of rule '" + name + "': " + ex.getMessage(), ex);
+ }
+ if (result instanceof Boolean) {
+ return (boolean) result;
+ } else {
+ throw new IllegalArgumentException("Error evaluating condition of rule '" + name + "': result is not boolean but " + result);
+ }
+ }).
+ then(facts -> {
+ action.execute((RulesFacts) facts);
+ triggerMap.put(name, timerService.getCurrentTimeMillis());
+ }).
+ build();
+ }
+
+ private List<Node> backtrackFrom(NodeCollection collection, Node node) {
+ List<Node> total = new ArrayList<>();
+ List<Node> children = new ArrayList<>();
+
+ for (NodeSocket s : node.getInputs()) {
+ children.addAll(Arrays.stream(collection.getConnections()).filter(c -> c.getTo().equals(s.getId())).map(c -> collection.getNodeById(collection.getSocketById(c.getFrom()).getNodeId())).collect(Collectors.toList()));
+ }
+
+ for (Node child : children) {
+ total.add(child);
+ total.addAll(backtrackFrom(collection, child));
+ }
+
+ return total;
+ }
+
+ public Map<String, Long> getTriggerMap() {
+ return triggerMap;
+ }
+}
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesService.java b/manager/src/main/java/org/openremote/manager/rules/RulesService.java
index 61cd96374..b1befb046 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesService.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesService.java
@@ -33,8 +33,10 @@ import org.openremote.manager.asset.AssetUpdateProcessor;
import org.openremote.manager.concurrent.ManagerExecutorService;
import org.openremote.manager.event.ClientEventService;
import org.openremote.manager.notification.NotificationService;
+import org.openremote.manager.rules.flow.FlowResourceImpl;
import org.openremote.manager.rules.geofence.GeofenceAssetAdapter;
import org.openremote.manager.security.ManagerIdentityService;
+import org.openremote.manager.web.ManagerWebService;
import org.openremote.model.Constants;
import org.openremote.model.asset.Asset;
import org.openremote.model.asset.AssetAttribute;
@@ -167,6 +169,13 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse
geofenceAssetAdapters.sort(Comparator.comparingInt(GeofenceAssetAdapter::getPriority));
container.getService(MessageBrokerSetupService.class).getContext().addRoutes(this);
configEventExpires = getString(container.getConfig(), RULE_EVENT_EXPIRES, RULE_EVENT_EXPIRES_DEFAULT);
+
+ container.getService(ManagerWebService.class).getApiSingletons().add(
+ new FlowResourceImpl(
+ container.getService(TimerService.class),
+ container.getService(ManagerIdentityService.class)
+ )
+ );
}
@Override
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesetDeployment.java b/manager/src/main/java/org/openremote/manager/rules/RulesetDeployment.java
index 73127f5f3..a523f7957 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesetDeployment.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesetDeployment.java
@@ -41,7 +41,7 @@ import org.openremote.model.rules.Assets;
import org.openremote.model.rules.Ruleset;
import org.openremote.model.rules.RulesetStatus;
import org.openremote.model.rules.Users;
-import org.openremote.model.rules.json.JsonRulesetDefinition;
+import org.openremote.model.rules.flow.NodeCollection;
import org.openremote.model.util.Pair;
import javax.script.*;
@@ -94,6 +94,7 @@ public class RulesetDeployment {
throw new SecurityException("Not allowed: " + receiver);
}
}
+
public static final int DEFAULT_RULE_PRIORITY = 1000;
// Share one JS script engine manager, it's thread-safe
static final protected ScriptEngineManager scriptEngineManager;
@@ -135,6 +136,7 @@ public class RulesetDeployment {
protected RulesetStatus status = RulesetStatus.READY;
protected Throwable error;
protected JsonRulesBuilder jsonRulesBuilder;
+ protected FlowRulesBuilder flowRulesBuilder;
protected CalendarEvent validity;
protected Pair<Long, Long> nextValidity;
@@ -212,6 +214,8 @@ public class RulesetDeployment {
return compileRulesGroovy(ruleset, assetsFacade, usersFacade, notificationsFacade);
case JSON:
return compileRulesJson(ruleset);
+ case FLOW:
+ return compileRulesFlow(ruleset, assetsFacade,usersFacade,notificationsFacade);
}
return false;
}
@@ -442,6 +446,23 @@ public class RulesetDeployment {
}
}
+ protected boolean compileRulesFlow(Ruleset ruleset, Assets assetsFacade, Users usersFacade, NotificationsFacade consolesFacade) {
+ try {
+ flowRulesBuilder = new FlowRulesBuilder(timerService, assetStorageService, assetsFacade, usersFacade, notificationsFacade);
+ NodeCollection nodeCollection = Container.JSON.readValue(ruleset.getRules(), NodeCollection.class);
+ flowRulesBuilder.add(nodeCollection);
+ for (Rule rule : flowRulesBuilder.build()) {
+ RulesEngine.LOG.info("Registering rule: " + rule.getName());
+ rules.register(rule);
+ }
+ return true;
+ } catch (Exception e) {
+ RulesEngine.LOG.log(Level.SEVERE, "Error evaluating ruleset: " + ruleset, e);
+ setError(e);
+ return false;
+ }
+ }
+
public RulesetStatus getStatus() {
return status;
}
@@ -463,7 +484,7 @@ public class RulesetDeployment {
}
public boolean isError() {
- return getStatus() == RulesetStatus.LOOP_ERROR || ((getStatus() == RulesetStatus.EXECUTION_ERROR || getStatus() == RulesetStatus.COMPILATION_ERROR) && !isContinueOnError());
+ return getStatus() == RulesetStatus.LOOP_ERROR || ((getStatus() == RulesetStatus.EXECUTION_ERROR || getStatus() == RulesetStatus.COMPILATION_ERROR) && !isContinueOnError());
}
public boolean isContinueOnError() {
@@ -479,4 +500,4 @@ public class RulesetDeployment {
", status=" + status +
'}';
}
-}
+}
\ No newline at end of file
diff --git a/manager/src/main/java/org/openremote/manager/rules/flow/FlowResourceImpl.java b/manager/src/main/java/org/openremote/manager/rules/flow/FlowResourceImpl.java
new file mode 100644
index 000000000..ad3493980
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/rules/flow/FlowResourceImpl.java
@@ -0,0 +1,39 @@
+package org.openremote.manager.rules.flow;
+
+import org.openremote.container.timer.TimerService;
+import org.openremote.manager.security.ManagerIdentityService;
+import org.openremote.manager.web.ManagerWebResource;
+import org.openremote.model.http.RequestParams;
+import org.openremote.model.rules.flow.FlowResource;
+import org.openremote.model.rules.flow.Node;
+import org.openremote.model.rules.flow.NodeType;
+
+import java.util.Arrays;
+import java.util.logging.Logger;
+
+public class FlowResourceImpl extends ManagerWebResource implements FlowResource {
+
+ private static final Logger LOG = Logger.getLogger(FlowResourceImpl.class.getName());
+
+ public FlowResourceImpl(TimerService timerService, ManagerIdentityService identityService) {
+ super(timerService, identityService);
+ for (Node node : Arrays.stream(NodeModel.values()).map(c -> c.getDefinition()).toArray(Node[]::new)) {
+ LOG.info("Node found: " + node.getName());
+ }
+ }
+
+ @Override
+ public Node[] getAllNodeDefinitions(RequestParams requestParams) {
+ return Arrays.stream(NodeModel.values()).map(c -> c.getDefinition()).toArray(Node[]::new);
+ }
+
+ @Override
+ public Node[] getAllNodeDefinitionsByType(RequestParams requestParams, NodeType type) {
+ return Arrays.stream(NodeModel.values()).filter((n) -> n.getDefinition().getType().equals(type)).map(c -> c.getDefinition()).toArray(Node[]::new);
+ }
+
+ @Override
+ public Node getNodeDefinition(RequestParams requestParams, String name) {
+ return NodeModel.getDefinitionFor(name);
+ }
+}
diff --git a/manager/src/main/java/org/openremote/manager/rules/flow/NodeExecutionRequestInfo.java b/manager/src/main/java/org/openremote/manager/rules/flow/NodeExecutionRequestInfo.java
new file mode 100644
index 000000000..ffcaa4347
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/rules/flow/NodeExecutionRequestInfo.java
@@ -0,0 +1,188 @@
+package org.openremote.manager.rules.flow;
+
+import org.openremote.manager.rules.RulesFacts;
+import org.openremote.model.rules.Assets;
+import org.openremote.model.rules.Notifications;
+import org.openremote.model.rules.Users;
+import org.openremote.model.rules.flow.*;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
+
+public class NodeExecutionRequestInfo {
+ private NodeCollection collection;
+
+ private int outputSocketIndex;
+ private NodeSocket outputSocket;
+
+ private Node node;
+ private NodeSocket[] inputs;
+ private NodeSocket[] outputs;
+ private NodeInternal[] internals;
+
+ private RulesFacts facts;
+
+ private Assets assets;
+ private Users users;
+ private Notifications notifications;
+
+ public NodeExecutionRequestInfo() {
+ collection = new NodeCollection();
+ outputSocketIndex = -1;
+ outputSocket = null;
+ node = null;
+ inputs = new NodeSocket[]{};
+ outputs = new NodeSocket[]{};
+ internals = new NodeInternal[]{};
+ facts = null;
+ assets = null;
+ users = null;
+ notifications = null;
+ }
+
+ public NodeExecutionRequestInfo(NodeCollection collection, int outputSocketIndex, NodeSocket outputSocket, Node node, NodeSocket[] inputs, NodeSocket[] outputs, NodeInternal[] internals, RulesFacts facts, Assets assets, Users users, Notifications notifications) {
+ this.collection = collection;
+ this.outputSocketIndex = outputSocketIndex;
+ this.outputSocket = outputSocket;
+ this.node = node;
+ this.inputs = inputs;
+ this.outputs = outputs;
+ this.internals = internals;
+ this.facts = facts;
+ this.assets = assets;
+ this.users = users;
+ this.notifications = notifications;
+ }
+
+ public NodeExecutionRequestInfo(NodeCollection collection, Node node, NodeSocket socket, RulesFacts facts, Assets assets, Users users, Notifications notifications) {
+ if (socket != null && Arrays.stream(node.getOutputs()).noneMatch(c -> c.getNodeId().equals(node.getId())))
+ throw new IllegalArgumentException("Given socket does not belong to given node");
+
+ this.collection = collection;
+ this.outputSocketIndex = Arrays.asList(node.getOutputs()).indexOf(socket);
+ this.outputSocket = socket;
+ this.node = node;
+
+ List<NodeSocket> inputs = new ArrayList<>();
+ for (NodeSocket s : node.getInputs()) {
+ inputs.addAll(Arrays.stream(collection.getConnections()).filter(c -> c.getTo().equals(s.getId())).map(c -> collection.getSocketById(c.getFrom())).collect(Collectors.toList()));
+ }
+ this.inputs = inputs.toArray(new NodeSocket[0]);
+
+ List<NodeSocket> outputs = new ArrayList<>();
+ for (NodeSocket s : node.getOutputs()) {
+ outputs.addAll(Arrays.stream(collection.getConnections()).filter(c -> c.getFrom().equals(s.getId())).map(c -> collection.getSocketById(c.getTo())).collect(Collectors.toList()));
+ }
+
+ this.outputs = outputs.toArray(new NodeSocket[0]);
+ this.internals = node.getInternals();
+
+ this.facts = facts;
+ this.assets = assets;
+ this.users = users;
+ this.notifications = notifications;
+ }
+
+ public Object getValueFromInput(int index) {
+ NodeSocket aSocket = getInputs()[index];
+ Node aNode = getCollection().getNodeById(aSocket.getNodeId());
+ return NodeModel.getImplementationFor(aNode.getName()).execute(
+ new NodeExecutionRequestInfo(getCollection(), aNode, aSocket, getFacts(), getAssets(), getUsers(), getNotifications())
+ );
+ }
+
+ public NodeDataType getTypeFromInput(int index) {
+ NodeSocket aSocket = getInputs()[index];
+ return aSocket.getType();
+ }
+
+ public NodeCollection getCollection() {
+ return collection;
+ }
+
+ public void setCollection(NodeCollection collection) {
+ this.collection = collection;
+ }
+
+ public int getOutputSocketIndex() {
+ return outputSocketIndex;
+ }
+
+ public void setOutputSocketIndex(int outputSocketIndex) {
+ this.outputSocketIndex = outputSocketIndex;
+ }
+
+ public NodeSocket getOutputSocket() {
+ return outputSocket;
+ }
+
+ public void setOutputSocket(NodeSocket outputSocket) {
+ this.outputSocket = outputSocket;
+ }
+
+ public Node getNode() {
+ return node;
+ }
+
+ public void setNode(Node node) {
+ this.node = node;
+ }
+
+ public NodeSocket[] getInputs() {
+ return inputs;
+ }
+
+ public void setInputs(NodeSocket[] inputs) {
+ this.inputs = inputs;
+ }
+
+ public NodeSocket[] getOutputs() {
+ return outputs;
+ }
+
+ public void setOutputs(NodeSocket[] outputs) {
+ this.outputs = outputs;
+ }
+
+ public NodeInternal[] getInternals() {
+ return internals;
+ }
+
+ public void setInternals(NodeInternal[] internals) {
+ this.internals = internals;
+ }
+
+ public Assets getAssets() {
+ return assets;
+ }
+
+ public void setAssets(Assets assets) {
+ this.assets = assets;
+ }
+
+ public Users getUsers() {
+ return users;
+ }
+
+ public void setUsers(Users users) {
+ this.users = users;
+ }
+
+ public Notifications getNotifications() {
+ return notifications;
+ }
+
+ public void setNotifications(Notifications notifications) {
+ this.notifications = notifications;
+ }
+
+ public RulesFacts getFacts() {
+ return facts;
+ }
+
+ public void setFacts(RulesFacts facts) {
+ this.facts = facts;
+ }
+}
diff --git a/manager/src/main/java/org/openremote/manager/rules/flow/NodeImplementation.java b/manager/src/main/java/org/openremote/manager/rules/flow/NodeImplementation.java
new file mode 100644
index 000000000..7de6d544e
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/rules/flow/NodeImplementation.java
@@ -0,0 +1,6 @@
+package org.openremote.manager.rules.flow;
+
+public interface NodeImplementation {
+ Object execute(NodeExecutionRequestInfo info);
+}
+
diff --git a/manager/src/main/java/org/openremote/manager/rules/flow/NodeModel.java b/manager/src/main/java/org/openremote/manager/rules/flow/NodeModel.java
new file mode 100644
index 000000000..cac99bfa8
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/rules/flow/NodeModel.java
@@ -0,0 +1,480 @@
+package org.openremote.manager.rules.flow;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import org.openremote.container.Container;
+import org.openremote.manager.rules.RulesBuilder;
+import org.openremote.manager.rules.RulesEngine;
+import org.openremote.model.query.AssetQuery;
+import org.openremote.model.rules.AssetState;
+import org.openremote.model.rules.flow.*;
+import org.openremote.model.value.*;
+
+import java.util.List;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
+public enum NodeModel {
+ READ_ATTRIBUTE(
+ new Node(NodeType.INPUT, new NodeInternal[]{
+ new NodeInternal("Attribute", new Picker(PickerType.ASSET_ATTRIBUTE))
+ },
+ new NodeSocket[0], new NodeSocket[]{
+ new NodeSocket("value", NodeDataType.ANY)
+ }),
+ info -> {
+ AssetAttributeInternalValue assetAttributePair = Container.JSON.convertValue(info.getInternals()[0].getValue(), AssetAttributeInternalValue.class);
+ String assetId = assetAttributePair.getAssetId();
+ String attributeName = assetAttributePair.getAttributeName();
+ Optional<AssetState> readValue = info.getFacts().matchFirstAssetState(new AssetQuery().ids(assetId).attributeName(attributeName));
+ if (!readValue.isPresent()) return null;
+ return readValue.get().getValue().orElse(null);
+ },
+ params -> {
+ AssetAttributeInternalValue internal = Container.JSON.convertValue(params.getNode().getInternals()[0].getValue(), AssetAttributeInternalValue.class);
+ String assetId = internal.getAssetId();
+ String attributeName = internal.getAttributeName();
+ List<AssetState> allAssets = params.getFacts().matchAssetState(new AssetQuery().ids(assetId).attributeName(attributeName)
+ ).collect(Collectors.toList());
+
+ return allAssets.stream().anyMatch(state -> {
+ long timestamp = state.getTimestamp();
+ long triggerStamp = params.getBuilder().getTriggerMap().getOrDefault(params.getRuleName(), -1L);
+ if (triggerStamp == -1L) return true; //The flow has never been executed
+ return timestamp > triggerStamp && state.isValueChanged();
+ });
+ }
+ ),
+
+ WRITE_ATTRIBUTE(new Node(NodeType.OUTPUT, new NodeInternal[]{
+ new NodeInternal("Attribute", new Picker(PickerType.ASSET_ATTRIBUTE))
+ }, new NodeSocket[]{
+ new NodeSocket("value", NodeDataType.ANY)
+ }, new NodeSocket[0]),
+ info -> ((RulesBuilder.Action) facts -> {
+ info.setFacts(facts);
+ Object value = info.getValueFromInput(0);
+ if (value == null) {
+ RulesEngine.LOG.warning("Flow rule error: node " + info.getNode().getName() + " receives invalid value");
+ return;
+ }
+ AssetAttributeInternalValue assetAttributePair = Container.JSON.convertValue(info.getInternals()[0].getValue(), AssetAttributeInternalValue.class);
+ Optional<AssetState> existingValue = info.getFacts().matchFirstAssetState(new AssetQuery().ids(assetAttributePair.getAssetId()).attributeName(assetAttributePair.getAttributeName()));
+
+ if (existingValue.isPresent())
+ if (existingValue.get().getValue().isPresent())
+ if (existingValue.get().getValue().get().equals(value)) return;
+
+ try {
+ if (value instanceof Value) {
+ info.getAssets().dispatch(
+ assetAttributePair.getAssetId(),
+ assetAttributePair.getAttributeName(),
+ (Value) value
+ );
+ } else {
+ info.getAssets().dispatch(
+ assetAttributePair.getAssetId(),
+ assetAttributePair.getAttributeName(),
+ Values.parseOrNull(Container.JSON.writeValueAsString(value))
+ );
+ }
+ } catch (JsonProcessingException e) {
+ RulesEngine.LOG.severe("Flow rule error: node " + info.getNode().getName() + " receives invalid value");
+ }
+ })),
+
+ BOOLEAN_INPUT(new Node(NodeType.INPUT, new NodeInternal[]{
+ new NodeInternal("value", new Picker(PickerType.CHECKBOX))
+ }, new NodeSocket[0], new NodeSocket[]{
+ new NodeSocket("value", NodeDataType.BOOLEAN)
+ }),
+ info -> {
+ Object value = info.getInternals()[0].getValue();
+ if (value == null) return Values.create(false);
+ if (!(value instanceof Boolean)) return Values.create(false);
+ return Values.create((boolean) value);
+ }),
+
+ AND_GATE(new Node(NodeType.PROCESSOR, "&", new NodeInternal[0], new NodeSocket[]{
+ new NodeSocket("a", NodeDataType.BOOLEAN),
+ new NodeSocket("b", NodeDataType.BOOLEAN),
+ }, new NodeSocket[]{
+ new NodeSocket("c", NodeDataType.BOOLEAN),
+ }),
+ info -> {
+ try {
+ BooleanValue a = (BooleanValue) info.getValueFromInput(0);
+ BooleanValue b = (BooleanValue) info.getValueFromInput(1);
+ return Values.create(a.getBoolean() && b.getBoolean());
+ } catch (Exception e) {
+ RulesEngine.LOG.warning("Flow rule processing error: " + e.getMessage());
+ return Values.create(false);
+ }
+ }),
+
+ OR_GATE(new Node(NodeType.PROCESSOR, "∥", new NodeInternal[0], new NodeSocket[]{
+ new NodeSocket("a", NodeDataType.BOOLEAN),
+ new NodeSocket("b", NodeDataType.BOOLEAN),
+ }, new NodeSocket[]{
+ new NodeSocket("c", NodeDataType.BOOLEAN),
+ }),
+ info -> {
+ try {
+ BooleanValue a = (BooleanValue) info.getValueFromInput(0);
+ BooleanValue b = (BooleanValue) info.getValueFromInput(1);
+ return Values.create(a.getBoolean() || b.getBoolean());
+ } catch (Exception e) {
+ RulesEngine.LOG.warning("Flow rule processing error: " + e.getMessage());
+ return Values.create(false);
+ }
+ }),
+
+ NOT_GATE(new Node(NodeType.PROCESSOR, "!", new NodeInternal[0], new NodeSocket[]{
+ new NodeSocket("i", NodeDataType.BOOLEAN),
+ }, new NodeSocket[]{
+ new NodeSocket("o", NodeDataType.BOOLEAN),
+ }),
+ info -> {
+ try {
+ BooleanValue a = (BooleanValue) info.getValueFromInput(0);
+ return Values.create(!a.getBoolean());
+ } catch (Exception e) {
+ RulesEngine.LOG.warning("Flow rule processing error: " + e.getMessage());
+ return Values.create(true);
+ }
+ }),
+
+ NUMBER_INPUT(new Node(NodeType.INPUT, new NodeInternal[]{
+ new NodeInternal("value", new Picker(PickerType.NUMBER))
+ }, new NodeSocket[0], new NodeSocket[]{
+ new NodeSocket("value", NodeDataType.NUMBER)
+ }),
+ info -> {
+ try {
+ return Values.create(Float.parseFloat(Container.JSON.writeValueAsString(info.getInternals()[0].getValue())));
+ } catch (JsonProcessingException e) {
+ RulesEngine.RULES_LOG.warning("Number node returned invalid value");
+ return Values.create(0f);
+ }
+ }),
+
+ ADD_OPERATOR(new Node(NodeType.PROCESSOR, "+", new NodeInternal[0], new NodeSocket[]{
+ new NodeSocket("a", NodeDataType.NUMBER),
+ new NodeSocket("b", NodeDataType.NUMBER),
+ }, new NodeSocket[]{
+ new NodeSocket("c", NodeDataType.NUMBER),
+ }),
+ info -> {
+ try {
+ NumberValue a = (NumberValue) info.getValueFromInput(0);
+ NumberValue b = (NumberValue) info.getValueFromInput(1);
+ return Values.create(a.getNumber() + b.getNumber());
+ } catch (Exception e) {
+ RulesEngine.LOG.warning("Flow rule processing error: " + e.getMessage());
+ return Values.create(0);
+ }
+ }),
+
+ SUBTRACT_OPERATOR(new Node(NodeType.PROCESSOR, "-", new NodeInternal[0], new NodeSocket[]{
+ new NodeSocket("a", NodeDataType.NUMBER),
+ new NodeSocket("b", NodeDataType.NUMBER),
+ }, new NodeSocket[]{
+ new NodeSocket("c", NodeDataType.NUMBER),
+ }),
+ info -> {
+ try {
+ NumberValue a = (NumberValue) info.getValueFromInput(0);
+ NumberValue b = (NumberValue) info.getValueFromInput(1);
+ return Values.create(a.getNumber() - b.getNumber());
+ } catch (Exception e) {
+ RulesEngine.LOG.warning("Flow rule processing error: " + e.getMessage());
+ return Values.create(0);
+ }
+ }),
+
+ MULTIPLY_OPERATOR(new Node(NodeType.PROCESSOR, "×", new NodeInternal[0], new NodeSocket[]{
+ new NodeSocket("a", NodeDataType.NUMBER),
+ new NodeSocket("b", NodeDataType.NUMBER),
+ }, new NodeSocket[]{
+ new NodeSocket("c", NodeDataType.NUMBER),
+ }),
+ info -> {
+ try {
+ NumberValue a = (NumberValue) info.getValueFromInput(0);
+ NumberValue b = (NumberValue) info.getValueFromInput(1);
+ return Values.create(a.getNumber() * b.getNumber());
+ } catch (Exception e) {
+ RulesEngine.LOG.warning("Flow rule processing error: " + e.getMessage());
+ return Values.create(0);
+ }
+ }),
+
+ DIVIDE_OPERATOR(new Node(NodeType.PROCESSOR, "÷", new NodeInternal[0], new NodeSocket[]{
+ new NodeSocket("a", NodeDataType.NUMBER),
+ new NodeSocket("b", NodeDataType.NUMBER),
+ }, new NodeSocket[]{
+ new NodeSocket("c", NodeDataType.NUMBER),
+ }),
+ info -> {
+ try {
+ NumberValue a = (NumberValue) info.getValueFromInput(0);
+ NumberValue b = (NumberValue) info.getValueFromInput(1);
+
+ if (b.getNumber() == 0)
+ return Values.create(0f);
+
+ return Values.create(a.getNumber() / b.getNumber());
+ } catch (Exception e) {
+ RulesEngine.LOG.warning("Flow rule processing error: " + e.getMessage());
+ return Values.create(0);
+ }
+ }),
+
+ EQUALS_COMPARATOR(new Node(NodeType.PROCESSOR, "=", new NodeInternal[0], new NodeSocket[]{
+ new NodeSocket("a", NodeDataType.ANY),
+ new NodeSocket("b", NodeDataType.ANY),
+ }, new NodeSocket[]{
+ new NodeSocket("c", NodeDataType.BOOLEAN),
+ }),
+ info -> {
+ try {
+ Object a = info.getValueFromInput(0);
+ Object b = info.getValueFromInput(1);
+ return Values.create(a.equals(b));
+ } catch (Exception e) {
+ RulesEngine.LOG.warning("Flow rule processing error: " + e.getMessage());
+ return Values.create(false);
+ }
+ }),
+
+ GREATER_THAN(new Node(NodeType.PROCESSOR, ">", new NodeInternal[0], new NodeSocket[]{
+ new NodeSocket("a", NodeDataType.NUMBER),
+ new NodeSocket("b", NodeDataType.NUMBER),
+ }, new NodeSocket[]{
+ new NodeSocket("c", NodeDataType.BOOLEAN),
+ }),
+ info -> {
+ try {
+ NumberValue a = (NumberValue) info.getValueFromInput(0);
+ NumberValue b = (NumberValue) info.getValueFromInput(1);
+ return Values.create(a.getNumber() > b.getNumber());
+ } catch (Exception e) {
+ RulesEngine.LOG.warning("Flow rule processing error: " + e.getMessage());
+ return Values.create(false);
+ }
+ }),
+
+ LESS_THAN(new Node(NodeType.PROCESSOR, "<", new NodeInternal[0], new NodeSocket[]{
+ new NodeSocket("a", NodeDataType.NUMBER),
+ new NodeSocket("b", NodeDataType.NUMBER),
+ }, new NodeSocket[]{
+ new NodeSocket("c", NodeDataType.BOOLEAN),
+ }),
+ info -> {
+ try {
+ NumberValue a = (NumberValue) info.getValueFromInput(0);
+ NumberValue b = (NumberValue) info.getValueFromInput(1);
+ return Values.create(a.getNumber() < b.getNumber());
+ } catch (Exception e) {
+ RulesEngine.LOG.warning("Flow rule processing error: " + e.getMessage());
+ return Values.create(false);
+ }
+ }),
+
+ ROUND_NODE(new Node(NodeType.PROCESSOR, new NodeInternal[]{
+ new NodeInternal("Rounding method", new Picker(PickerType.DROPDOWN, new Option[]{
+ new Option("Round", "round"),
+ new Option("Ceiling", "ceil"),
+ new Option("Floor", "floor")
+ }))
+ }, new NodeSocket[]{
+ new NodeSocket("value", NodeDataType.NUMBER),
+ }, new NodeSocket[]{
+ new NodeSocket("value", NodeDataType.NUMBER),
+ }),
+ info -> {
+ try {
+ NumberValue a = (NumberValue) info.getValueFromInput(0);
+ switch ((String) info.getInternals()[0].getValue()) {
+ case "round":
+ return Values.create((float) Math.round(a.getNumber()));
+ case "ceil":
+ return Values.create((float) Math.ceil(a.getNumber()));
+ case "floor":
+ return Values.create((float) Math.floor(a.getNumber()));
+ }
+ return Values.create((float) Math.round(a.getNumber()));
+ } catch (Exception e) {
+ RulesEngine.LOG.warning("Flow rule processing error: " + e.getMessage());
+ return Values.create(0);
+ }
+ }),
+
+ ABS_OPERATOR(new Node(NodeType.PROCESSOR, "|x|", new NodeInternal[0], new NodeSocket[]{
+ new NodeSocket("value", NodeDataType.NUMBER),
+ }, new NodeSocket[]{
+ new NodeSocket("absolute", NodeDataType.NUMBER),
+ }),
+ info -> {
+ try {
+ NumberValue a = (NumberValue) info.getValueFromInput(0);
+ return Values.create((float) Math.abs(a.getNumber()));
+ } catch (Exception e) {
+ RulesEngine.LOG.warning("Flow rule processing error: " + e.getMessage());
+ return Values.create(false);
+ }
+ }),
+
+ POW_OPERATOR(new Node(NodeType.PROCESSOR, "^", new NodeInternal[0], new NodeSocket[]{
+ new NodeSocket("base", NodeDataType.NUMBER),
+ new NodeSocket("exponent", NodeDataType.NUMBER),
+ }, new NodeSocket[]{
+ new NodeSocket("value", NodeDataType.NUMBER),
+ }),
+ info -> {
+ try {
+ NumberValue a = (NumberValue) info.getValueFromInput(0);
+ NumberValue b = (NumberValue) info.getValueFromInput(1);
+ return Values.create((float) Math.pow(a.getNumber(), b.getNumber()));
+ } catch (Exception e) {
+ RulesEngine.LOG.warning("Flow rule processing error: " + e.getMessage());
+ return Values.create(false);
+ }
+ }),
+
+ NUMBER_SWITCH(new Node(NodeType.PROCESSOR, new NodeInternal[0], new NodeSocket[]{
+ new NodeSocket("when", NodeDataType.BOOLEAN),
+ new NodeSocket("then", NodeDataType.NUMBER),
+ new NodeSocket("else", NodeDataType.NUMBER),
+ }, new NodeSocket[]{
+ new NodeSocket("output", NodeDataType.NUMBER),
+ }),
+ info -> {
+ try {
+ BooleanValue condition;
+ try {
+ condition = (BooleanValue) info.getValueFromInput(0);
+ } catch (Exception e) {
+ condition = Values.create(false);
+ }
+ NumberValue then = (NumberValue) info.getValueFromInput(1);
+ NumberValue _else = (NumberValue) info.getValueFromInput(2);
+ return Values.create(condition.getBoolean() ? then.getNumber() : _else.getNumber());
+ } catch (Exception e) {
+ RulesEngine.LOG.warning("Flow rule processing error: " + e.getMessage());
+ return Values.create(0);
+ }
+ }),
+
+ TEXT_INPUT(new Node(NodeType.INPUT, new NodeInternal[]{
+ new NodeInternal("value", new Picker(PickerType.MULTILINE))
+ }, new NodeSocket[0], new NodeSocket[]{
+ new NodeSocket("value", NodeDataType.STRING)
+ }),
+ info -> {
+ Object value = info.getInternals()[0].getValue();
+ if (value == null) return Values.create("");
+ if (!(value instanceof String)) return Values.create("");
+ return Values.create((String) value);
+ }),
+
+ COMBINE_TEXT(new Node(NodeType.PROCESSOR, new NodeInternal[]{
+ new NodeInternal("joiner", new Picker(PickerType.TEXT))
+ }, new NodeSocket[]{
+ new NodeSocket("a", NodeDataType.STRING),
+ new NodeSocket("b", NodeDataType.STRING),
+ }, new NodeSocket[]{
+ new NodeSocket("c", NodeDataType.STRING),
+ }),
+ info -> {
+ try {
+ Object rJoiner = info.getInternals()[0].getValue();
+ Object rA = info.getValueFromInput(0);
+ Object rB = info.getValueFromInput(1);
+ StringValue a, b;
+
+ if (rA instanceof StringValue)
+ a = (StringValue) rA;
+ else a = Values.create(rA.toString());
+
+ if (rB instanceof StringValue)
+ b = (StringValue) rB;
+ else b = Values.create(rB.toString());
+
+ String joiner = rJoiner == null ? "" : (String) rJoiner;
+ return Values.create(a.getString() + joiner + b.getString());
+ } catch (Exception e) {
+ RulesEngine.LOG.warning("Flow rule processing error: " + e.getMessage());
+ return Values.create(0);
+ }
+ }),
+
+ TEXT_SWITCH(new Node(NodeType.PROCESSOR, new NodeInternal[0], new NodeSocket[]{
+ new NodeSocket("when", NodeDataType.BOOLEAN),
+ new NodeSocket("then", NodeDataType.STRING),
+ new NodeSocket("else", NodeDataType.STRING),
+ }, new NodeSocket[]{
+ new NodeSocket("output", NodeDataType.STRING),
+ }),
+ info -> {
+ try {
+ BooleanValue condition;
+ try {
+ condition = (BooleanValue) info.getValueFromInput(0);
+ } catch (Exception e) {
+ condition = Values.create(false);
+ }
+ StringValue then = (StringValue) info.getValueFromInput(1);
+ StringValue _else = (StringValue) info.getValueFromInput(2);
+ return Values.create(condition.getBoolean() ? then.getString() : _else.getString());
+ } catch (Exception e) {
+ RulesEngine.LOG.warning("Flow rule processing error: " + e.getMessage());
+ return Values.create(0);
+ }
+ }),
+ ;
+
+ NodeModel(Node definition, NodeImplementation implementation) {
+ this.definition = definition;
+ definition.setName(this.name());
+ this.implementation = implementation;
+ this.triggerFunction = (params) -> {
+ return false;
+ };
+ }
+
+ NodeModel(Node definition, NodeImplementation implementation, NodeTriggerFunction triggerFunction) {
+ this.definition = definition;
+ definition.setName(this.name());
+ this.implementation = implementation;
+ this.triggerFunction = triggerFunction;
+ }
+
+ private Node definition;
+ private NodeImplementation implementation;
+ private NodeTriggerFunction triggerFunction;
+
+ public Node getDefinition() {
+ return definition;
+ }
+
+ public NodeImplementation getImplementation() {
+ return implementation;
+ }
+
+ public NodeTriggerFunction getTriggerFunction() {
+ return triggerFunction;
+ }
+
+ public static NodeImplementation getImplementationFor(String name) {
+ return NodeModel.valueOf(name).implementation;
+ }
+
+ public static NodeTriggerFunction getTriggerFunctionFor(String name) {
+ return NodeModel.valueOf(name).triggerFunction;
+ }
+
+ public static Node getDefinitionFor(String name) {
+ return NodeModel.valueOf(name).definition;
+ }
+}
diff --git a/manager/src/main/java/org/openremote/manager/rules/flow/NodeTriggerFunction.java b/manager/src/main/java/org/openremote/manager/rules/flow/NodeTriggerFunction.java
new file mode 100644
index 000000000..2ec2af7d9
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/rules/flow/NodeTriggerFunction.java
@@ -0,0 +1,5 @@
+package org.openremote.manager.rules.flow;
+
+public interface NodeTriggerFunction {
+ boolean satisfies(NodeTriggerParameters parameters);
+}
diff --git a/manager/src/main/java/org/openremote/manager/rules/flow/NodeTriggerParameters.java b/manager/src/main/java/org/openremote/manager/rules/flow/NodeTriggerParameters.java
new file mode 100644
index 000000000..562a19326
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/rules/flow/NodeTriggerParameters.java
@@ -0,0 +1,42 @@
+package org.openremote.manager.rules.flow;
+
+import org.openremote.manager.rules.FlowRulesBuilder;
+import org.openremote.manager.rules.RulesFacts;
+import org.openremote.model.rules.flow.Node;
+import org.openremote.model.rules.flow.NodeCollection;
+
+public class NodeTriggerParameters {
+ private String ruleName;
+ private RulesFacts facts;
+ private FlowRulesBuilder builder;
+ private NodeCollection collection;
+ private Node node;
+
+ public NodeTriggerParameters(String ruleName, RulesFacts facts, FlowRulesBuilder builder, NodeCollection collection, Node node) {
+ this.ruleName = ruleName;
+ this.facts = facts;
+ this.builder = builder;
+ this.collection = collection;
+ this.node = node;
+ }
+
+ public String getRuleName() {
+ return ruleName;
+ }
+
+ public RulesFacts getFacts() {
+ return facts;
+ }
+
+ public FlowRulesBuilder getBuilder() {
+ return builder;
+ }
+
+ public NodeCollection getCollection() {
+ return collection;
+ }
+
+ public Node getNode() {
+ return node;
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/rules/Ruleset.java b/model/src/main/java/org/openremote/model/rules/Ruleset.java
index b209dbab5..48070f11f 100644
--- a/model/src/main/java/org/openremote/model/rules/Ruleset.java
+++ b/model/src/main/java/org/openremote/model/rules/Ruleset.java
@@ -127,7 +127,8 @@ public abstract class Ruleset {
" reset: null // Only trigger once ever\n" +
" }\n" +
"]"
- );
+ ),
+ FLOW(".json", "{\"name\":\"\", \"description\": \"\", \"nodes\":[], \"connections\":[]}");
final String fileExtension;
final String emptyRulesExample;
diff --git a/model/src/main/java/org/openremote/model/rules/flow/AssetAttributeInternalValue.java b/model/src/main/java/org/openremote/model/rules/flow/AssetAttributeInternalValue.java
new file mode 100644
index 000000000..2f4c8d280
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/rules/flow/AssetAttributeInternalValue.java
@@ -0,0 +1,30 @@
+package org.openremote.model.rules.flow;
+
+public class AssetAttributeInternalValue {
+ private String assetId;
+ private String attributeName;
+
+ public AssetAttributeInternalValue() {
+ }
+
+ public AssetAttributeInternalValue(String assetId, String attributeName) {
+ this.assetId = assetId;
+ this.attributeName = attributeName;
+ }
+
+ public String getAssetId() {
+ return assetId;
+ }
+
+ public void setAssetId(String assetId) {
+ this.assetId = assetId;
+ }
+
+ public String getAttributeName() {
+ return attributeName;
+ }
+
+ public void setAttributeName(String attributeName) {
+ this.attributeName = attributeName;
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/rules/flow/FlowResource.java b/model/src/main/java/org/openremote/model/rules/flow/FlowResource.java
new file mode 100644
index 000000000..5ac9bfc6a
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/rules/flow/FlowResource.java
@@ -0,0 +1,30 @@
+package org.openremote.model.rules.flow;
+
+import jsinterop.annotations.JsType;
+import org.openremote.model.http.RequestParams;
+import org.openremote.model.http.SuccessStatusCode;
+
+import javax.ws.rs.*;
+
+import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
+
+@Path("flow")
+@JsType(isNative = true)
+public interface FlowResource {
+ @GET
+ @Produces(APPLICATION_JSON)
+ @SuccessStatusCode(200)
+ Node[] getAllNodeDefinitions(@BeanParam RequestParams requestParams);
+
+ @GET
+ @Path("{type}")
+ @Produces(APPLICATION_JSON)
+ @SuccessStatusCode(200)
+ Node[] getAllNodeDefinitionsByType(@BeanParam RequestParams requestParams, @PathParam("type") NodeType type);
+
+ @GET
+ @Path("{name}")
+ @Produces(APPLICATION_JSON)
+ @SuccessStatusCode(200)
+ Node getNodeDefinition(@BeanParam RequestParams requestParams, @PathParam("name") String name);
+}
diff --git a/model/src/main/java/org/openremote/model/rules/flow/Node.java b/model/src/main/java/org/openremote/model/rules/flow/Node.java
new file mode 100644
index 000000000..09c9aeb85
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/rules/flow/Node.java
@@ -0,0 +1,104 @@
+package org.openremote.model.rules.flow;
+
+public class Node {
+ // Generation of ID is the responsibility of the front end and is unique for every node in a structure, not for every node in the system
+ private String id;
+ private NodeType type;
+ private String name;
+ private NodePosition position;
+ private NodePosition size;
+ private NodeInternal[] internals;
+ private NodeSocket[] inputs;
+ private NodeSocket[] outputs;
+ private String displayCharacter;
+
+ public Node(NodeType type, NodeInternal[] internals, NodeSocket[] inputs, NodeSocket[] outputs) {
+ this.id = "INVALID ID";
+ this.type = type;
+ this.position = new NodePosition(0, 0);
+ this.size = new NodePosition(0, 0);
+ this.internals = internals;
+ this.inputs = inputs;
+ this.outputs = outputs;
+ this.displayCharacter = null;
+ }
+
+ public Node(NodeType type, String displayCharacter, NodeInternal[] internals, NodeSocket[] inputs, NodeSocket[] outputs) {
+ if (internals.length != 0)
+ throw new IllegalArgumentException("A node cannot have internals when a display character is specified");
+
+ this.id = "INVALID ID";
+ this.type = type;
+ this.position = new NodePosition(0, 0);
+ this.size = new NodePosition(0, 0);
+ this.internals = internals;
+ this.inputs = inputs;
+ this.outputs = outputs;
+ this.displayCharacter = displayCharacter;
+ }
+
+ public Node() {
+ id = "INVALID ID";
+ type = NodeType.INPUT;
+ name = "Unnamed node";
+ position = new NodePosition();
+ size = new NodePosition();
+ internals = new NodeInternal[]{};
+ inputs = new NodeSocket[]{};
+ outputs = new NodeSocket[]{};
+ displayCharacter = null;
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public NodeType getType() {
+ return type;
+ }
+
+ public void setType(NodeType type) {
+ this.type = type;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public NodePosition getPosition() {
+ return position;
+ }
+
+ public void setPosition(NodePosition position) {
+ this.position = position;
+ }
+
+ public NodeInternal[] getInternals() {
+ return internals;
+ }
+
+ public NodeSocket[] getInputs() {
+ return inputs;
+ }
+
+ public NodeSocket[] getOutputs() {
+ return outputs;
+ }
+
+ public String getDisplayCharacter() {
+ return displayCharacter;
+ }
+
+ public NodePosition getSize() {
+ return size;
+ }
+
+ public void setSize(NodePosition size) {
+ this.size = size;
+ }
+}
+
diff --git a/model/src/main/java/org/openremote/model/rules/flow/NodeCollection.java b/model/src/main/java/org/openremote/model/rules/flow/NodeCollection.java
new file mode 100644
index 000000000..3f56f0c16
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/rules/flow/NodeCollection.java
@@ -0,0 +1,76 @@
+package org.openremote.model.rules.flow;
+
+public class NodeCollection {
+ private String name;
+ private String description;
+ private Node[] nodes;
+ private NodeConnection[] connections;
+
+ public NodeCollection(String name, String description, Node[] nodes, NodeConnection[] connections) {
+ this.name = name;
+ this.description = description;
+ this.nodes = nodes;
+ this.connections = connections;
+ }
+
+ public NodeCollection() {
+ name = "Unnamed node collection";
+ description = "No description provided";
+ nodes = new Node[]{};
+ connections = new NodeConnection[]{};
+ }
+
+ public Node getNodeById(String id) throws IllegalArgumentException {
+ for (Node node : nodes) {
+ if (node.getId().equals(id))
+ return node;
+ }
+ throw new IllegalArgumentException("Invalid node ID");
+ }
+
+ public NodeSocket getSocketById(String id) throws IllegalArgumentException {
+ for (Node node : nodes) {
+ for (NodeSocket socket : node.getInputs())
+ if (socket.getId().equals(id))
+ return socket;
+
+ for (NodeSocket socket : node.getOutputs())
+ if (socket.getId().equals(id))
+ return socket;
+ }
+ throw new IllegalArgumentException("Invalid socket ID");
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public Node[] getNodes() {
+ return nodes;
+ }
+
+ public void setNodes(Node[] nodes) {
+ this.nodes = nodes;
+ }
+
+ public NodeConnection[] getConnections() {
+ return connections;
+ }
+
+ public void setConnections(NodeConnection[] connections) {
+ this.connections = connections;
+ }
+}
+
diff --git a/model/src/main/java/org/openremote/model/rules/flow/NodeConnection.java b/model/src/main/java/org/openremote/model/rules/flow/NodeConnection.java
new file mode 100644
index 000000000..b5387ed41
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/rules/flow/NodeConnection.java
@@ -0,0 +1,32 @@
+package org.openremote.model.rules.flow;
+
+public class NodeConnection {
+ private String from;
+ private String to;
+
+ public NodeConnection(String from, String to) {
+ this.from = from;
+ this.to = to;
+ }
+
+ public NodeConnection() {
+ from = null;
+ to = null;
+ }
+
+ public String getFrom() {
+ return from;
+ }
+
+ public void setFrom(String from) {
+ this.from = from;
+ }
+
+ public String getTo() {
+ return to;
+ }
+
+ public void setTo(String to) {
+ this.to = to;
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/rules/flow/NodeDataType.java b/model/src/main/java/org/openremote/model/rules/flow/NodeDataType.java
new file mode 100644
index 000000000..b35bcbe71
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/rules/flow/NodeDataType.java
@@ -0,0 +1,11 @@
+package org.openremote.model.rules.flow;
+
+public enum NodeDataType {
+ NUMBER,
+ STRING,
+ BOOLEAN,
+ @Deprecated
+ TRIGGER,
+ COLOR,
+ ANY
+}
diff --git a/model/src/main/java/org/openremote/model/rules/flow/NodeInternal.java b/model/src/main/java/org/openremote/model/rules/flow/NodeInternal.java
new file mode 100644
index 000000000..a99c48d1d
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/rules/flow/NodeInternal.java
@@ -0,0 +1,49 @@
+package org.openremote.model.rules.flow;
+
+public class NodeInternal {
+ private String name;
+ private Picker picker;
+ private Object value;
+
+ public NodeInternal(String name, Picker picker, Object value) {
+ this.name = name;
+ this.picker = picker;
+ this.value = value;
+ }
+
+ public NodeInternal(String name, Picker picker) {
+ this.name = name;
+ this.picker = picker;
+ this.value = picker.getOptions().length == 0 ? null : picker.getOptions()[0].getValue();
+ }
+
+ public NodeInternal() {
+ name = null;
+ picker = new Picker();
+ value = null;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public Picker getPicker() {
+ return picker;
+ }
+
+ public void setPicker(Picker picker) {
+ this.picker = picker;
+ }
+
+ public Object getValue() {
+ return value;
+ }
+
+ public void setValue(Object value) {
+ this.value = value;
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/rules/flow/NodePosition.java b/model/src/main/java/org/openremote/model/rules/flow/NodePosition.java
new file mode 100644
index 000000000..78970618a
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/rules/flow/NodePosition.java
@@ -0,0 +1,16 @@
+package org.openremote.model.rules.flow;
+
+public class NodePosition {
+ public float x;
+ public float y;
+
+ public NodePosition(float x, float y) {
+ this.x = x;
+ this.y = y;
+ }
+
+ public NodePosition() {
+ x = 0;
+ y = 0;
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/rules/flow/NodeSocket.java b/model/src/main/java/org/openremote/model/rules/flow/NodeSocket.java
new file mode 100644
index 000000000..afe4c43ef
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/rules/flow/NodeSocket.java
@@ -0,0 +1,71 @@
+package org.openremote.model.rules.flow;
+
+public class NodeSocket {
+ // Generation of ID is the responsibility of the npm package
+ private String id;
+ private String name;
+ private NodeDataType type;
+ // Assignment of Node ID is the responsibility of the npm package
+ private String nodeId;
+ // Assignment of index is the responsibility of the npm package
+ private int index;
+
+ public NodeSocket(String name, NodeDataType type) {
+ this.id = "INVALID ID";
+ this.name = name;
+ this.type = type;
+ this.nodeId = "INVALID NODE ID";
+ this.index = 0;
+ }
+
+ public NodeSocket() {
+ id = "INVALID ID";
+ name = "Unnamed socket";
+ type = NodeDataType.ANY;
+ nodeId = "INVALID NODE ID";
+ index = -1;
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public NodeDataType getType() {
+ return type;
+ }
+
+ public void setType(NodeDataType type) {
+ this.type = type;
+ }
+
+ public String getNodeId() {
+ return nodeId;
+ }
+
+ public void setNodeId(String nodeId) {
+ this.nodeId = nodeId;
+ }
+
+ public int getIndex() {
+ return index;
+ }
+
+ public void setIndex(int index) {
+ this.index = index;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (obj instanceof NodeSocket)
+ return ((NodeSocket) obj).id.equals(id);
+ else return false;
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/rules/flow/NodeType.java b/model/src/main/java/org/openremote/model/rules/flow/NodeType.java
new file mode 100644
index 000000000..926d4a62e
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/rules/flow/NodeType.java
@@ -0,0 +1,9 @@
+package org.openremote.model.rules.flow;
+
+public enum NodeType {
+ INPUT,
+ PROCESSOR,
+ OUTPUT,
+ @Deprecated
+ THEN
+}
diff --git a/model/src/main/java/org/openremote/model/rules/flow/Option.java b/model/src/main/java/org/openremote/model/rules/flow/Option.java
new file mode 100644
index 000000000..4c91244b4
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/rules/flow/Option.java
@@ -0,0 +1,30 @@
+package org.openremote.model.rules.flow;
+
+public class Option {
+ private String name;
+ private Object value;
+
+ public Option(String name, Object value) {
+ this.name = name;
+ this.value = value;
+ }
+
+ public Option() {
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public Object getValue() {
+ return value;
+ }
+
+ public void setValue(Object value) {
+ this.value = value;
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/rules/flow/Picker.java b/model/src/main/java/org/openremote/model/rules/flow/Picker.java
new file mode 100644
index 000000000..ac916419b
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/rules/flow/Picker.java
@@ -0,0 +1,37 @@
+package org.openremote.model.rules.flow;
+
+public class Picker {
+ private PickerType type;
+ private Option[] options;
+
+ public Picker(PickerType type, Option[] options) {
+ this.type = type;
+ this.options = options;
+ }
+
+ public Picker(PickerType type) {
+ this.type = type;
+ this.options = new Option[0];
+ }
+
+ public Picker() {
+ type = PickerType.NUMBER;
+ options = new Option[]{};
+ }
+
+ public PickerType getType() {
+ return type;
+ }
+
+ public void setType(PickerType type) {
+ this.type = type;
+ }
+
+ public Option[] getOptions() {
+ return options;
+ }
+
+ public void setOptions(Option[] options) {
+ this.options = options;
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/rules/flow/PickerType.java b/model/src/main/java/org/openremote/model/rules/flow/PickerType.java
new file mode 100644
index 000000000..35db145e5
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/rules/flow/PickerType.java
@@ -0,0 +1,13 @@
+package org.openremote.model.rules.flow;
+
+public enum PickerType {
+ TEXT,
+ MULTILINE,
+ NUMBER,
+ DROPDOWN,
+ DOUBLE_DROPDOWN,
+ CHECKBOX,
+ ASSET_ATTRIBUTE,
+ COLOR
+}
+
diff --git a/test/src/test/groovy/org/openremote/test/rules/residence/FlowRulesTest.groovy b/test/src/test/groovy/org/openremote/test/rules/residence/FlowRulesTest.groovy
new file mode 100644
index 000000000..918ba650d
--- /dev/null
+++ b/test/src/test/groovy/org/openremote/test/rules/residence/FlowRulesTest.groovy
@@ -0,0 +1,81 @@
+package org.openremote.test.rules.residence
+
+import org.openremote.manager.asset.AssetProcessingService
+import org.openremote.manager.asset.AssetStorageService
+import org.openremote.manager.rules.FlowRulesBuilder
+import org.openremote.manager.rules.RulesService
+import org.openremote.manager.rules.RulesetStorageService
+import org.openremote.manager.setup.SetupService
+import org.openremote.manager.setup.builtin.ManagerDemoSetup
+import org.openremote.model.attribute.AttributeEvent
+import org.openremote.model.rules.GlobalRuleset
+import org.openremote.model.rules.Ruleset
+import org.openremote.model.rules.flow.NodeCollection
+import org.openremote.model.value.Values
+import org.openremote.test.ManagerContainerTrait
+import spock.lang.Specification
+import spock.util.concurrent.PollingConditions
+
+import static org.openremote.model.rules.RulesetStatus.DEPLOYED
+
+class FlowRulesTest extends Specification implements ManagerContainerTrait {
+ private FlowRulesBuilder builder;
+
+ def "Execute flow rules"() {
+ given: "expected conditions"
+ def conditions = new PollingConditions(timeout: 15)
+
+ and: "the container is started"
+ def serverPort = findEphemeralPort()
+ def container = startContainer(defaultConfig(serverPort), defaultServices())
+ def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)
+ def rulesService = container.getService(RulesService.class)
+ def rulesetStorageService = container.getService(RulesetStorageService.class)
+ def assetStorageService = container.getService(AssetStorageService.class)
+ def assetProcessingService = container.getService(AssetProcessingService.class)
+ def startTemperature = 25;
+
+ and: "relevant attributes have been populated"
+ assetProcessingService.sendAttributeEvent(new AttributeEvent(
+ managerDemoSetup.apartment1LivingroomId,
+ "targetTemperature",
+ Values.create(startTemperature)
+ ))
+ assetProcessingService.sendAttributeEvent(new AttributeEvent(
+ managerDemoSetup.apartment1Bedroom1Id,
+ "targetTemperature",
+ Values.create(0)
+ ))
+
+ when: "a valid node collection is added"
+ String json = getClass().getResource("/org/openremote/test/rules/BasicFlowRules.json").text
+ json = json.replaceAll("%LIVING ROOM ID%", managerDemoSetup.apartment1LivingroomId)
+ json = json.replaceAll("%BEDROOM ID%", managerDemoSetup.apartment1Bedroom1Id)
+ println(json);
+ NodeCollection realCollection = container.JSON.readValue(json, NodeCollection.class)
+ def ruleset = (new GlobalRuleset(
+ realCollection.name,
+ Ruleset.Lang.FLOW,
+ json
+ ))
+ rulesetStorageService.merge(ruleset)
+ then: "the flow should be deployed"
+ conditions.eventually {
+ assert rulesService.globalEngine != null
+ assert rulesService.globalEngine.isRunning()
+ assert rulesService.globalEngine.deployments.values().any({ it.name == realCollection.name && it.status == DEPLOYED})
+ }
+
+ println(assetStorageService.
+ find(managerDemoSetup.apartment1Bedroom1Id).getAttribute("targetTemperature").get().getValue().present);
+
+ and: "the flow should be executed correctly"
+ conditions.eventually {
+ def bedroomTargetTemp = assetStorageService.
+ find(managerDemoSetup.apartment1Bedroom1Id).
+ getAttribute("targetTemperature").get().getValueAsNumber().get()
+ println(bedroomTargetTemp)
+ assert bedroomTargetTemp.intValue() == (startTemperature.intValue() + 10) : ("it was actually " + bedroomTargetTemp.intValue())//convert to int considering floating point inaccuracy
+ }
+ }
+}
diff --git a/test/src/test/resources/org/openremote/test/rules/BasicFlowRules.json b/test/src/test/resources/org/openremote/test/rules/BasicFlowRules.json
new file mode 100644
index 000000000..7b45fb3f8
--- /dev/null
+++ b/test/src/test/resources/org/openremote/test/rules/BasicFlowRules.json
@@ -0,0 +1,156 @@
+{
+ "name": "rule for testing",
+ "description": "",
+ "connections": [
+ {
+ "from": "N0CBrPgIs",
+ "to": "dT7rFX3V_"
+ },
+ {
+ "from": "B3magR7AC",
+ "to": "UwzPymiwW"
+ },
+ {
+ "from": "nUEm7wYYX",
+ "to": "e1hlx5398"
+ }
+ ],
+ "nodes": [
+ {
+ "inputs": [],
+ "internals": [
+ {
+ "name": "Attribute",
+ "picker": {
+ "type": "ASSET_ATTRIBUTE"
+ },
+ "value": {
+ "assetId": "%LIVING ROOM ID%",
+ "attributeName": "targetTemperature"
+ }
+ }
+ ],
+ "name": "READ_ATTRIBUTE",
+ "outputs": [
+ {
+ "name": "value",
+ "type": "NUMBER",
+ "nodeId": "rNVAoZc1",
+ "id": "N0CBrPgIs"
+ }
+ ],
+ "type": "INPUT",
+ "position": {
+ "x": -655.6875,
+ "y": -261.5
+ },
+ "size": {
+ "x": 225,
+ "y": 65
+ },
+ "id": "rNVAoZc1"
+ },
+ {
+ "inputs": [
+ {
+ "name": "a",
+ "type": "NUMBER",
+ "nodeId": "kZpTRGu9",
+ "id": "dT7rFX3V_"
+ },
+ {
+ "name": "b",
+ "type": "NUMBER",
+ "nodeId": "kZpTRGu9",
+ "id": "UwzPymiwW"
+ }
+ ],
+ "internals": [],
+ "name": "ADD_OPERATOR",
+ "displayCharacter": "+",
+ "outputs": [
+ {
+ "name": "c",
+ "type": "NUMBER",
+ "nodeId": "kZpTRGu9",
+ "id": "nUEm7wYYX"
+ }
+ ],
+ "type": "PROCESSOR",
+ "position": {
+ "x": -250.49999999999994,
+ "y": -149.27777777777777
+ },
+ "size": {
+ "x": 0,
+ "y": 0
+ },
+ "id": "kZpTRGu9"
+ },
+ {
+ "inputs": [],
+ "internals": [
+ {
+ "name": "value",
+ "picker": {
+ "type": "NUMBER"
+ },
+ "value": 10
+ }
+ ],
+ "name": "NUMBER_INPUT",
+ "outputs": [
+ {
+ "name": "value",
+ "type": "NUMBER",
+ "nodeId": "0UO-OCth",
+ "id": "B3magR7AC"
+ }
+ ],
+ "type": "INPUT",
+ "position": {
+ "x": -580.6102430555555,
+ "y": -100.38888888888886
+ },
+ "size": {
+ "x": 148,
+ "y": 17
+ },
+ "id": "0UO-OCth"
+ },
+ {
+ "inputs": [
+ {
+ "name": "value",
+ "type": "NUMBER",
+ "nodeId": "D35ZQrzd",
+ "id": "e1hlx5398"
+ }
+ ],
+ "internals": [
+ {
+ "name": "Attribute",
+ "picker": {
+ "type": "ASSET_ATTRIBUTE"
+ },
+ "value": {
+ "assetId": "%BEDROOM ID%",
+ "attributeName": "targetTemperature"
+ }
+ }
+ ],
+ "name": "WRITE_ATTRIBUTE",
+ "outputs": [],
+ "type": "OUTPUT",
+ "position": {
+ "x": -111.5208333333333,
+ "y": -192.44444444444434
+ },
+ "size": {
+ "x": 143,
+ "y": 65
+ },
+ "id": "D35ZQrzd"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/ui/component/or-rules/package.json b/ui/component/or-rules/package.json
index 21e9f1f69..ff3a7a3cd 100644
--- a/ui/component/or-rules/package.json
+++ b/ui/component/or-rules/package.json
@@ -25,12 +25,16 @@
"@openremote/or-asset-viewer": "^1.1.0",
"ace-builds": "^1.4.7",
"lit-element": "^2.2.1",
+ "linqts": "^1.12.6",
+ "resize-observer": "^1.0.0",
+ "shortid": "^2.2.15",
"moment": "^2.24.0"
},
"devDependencies": {
"tslint": ">=5.11.0",
"typescript": ">=3.4.5",
"webpack": "^4.41.2",
- "webpack-cli": "^3.3.9"
+ "webpack-cli": "^3.3.9",
+ "@types/shortid": "^0.0.29"
}
}
diff --git a/ui/component/or-rules/src/flow-viewer/components/confirmation-dialog.ts b/ui/component/or-rules/src/flow-viewer/components/confirmation-dialog.ts
new file mode 100644
index 000000000..810a3bfee
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/components/confirmation-dialog.ts
@@ -0,0 +1,40 @@
+import { LitElement, html, customElement, css, property } from "lit-element";
+import { i18next, translate } from "@openremote/or-translate";
+
+@customElement("confirmation-dialog")
+export class ConfirmationDialog extends translate(i18next)(LitElement) {
+ @property({ type: String }) public agreeText = i18next.t("ok");
+ @property({ type: String }) public disagreeText = i18next.t("cancel");
+ @property({ type: String }) public question = i18next.t("areYouSure", "Are you sure?");
+
+ public static get styles() {
+ return css`
+ .question{
+ width: 100%;
+ padding: 15px 5px 25px 5px;
+ text-align: center;
+ }
+ .container{
+ display: flex;
+ flex-direction: row;
+ justify-content: space-between;
+ justify-content: space-evenly;
+ justify-content: space-around;
+ }`;
+ }
+
+ protected render() {
+ return html`
+ <div class="question">${this.question}</div>
+ <div class="container">
+ <or-input type="button" unElevated label="${this.agreeText}"
+ @click="${() => { this.dispatchEvent(new CustomEvent("agreed")); }}">
+ </or-input>
+
+ <or-input type="button" label="${this.disagreeText}"
+ @click="${() => { this.dispatchEvent(new CustomEvent("disagreed")); }}">
+ </or-input>
+ </div>
+ `;
+ }
+}
diff --git a/ui/component/or-rules/src/flow-viewer/components/connection-container.ts b/ui/component/or-rules/src/flow-viewer/components/connection-container.ts
new file mode 100644
index 000000000..769454eab
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/components/connection-container.ts
@@ -0,0 +1,26 @@
+import { LitElement, html, customElement, property } from "lit-element";
+import { repeat } from "lit-html/directives/repeat";
+import { EditorWorkspace } from "./editor-workspace";
+import { project } from "./flow-editor";
+
+@customElement("connection-container")
+export class ConnectionContainer extends LitElement {
+ @property({ attribute: false }) private workspace!: EditorWorkspace;
+
+ constructor() {
+ super();
+ project.addListener("connectioncreated", () => {
+ this.requestUpdate();
+ });
+ project.addListener("connectionremoved", () => {
+ this.requestUpdate();
+ });
+ project.addListener("cleared", () => {
+ this.requestUpdate();
+ });
+ }
+
+ protected render() {
+ return html`${repeat(project.connections, (c) => c.from! + c.to!, (c) => html`<connection-line .workspace="${this.workspace}" .connection="${c}"></connection-line>`)}`;
+ }
+}
diff --git a/ui/component/or-rules/src/flow-viewer/components/connection-line.ts b/ui/component/or-rules/src/flow-viewer/components/connection-line.ts
new file mode 100644
index 000000000..8a8918285
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/components/connection-line.ts
@@ -0,0 +1,127 @@
+import { html, customElement, css, property } from "lit-element";
+import { NodeConnection } from "@openremote/model";
+import { IdentityDomLink, IdentityAssigner, NodeUtilities } from "../node-structure";
+import { FlowNodeSocket } from "./flow-node-socket";
+import { ResizeObserver } from "resize-observer";
+import { SelectableElement } from "./selectable-element";
+import { EditorWorkspace } from "./editor-workspace";
+import { FlowNode } from "./flow-node";
+import { project } from "./flow-editor";
+
+@customElement("connection-line")
+export class ConnectionLine extends SelectableElement {
+ @property({ attribute: false }) public connection!: NodeConnection;
+ @property({ attribute: false }) public workspace!: EditorWorkspace;
+
+ @property({ type: String }) private polylineId: string;
+
+ private fromNodeElement!: FlowNode;
+ private toNodeElement!: FlowNode;
+
+ private fromElement!: FlowNodeSocket;
+ private toElement!: FlowNodeSocket;
+ private resizeObserver!: ResizeObserver;
+ private readonly fancyLine = true;
+ private readonly curveIntensity = 1;
+
+ constructor() {
+ super();
+ this.polylineId = IdentityAssigner.generateIdentity();
+ }
+
+ public disconnectedCallback() {
+ super.disconnectedCallback();
+ this.resizeObserver.disconnect();
+ project.removeListener("connectionremoved", this.nodeChanged);
+ }
+
+ protected firstUpdated() {
+ super.firstUpdated();
+ this.setHandle(this.shadowRoot!.getElementById(this.polylineId)!);
+ }
+
+ protected render() {
+ if (this.isInvalid) {
+ const fromSocket = NodeUtilities.getSocketFromID(this.connection.from!, project.nodes);
+ const toSocket = NodeUtilities.getSocketFromID(this.connection.to!, project.nodes);
+ this.fromNodeElement = IdentityDomLink.map[fromSocket!.nodeId!];
+ this.toNodeElement = IdentityDomLink.map[toSocket!.nodeId!];
+ this.fromElement = IdentityDomLink.map[fromSocket!.id!];
+ this.toElement = IdentityDomLink.map[toSocket!.id!];
+ if (this.isInvalid) {
+ console.warn(this.fromNodeElement);
+ console.warn(this.toNodeElement);
+ console.warn(this.fromElement);
+ console.warn(this.toElement);
+
+ console.warn("Attempt to render invalid connection");
+ return html``;
+ } else {
+ this.fromNodeElement.addEventListener("updated", this.nodeChanged);
+ this.toNodeElement.addEventListener("updated", this.nodeChanged);
+ this.resizeObserver = new ResizeObserver(this.nodeChanged);
+ this.resizeObserver.observe(this.fromNodeElement);
+ this.resizeObserver.observe(this.toNodeElement);
+ }
+ }
+
+ const parentSize = this.workspace.clientRect;
+ const from = this.fromElement.connectionPosition;
+ const to = this.toElement.connectionPosition;
+
+ if (this.fancyLine) {
+
+ const x1 = from.x - parentSize.left;
+ const y1 = from.y - parentSize.top;
+
+ const x2 = to.x - parentSize.left;
+ const y2 = to.y - parentSize.top;
+
+ const intensity = this.curveIntensity * (Math.abs(x1 - x2) / 2);
+ // const intensity = 100 * this.workspace.camera.zoom;
+
+ return html`<svg style="stroke-width: ${this.workspace.camera.zoom * (this.selected ? 5 : 3)}px;">
+ <path id="${this.polylineId}"
+ d="M ${x1} ${y1} C ${x1 + intensity} ${y1}, ${x2 - intensity} ${y2}, ${x2} ${y2}"
+ selected="${this.selected}"
+ />
+ </svg>`;
+ }
+
+ return html`<svg style="stroke-width: ${this.workspace.camera.zoom * (this.selected ? 5 : 3)}px;"><polyline id="${this.polylineId}"
+ selected="${this.selected}"
+ points="
+ ${from.x - parentSize.left}, ${from.y - parentSize.top}
+ ${to.x - parentSize.left}, ${to.y - parentSize.top}"
+ ></polyline>
+ </svg>`;
+ }
+
+ public static get styles() {
+ return css`
+ svg{
+ fill: none;
+ overflow: visible;
+ position: absolute;
+ pointer-events: none;
+ stroke-linejoin: round;
+ }
+ path, line{
+ position: absolute;
+ pointer-events: all;
+ }
+ path:hover, line:hover, path[selected = true], line[selected = true]{
+ stroke: var(--highlight);
+ }
+ text{
+ fill: red;
+ stroke: none;
+ }`;
+ }
+
+ private nodeChanged = () => { this.requestUpdate(); };
+
+ private get isInvalid() {
+ return (!this.fromNodeElement || !this.toNodeElement || !this.fromElement || !this.toElement);
+ }
+}
diff --git a/ui/component/or-rules/src/flow-viewer/components/context-menu.ts b/ui/component/or-rules/src/flow-viewer/components/context-menu.ts
new file mode 100644
index 000000000..b047628f8
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/components/context-menu.ts
@@ -0,0 +1,141 @@
+import { LitElement, property, customElement, html, css } from "lit-element";
+import { ContextMenuEntry, ContextMenuButton } from "../models/context-menu-button";
+import { translate, i18next } from "@openremote/or-translate";
+
+@customElement("context-menu")
+export class ContextMenu extends translate(i18next)(LitElement) {
+ public static get opened() { return ContextMenu.main.isOpen; }
+
+ public static get styles() {
+ return css`
+ :host{
+ display: inline-block;
+ position: fixed;
+ background: white;
+ outline: 1px solid rgb(200,200,200);
+ box-shadow: rgba(0, 0, 0, 0.05) 0 2px 4px;
+ font-size: 13px;
+ z-index: 1000000;
+ }
+ .context-menu-button{
+ color: rgb(0,0,0);
+ display: grid;
+ align-items: center;
+ justify-items: start;
+ grid-template-rows: 32px;
+ grid-template-columns: 32px 220px;
+ grid-template-areas:
+ "icon label";
+ }
+ .context-menu-button:hover{
+ background: whitesmoke;
+ }
+ .label
+ {
+ grid-area: label;
+ }
+ or-icon{
+ justify-self: center;
+ grid-area: icon;
+ height: 16px;
+ width: 16px;
+ }
+ .muted{
+ pointer-events: none;
+ color: rgb(150,150,150);
+ }
+ .context-menu-separator{
+ --thickness: 1px;
+ border: 0;
+ height: var(--thickness);
+ border-bottom: solid var(--thickness);
+ border-color: rgb(234,234,234);
+ padding: 0;
+ margin: 5px 10px calc(5px - var(--thickness)) 10px;
+ }`;
+ }
+
+ public static open(x: number, y: number, container: Element, buttons: (ContextMenuEntry)[]) {
+ ContextMenu.main.container = container;
+ ContextMenu.main.style.top = y + "px";
+ ContextMenu.main.style.left = x + "px";
+ window.addEventListener("mousedown", ContextMenu.main.closeCallback);
+ window.addEventListener("blur", ContextMenu.main.closeCallback);
+ window.addEventListener("wheel", ContextMenu.main.closeCallback);
+ ContextMenu.main.entries = buttons;
+ ContextMenu.main.isOpen = true;
+ }
+
+ public static close() {
+ window.removeEventListener("mousedown", ContextMenu.main.closeCallback);
+ window.removeEventListener("blur", ContextMenu.main.closeCallback);
+ window.removeEventListener("wheel", ContextMenu.main.closeCallback);
+ ContextMenu.main.isOpen = false;
+ }
+
+ private static main: ContextMenu;
+ private entries: ContextMenuEntry[] = [];
+
+ @property({ attribute: false }) private isOpen = false;
+
+ private container!: Element;
+
+ protected firstUpdated() {
+ ContextMenu.main = this;
+ }
+
+ protected updated() {
+ if (!this.container) { return; }
+ const bounds = this.container.getBoundingClientRect();
+ const box = this.getBoundingClientRect();
+ if (box.top + box.height > bounds.bottom) {
+ this.style.top = box.top - box.height + "px";
+ }
+
+ if (box.left + box.width > bounds.right) {
+ this.style.left = bounds.right - box.width + "px";
+ }
+ }
+
+ protected render() {
+ this.style.display = this.isOpen ? "unset" : "none";
+ if (!this.isOpen) {
+ return html``;
+ }
+ const elements = this.entries.map(
+ (e) => {
+ switch (e.type) {
+ case "button":
+ return this.buttonTemplate(e as ContextMenuButton);
+ case "separator":
+ return this.separatorTemplate();
+ }
+ }
+ );
+ return html`${elements.length > 0 ? elements : html`<div class="context-menu-button muted">...</div>`}`;
+ }
+
+ private closeCallback = () => {
+ ContextMenu.close();
+ }
+
+ private buttonTemplate(button: ContextMenuButton) {
+ const action = (e: MouseEvent) => {
+ if (e.buttons !== 1) { return; }
+ ContextMenu.close();
+ if (button.action) {
+ button.action();
+ }
+ e.stopImmediatePropagation();
+ e.stopPropagation();
+ };
+ return html`
+ <div class="context-menu-button ${(button.disabled || false) ? `muted` : ``}" @mousedown="${action}">
+ ${button.icon ? html`<or-icon icon="${button.icon}"></or-icon>` : null}
+ <span class="label">${button.label}</span></div>`;
+ }
+
+ private separatorTemplate() {
+ return html`<div class="context-menu-separator"></div>`;
+ }
+}
diff --git a/ui/component/or-rules/src/flow-viewer/components/editor-workspace.ts b/ui/component/or-rules/src/flow-viewer/components/editor-workspace.ts
new file mode 100644
index 000000000..69ecefe32
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/components/editor-workspace.ts
@@ -0,0 +1,265 @@
+import { LitElement, html, customElement, property } from "lit-element";
+import { repeat } from "lit-html/directives/repeat";
+import { Node, NodeSocket, NodeType } from "@openremote/model";
+import { IdentityDomLink, CopyMachine } from "../node-structure";
+import { List } from "linqts";
+import { FlowNodeSocket } from "./flow-node-socket";
+import { LightNodeCollection } from "../models/light-node-collection";
+import { EditorWorkspaceStyle } from "../styles/editor-workspace-style";
+import { i18next, translate } from "@openremote/or-translate";
+import { FlowNode } from "./flow-node";
+import { ConnectionLine } from "./connection-line";
+import { ContextMenuButton, ContextMenuSeparator } from "../models/context-menu-button";
+import { ContextMenu } from "./context-menu";
+import { project, input, copyPasteManager, integration, FlowEditor } from "./flow-editor";
+import { Camera } from "../models/camera";
+import { Utilities } from "../utils";
+import { createContextMenuButtons } from "./workspace-contextmenu-options";
+
+@customElement("editor-workspace")
+export class EditorWorkspace extends translate(i18next)(LitElement) {
+ public get clientRect() {
+ return this.cachedClientRect;
+ }
+
+ static get styles() {
+ return EditorWorkspaceStyle;
+ }
+
+ public get halfSize() {
+ const box = this.cachedClientRect;
+ return { x: box.width / 2, y: box.height / 2 };
+ }
+
+ private get isCameraInDefaultPosition() {
+ const errorMargin = 0.05;
+ return (Math.abs(this.camera.x) < errorMargin && Math.abs(this.camera.y) < errorMargin && this.camera.zoom > (1 - errorMargin) && this.camera.zoom < (1 + errorMargin));
+ }
+ @property({ attribute: false }) public camera: Camera = { x: 0, y: 0, zoom: 1 };
+
+ @property({ attribute: false }) public topNodeZindex = 1;
+ @property({ attribute: false }) public scrollSensitivity = 1.25;
+ @property({ attribute: false }) public zoomLowerBound = .2;
+ @property({ attribute: false }) public zoomUpperBound = 10;
+
+ @property({ attribute: false }) public application!: FlowEditor;
+
+ @property({ attribute: false }) private connectionDragging = false;
+ @property({ attribute: false }) private connectionFrom: { x: number, y: number } = { x: 0, y: 0 };
+ @property({ attribute: false }) private connectionTo: { x: number, y: number } = { x: 0, y: 0 };
+
+ private isPanning = false;
+ private cachedClientRect!: ClientRect;
+
+ constructor() {
+ super();
+ project.addListener("nodeadded", (n: Node) => { this.requestUpdate(); });
+ project.addListener("noderemoved", (n: Node) => { this.requestUpdate(); });
+ project.addListener("cleared", () => { this.requestUpdate(); });
+
+ project.addListener("connectionstart", (e: MouseEvent, s: NodeSocket) => {
+ if (e.buttons !== 1) { return; }
+ const pos = (IdentityDomLink.map[s.id!] as FlowNodeSocket).connectionPosition;
+ this.connectionFrom = this.pageToOffset(pos);
+ this.addEventListener("mousemove", project.connectionDragging);
+ this.addEventListener("mouseup", this.onEmptyConnectionRelease);
+ });
+
+ project.addListener("connecting", (e: MouseEvent) => {
+ this.connectionTo = { x: e.pageX - this.clientRect.left, y: e.pageY - this.clientRect.top };
+ this.connectionDragging = true;
+ });
+
+ project.addListener("connectionend", () => {
+ this.connectionDragging = false;
+ this.removeEventListener("mousemove", project.connectionDragging);
+ });
+
+ window.addEventListener("resize", () => {
+ this.cachedClientRect = this.getBoundingClientRect();
+ this.dispatchEvent(new CustomEvent("pan"));
+ });
+
+ this.addEventListener("mousedown", (e) => {
+ this.startPan(e);
+ if (e.buttons === 1) {
+ input.clearSelection();
+ }
+ });
+
+ this.addEventListener("contextmenu", (e) => {
+ const buttons = createContextMenuButtons(this, e);
+ ContextMenu.open(e.pageX, e.pageY, this, buttons);
+ e.preventDefault();
+ });
+ project.workspace = this;
+ this.addEventListener("wheel", this.onZoom, { passive: true });
+ }
+
+ public resetCamera() {
+ this.camera = { x: 0, y: 0, zoom: 1 };
+ this.dispatchEvent(new CustomEvent("pan"));
+ this.dispatchEvent(new CustomEvent("zoom"));
+ }
+
+ public fitCamera(nodes: Node[], padding = 25) {
+ const enumerable = new List<Node>();
+ enumerable.AddRange(nodes);
+ const XouterleastNode = enumerable.OrderBy((a: Node) => a!.position!.x!).First() as Node;
+ const YouterleastNode = enumerable.OrderBy((a: Node) => a!.position!.y!).First() as Node;
+
+ const XoutermostNode = enumerable.OrderByDescending((a: Node) => a!.position!.x! + (IdentityDomLink.map[a.id!] as FlowNode).scrollWidth).First() as Node;
+ const YoutermostNode = enumerable.OrderByDescending((a: Node) => a!.position!.y! + (IdentityDomLink.map[a.id!] as FlowNode).scrollHeight).First() as Node;
+
+ const XoutermostWidth = (IdentityDomLink.map[XoutermostNode.id!] as FlowNode).scrollWidth;
+ const YoutermostHeight = (IdentityDomLink.map[YoutermostNode.id!] as FlowNode).scrollHeight;
+
+ const fitBounds = {
+ left: XouterleastNode!.position!.x! - padding,
+ right: XoutermostNode!.position!.x! + padding + XoutermostWidth,
+ top: YoutermostNode!.position!.y! + padding + YoutermostHeight,
+ bottom: YouterleastNode!.position!.y! - padding,
+ };
+ const fitWidth = fitBounds.right - fitBounds.left;
+ const fitHeight = fitBounds.top - fitBounds.bottom;
+
+ const totalBounds = this.clientRect;
+ const center = {
+ x: (fitBounds.left + fitBounds.right) / 2.0,
+ y: (fitBounds.top + fitBounds.bottom) / 2.0
+ };
+ const targetZoom = Math.min(
+ totalBounds.width / fitWidth,
+ totalBounds.height / fitHeight
+ );
+
+ this.camera = {
+ x: -center.x,
+ y: -center.y,
+ zoom: Math.min(Math.max(this.zoomLowerBound, targetZoom), this.zoomUpperBound)
+ };
+ this.dispatchEvent(new CustomEvent("pan"));
+ this.dispatchEvent(new CustomEvent("zoom"));
+ }
+
+ public offsetToWorld(point: { x?: number, y?: number }) {
+ const halfSize = this.halfSize;
+ return {
+ x: (point.x! - halfSize.x) / this.camera.zoom - this.camera.x,
+ y: (point.y! - halfSize.y) / this.camera.zoom - this.camera.y
+ };
+ }
+
+ public worldToOffset(point: { x?: number, y?: number }) {
+ const halfSize = this.halfSize;
+ return {
+ x: (point.x! + this.camera.x) * this.camera.zoom + halfSize.x,
+ y: (point.y! + this.camera.y) * this.camera.zoom + halfSize.y
+ };
+ }
+
+ public pageToOffset(point: { x?: number, y?: number }) {
+ const box = this.clientRect;
+ return {
+ x: point.x! - box.left!,
+ y: point.y! - box.top!
+ };
+ }
+
+ public async pasteAt(x: number, y: number) {
+ const clone: LightNodeCollection = copyPasteManager.getFromClipboard({ x, y });
+ clone.nodes.forEach((n) => {
+ project.addNode(n);
+ });
+ await this.updateComplete;
+ clone.connections.forEach((c) => {
+ project.createConnection(c.from!, c.to!);
+ });
+ }
+
+ protected firstUpdated() {
+ this.cachedClientRect = this.getBoundingClientRect();
+ if (this.application.nodePanel.drawer) {
+ this.application.nodePanel.drawer.addEventListener("or-mwc-drawer-changed", async (e: any) => {
+ this.style.width = e.detail ? "calc(100% - 255px)" : "";
+ await this.updateComplete;
+ this.cachedClientRect = this.getBoundingClientRect();
+ this.dispatchEvent(new CustomEvent("pan"));
+ });
+ }
+ }
+
+ protected render() {
+ return html`
+ ${repeat(
+ project.nodes,
+ (i) => i.id,
+ (n) => html`<flow-node .node="${n}" .workspace="${this}"></flow-node>`)}
+ <connection-container .workspace="${this}"></connection-container>
+ <svg>
+ <line style="display:
+ ${this.connectionDragging ? null : `none`};
+ stroke-dasharray: ${20 * this.camera.zoom}, ${10 * this.camera.zoom};
+ stroke-opacity: 0.25; stroke-width: ${this.camera.zoom * 4}px"
+
+ x1="${this.connectionFrom.x}"
+ y1="${this.connectionFrom.y}"
+ x2="${this.connectionTo.x}"
+ y2="${this.connectionTo.y}"></line>
+ </svg>
+ <selection-box .workspace="${this}"></selection-box>
+ <div class="view-options" style="z-index: ${this.topNodeZindex + 1}">
+ ${!this.isCameraInDefaultPosition ? html`<or-input type="button" icon="vector-square" @click="${this.resetCamera}" label="${i18next.t("resetView", "Reset view")!}"></or-input>` : null}
+ ${project.nodes.length !== 0 ? html`<or-input type="button" icon="fit-to-page-outline" @click="${() => this.fitCamera(project.nodes)}" label="${i18next.t("fitView", "Fit view")!}"></or-input>` : null}
+ </div>
+ `;
+ }
+
+ private startPan(event: MouseEvent) {
+ if (this.connectionDragging) { return false; }
+ if (event.buttons !== 4) { return false; }
+ this.isPanning = true;
+ window.addEventListener("mousemove", this.onMove);
+ window.addEventListener("mouseup", this.stopPan);
+ event.preventDefault();
+ }
+
+ private onMove = (event: MouseEvent) => {
+ const documentZoom = window.devicePixelRatio;
+ this.camera = {
+ x: this.camera.x + event.movementX / this.camera.zoom / documentZoom,
+ y: this.camera.y + event.movementY / this.camera.zoom / documentZoom,
+ zoom: this.camera.zoom
+ };
+
+ this.dispatchEvent(new CustomEvent("pan"));
+ }
+
+ private onZoom = (event: WheelEvent) => {
+ if (this.connectionDragging) { return; }
+ if (this.isPanning) { return; }
+ const magnification = 0.9 * this.scrollSensitivity;
+ const rz = event.deltaY < 0 ? this.camera.zoom * magnification : this.camera.zoom / magnification;
+ if (rz < this.zoomLowerBound || rz > this.zoomUpperBound) { return; }
+
+ this.camera = {
+ x: this.camera.x,
+ y: this.camera.y,
+ zoom: rz
+ };
+
+ this.dispatchEvent(new CustomEvent("zoom"));
+ }
+
+ private onEmptyConnectionRelease = (ee: MouseEvent) => {
+ if (project.isCurrentlyConnecting) {
+ project.endConnectionDrag(ee, null, false);
+ }
+ }
+
+ private stopPan = () => {
+ if (!this.isPanning) { return; }
+ window.removeEventListener("mousemove", this.onMove);
+ this.isPanning = false;
+ }
+}
diff --git a/ui/component/or-rules/src/flow-viewer/components/flow-editor.ts b/ui/component/or-rules/src/flow-viewer/components/flow-editor.ts
new file mode 100644
index 000000000..5114f11ba
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/components/flow-editor.ts
@@ -0,0 +1,134 @@
+import { LitElement, html, customElement, css, query, property } from "lit-element";
+import { Integration } from "../services/integration";
+import { CopyPasteManager } from "../services/copy-paste-manager";
+import { Project } from "../services/project";
+import { Input } from "../services/input";
+import { ModalService } from "../services/modal";
+import { Exporter } from "../services/exporter";
+import { Shortcuts } from "../services/shortcuts";
+import { NodePanel } from "./node-panel";
+import { EditorWorkspace } from "./editor-workspace";
+import { TopBar } from "./top-bar";
+import { RuleView, OrRulesRuleChangedEvent } from "../..";
+import { RulesetUnion } from "@openremote/model";
+import { translate, i18next } from "@openremote/or-translate";
+import { NodeUtilities } from "../node-structure";
+
+export const integration = new Integration();
+export const copyPasteManager = new CopyPasteManager();
+export const project = new Project();
+export const input = new Input();
+export const modal = new ModalService();
+export const exporter = new Exporter();
+export const shortcuts = new Shortcuts();
+export const newIds: Set<string> = new Set<string>();
+
+@customElement("flow-editor")
+export class FlowEditor extends translate(i18next)(LitElement) implements RuleView {
+ @query("node-panel") public nodePanel!: NodePanel;
+ @query("top-bar") public topBar!: TopBar;
+ @query("editor-workspace") public editorWorkspace!: EditorWorkspace;
+ @property({ type: Boolean }) public showTopbar = false;
+
+ @property({ attribute: false })
+ public readonly?: boolean | undefined;
+ @property({ attribute: false })
+ protected _ruleset!: RulesetUnion;
+
+ constructor() {
+ super();
+ }
+
+ public validate() {
+ return NodeUtilities.validate(exporter.jsonToFlow(this._ruleset.rules || "{}"));
+ }
+
+ public beforeSave() {
+ if (this.readonly) { return; }
+ this.serialiseRule();
+ }
+
+ public set ruleset(ruleset: RulesetUnion) {
+ if (this._ruleset === ruleset) { return; }
+ this._ruleset = ruleset;
+ if (ruleset.rules) {
+ const collection = exporter.jsonToFlow(ruleset.rules!);
+ project.fromNodeCollection(collection);
+ project.setCurrentProject(ruleset.id!, ruleset.name!, collection.description!);
+ } else {
+ project.clear(true);
+ }
+ }
+
+ public static get styles() {
+ return [
+ css`
+ :host{
+ user-select: none;
+ display: grid;
+ grid-template-columns: 1fr auto;
+ grid-template-rows: 100%;
+ grid-template-areas:
+ "workspace node-panel";
+
+ width: 100%;
+ height: 100%;
+
+ --or-app-color4: rgb(76,76,76);
+
+ --socket-size: 24px;
+ --socket-display-size: 14px;
+
+ --topbar-height: 50px;
+ --nodepanel-width: 195px;
+ --roundness: 3px;
+
+ --highlight-faded: hsla(102, 100%, 31%, 0.2);
+ --highlight: hsla(102, 100%, 31%, 0.5);
+ --highlight-opaque: hsla(102, 100%, 31%);
+
+ --any: rgb(162, 0, 255);
+ --number: rgb(165, 228, 50);
+ --boolean: rgb(0, 102, 255);
+ --string: rgb(45, 180, 221);
+ --color: rgb(255, 228, 78);
+
+ --input-color: hsl(222, 60%, 46%);
+ --processor-color: hsl(102, 58%, 39%);
+ --output-color: hsl(282, 60%, 47%);
+
+ --input-color-h: hsl(222, 58%, 54%);
+ --processor-color-h: hsl(102, 48%, 49%);
+ --output-color-h: hsl(282, 58%, 54%);
+ }`];
+ }
+
+ protected async firstUpdated() {
+ await integration.refreshNodes();
+ this.requestUpdate();
+ await this.updateComplete;
+ project.addListener("changed", () => {
+ this.serialiseRule();
+ this.dispatchEvent(new OrRulesRuleChangedEvent(this.validate()));
+ });
+ }
+
+ protected render() {
+ if (this.showTopbar) {
+ this.style.gridTemplateRows = "var(--topbar-height) 1fr";
+ this.style.gridTemplateAreas = '"topbar topbar" "workspace node-panel";';
+ }
+
+ return html`
+ ${(this.showTopbar ? html`<top-bar .application="${this}" style="grid-area: topbar"></top-bar>` : ``)}
+ <node-panel .application="${this}" style="grid-area: node-panel" .nodes= "${integration.nodes}"></node-panel>
+ <editor-workspace .application="${this}" id="workspace" style="grid-area: workspace"></editor-workspace>
+ <context-menu></context-menu>
+ <popup-modal id="popup-modal"></popup-modal>
+ `;
+ }
+
+ private serialiseRule() {
+ this._ruleset.rules = exporter.flowToJson(project.toNodeCollection(this._ruleset.name!, project.existingFlowRuleDesc!));
+ }
+}
diff --git a/ui/component/or-rules/src/flow-viewer/components/flow-node-socket.ts b/ui/component/or-rules/src/flow-viewer/components/flow-node-socket.ts
new file mode 100644
index 000000000..44a8f871e
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/components/flow-node-socket.ts
@@ -0,0 +1,136 @@
+import { LitElement, customElement, property, html, css, query } from "lit-element";
+import { NodeSocket } from "@openremote/model";
+import { IdentityDomLink } from "../node-structure";
+import { Utilities } from "../utils";
+import { i18next, translate } from "@openremote/or-translate";
+import { project } from "./flow-editor";
+import { FlowNode } from "./flow-node";
+
+@customElement("flow-node-socket")
+export class FlowNodeSocket extends translate(i18next)(LitElement) {
+
+ public get connectionPosition() {
+ return Utilities.getCenter(this.circleElem.getBoundingClientRect());
+ }
+
+ public static get styles() {
+ return css`
+ :host{
+ width: auto;
+ height: var(--socket-size);
+ margin: 2px;
+ display: inline-block;
+ }
+ .socket{
+ background: none;
+ height: var(--socket-size);
+ width: var(--socket-size);
+ border-radius: 100%;
+ display: inline-flex;
+ justify-content: center;
+ align-items: center;
+ }
+ .socket:hover{
+ background: var(--highlight);
+ }
+ .label{
+ display:inline-block;
+ vertical-align: top;
+ color: rgba(0,0,0,.5);
+ text-transform: lowercase;
+ }
+ .circle{
+ box-sizing: border-box;
+ background: grey;
+ width: var(--socket-display-size);
+ height: var(--socket-display-size);
+ border-radius: 100%;
+ pointer-events: none;
+ border: 1px solid rgb(80,80,80);
+ }`;
+ }
+
+ public get socketTypeString() {
+ return this.socket.type!.toString().toLowerCase();
+ }
+ @property({ type: Object }) public socket!: NodeSocket;
+ @property({ type: String }) public side!: "input" | "output";
+ @property({ type: Boolean }) public renderLabel = false;
+
+ private identityDeleted = false;
+ @query("#circle")
+ private circleElem!: HTMLElement;
+
+ public disconnectedCallback() {
+ this.identityDeleted = delete IdentityDomLink.map[this.socket.id!];
+ project.removeListener("connectioncreated", this.forceUpdate);
+ project.removeListener("connectionremoved", this.forceUpdate);
+ project.removeListener("nodeadded", this.forceUpdate);
+ project.removeListener("noderemoved", this.forceUpdate);
+ project.removeListener("cleared", this.forceUpdate);
+ (IdentityDomLink.map[this.socket.nodeId!] as FlowNode).removeEventListener("updated", this.forceUpdate);
+ }
+
+ protected firstUpdated() {
+ this.title = Utilities.humanLike(this.socketTypeString);
+ this.linkIdentity();
+ project.addListener("connectioncreated", this.forceUpdate);
+ project.addListener("connectionremoved", this.forceUpdate);
+ project.addListener("nodeadded", this.forceUpdate);
+ project.addListener("noderemoved", this.forceUpdate);
+ project.addListener("cleared", this.forceUpdate);
+ (IdentityDomLink.map[this.socket.nodeId!] as FlowNode).addEventListener("updated", this.forceUpdate);
+
+ const isInputSocket = this.side === "input";
+
+ const md = (e: MouseEvent) => {
+ this.linkIdentity();
+ if (e.buttons !== 1) { return; }
+ if (project.isCurrentlyConnecting) { return; }
+ project.startConnectionDrag(e, this.socket, isInputSocket);
+ e.stopPropagation();
+ e.stopImmediatePropagation();
+ };
+
+ const mu = (e: MouseEvent) => {
+ project.createUndoSnapshot();
+ this.linkIdentity();
+ project.endConnectionDrag(e, this.socket, isInputSocket);
+ project.notifyChange();
+ if (e.buttons !== 1) { return; }
+ e.stopPropagation();
+ e.stopImmediatePropagation();
+ };
+
+ this.addEventListener("mousedown", md);
+ this.addEventListener("mouseup", mu);
+ }
+
+ protected updated() {
+ this.linkIdentity();
+ }
+
+ protected render() {
+ const color = `var(--${this.socketTypeString})`;
+
+ const socket = html`<div class="socket">
+ <div class="circle" id="circle" style="background: ${color}"></div>
+ </div>`;
+
+ if (!this.renderLabel) { return socket; }
+ const label = html`<div class="label">${i18next.t(this.socket.name!)}</div>`;
+ if (this.side === "input") {
+ return html`${socket}${label}`;
+ } else {
+ return html`${label}${socket}`;
+ }
+ }
+
+ private forceUpdate = () => this.requestUpdate();
+
+ private linkIdentity() {
+ if (!this.identityDeleted) {
+ IdentityDomLink.map[this.socket.id!] = this;
+ }
+ }
+}
diff --git a/ui/component/or-rules/src/flow-viewer/components/flow-node.ts b/ui/component/or-rules/src/flow-viewer/components/flow-node.ts
new file mode 100644
index 000000000..a29586e4f
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/components/flow-node.ts
@@ -0,0 +1,137 @@
+import { html, customElement, css, property } from "lit-element";
+import { Node, NodeSocket } from "@openremote/model";
+import { IdentityDomLink } from "../node-structure";
+import { FlowNodeStyle } from "../styles/flow-node-style";
+import { i18next } from "@openremote/or-translate";
+import { nodeConverter } from "../converters/node-converter";
+import { SelectableElement } from "./selectable-element";
+import { EditorWorkspace } from "./editor-workspace";
+import { project, newIds } from "./flow-editor";
+
+@customElement("flow-node")
+export class FlowNode extends SelectableElement {
+ @property({ converter: nodeConverter }) public node!: Node;
+ @property({ attribute: false }) public workspace!: EditorWorkspace;
+ @property({ type: Boolean, reflect: true }) public frozen = false;
+
+ @property({ type: Boolean, reflect: true }) private minimal = false;
+ @property({ attribute: false }) private isBeingDragged = false;
+
+ constructor() {
+ super();
+ }
+
+ public static get styles() {
+ return FlowNodeStyle;
+ }
+
+ public disconnectedCallback() {
+ this.workspace.removeEventListener("pan", this.setTranslate);
+ this.workspace.removeEventListener("zoom", this.setTranslate);
+ project.removeListener("cleared", this.forceUpdate);
+ project.removeListener("connectionremoved", this.linkIdentity);
+ super.disconnectedCallback();
+ }
+
+ public bringToFront() {
+ if (this.frozen) { return; }
+ this.style.zIndex = `${this.workspace.topNodeZindex++}`;
+ }
+
+ protected async firstUpdated() {
+ super.firstUpdated();
+ this.linkIdentity();
+ this.workspace.addEventListener("pan", this.setTranslate);
+ this.workspace.addEventListener("zoom", this.setTranslate);
+ project.addListener("cleared", this.forceUpdate);
+ project.addListener("connectionremoved", this.linkIdentity);
+ this.minimal = (this.node.displayCharacter || "").length !== 0;
+ this.bringToFront();
+ if (newIds.has(this.node.id!)) { // node centering has to keep track of which nodes were created by the user
+ await this.updateComplete;
+ await this.updateComplete;
+ const size = this.getBoundingClientRect();
+ this.node.position!.x! -= size.width / 2 / this.workspace.camera.zoom;
+ this.node.position!.y! -= size.height / 2 / this.workspace.camera.zoom;
+ this.setTranslate();
+ newIds.delete(this.node.id!);
+ }
+ if (this.minimal) {
+ this.addEventListener("mousedown", this.startDrag);
+ }
+ }
+
+
+ protected async updated() {
+ this.linkIdentity();
+ this.dispatchEvent(new CustomEvent("updated"));
+ }
+
+ protected render() {
+ if (this.minimal) {
+ this.style.background = `var(--${this.node.type!.toLowerCase()}-color)`;
+ } else {
+ this.style.background = "";
+ }
+
+ this.setTranslate();
+ this.style.boxShadow = this.selected ? "var(--highlight) 0 0 0 3px" : "";
+
+ const title = this.minimal ?
+ html`<div class="title minimal" ?singlechar="${this.node.displayCharacter!.length === 1}">${i18next.t(this.node.displayCharacter!)}</div>` :
+ html`<div class="title ${this.node.type!.toLowerCase()}" @mousedown="${this.startDrag}">${i18next.t(this.node.name!) || "invalid"}</div>`;
+
+ const inputSide = html`<div class="socket-side inputs">${this.node.inputs!.map((i) => html`<flow-node-socket ?renderlabel="${!this.minimal}" .socket="${i}" side="input"></flow-node-socket>`)}</div>`;
+ const outputSide = html`<div class="socket-side outputs">${this.node.outputs!.map((i) => html`<flow-node-socket ?renderlabel="${!this.minimal}" .socket="${i}" side="output"></flow-node-socket>`)}</div>`;
+ const spacer = html`<div style="width: 10px"></div>`;
+ return html`
+ ${title}
+ ${this.node.inputs!.length > 0 ? inputSide : spacer}
+ ${(this.minimal) ? null : html`<div class="internal-container">${this.node.internals!.map((i) =>
+ html`<internal-picker style="pointer-events: ${(this.frozen ? "none" : "normal")}" @picked="${async () => {
+ this.forceUpdate();
+ await this.updateComplete;
+ project.removeInvalidConnections();
+ }}" .node="${this.node}" .internalIndex="${this.node.internals!.indexOf(i)}"></internal-picker>`)}</div>`}
+ ${this.node.outputs!.length > 0 ? outputSide : spacer}
+ ${(this.frozen ? html`<or-icon class="lock-icon ${this.node.type!.toLowerCase()}" icon="lock"></or-icon>` : ``)}
+ `;
+ }
+
+ private forceUpdate = () => { this.requestUpdate(); };
+
+ private setTranslate = () => {
+ const pos = this.workspace.worldToOffset(this.node.position!);
+ this.style.transform = `translate(${pos.x}px, ${pos.y}px) scale(${this.workspace.camera.zoom})`;
+ this.dispatchEvent(new CustomEvent("updated"));
+ }
+
+ private startDrag = (e: MouseEvent) => {
+ if (this.frozen) { return; }
+ if (e.buttons !== 1) { return; }
+ project.createUndoSnapshot();
+ this.bringToFront();
+ window.addEventListener("mouseup", this.stopDrag);
+ window.addEventListener("mousemove", this.onDrag);
+ this.isBeingDragged = true;
+ }
+
+ private onDrag = (e: MouseEvent) => {
+ this.node.position = {
+ x: this.node.position!.x! + e.movementX / this.workspace.camera.zoom,
+ y: this.node.position!.y! + e.movementY / this.workspace.camera.zoom
+ };
+ this.setTranslate();
+ }
+
+ private stopDrag = () => {
+ window.removeEventListener("mouseup", this.stopDrag);
+ window.removeEventListener("mousemove", this.onDrag);
+ this.isBeingDragged = false;
+ project.notifyChange();
+ }
+
+ private linkIdentity = () => {
+ IdentityDomLink.map[this.node.id!] = this;
+ }
+}
diff --git a/ui/component/or-rules/src/flow-viewer/components/internal-picker.ts b/ui/component/or-rules/src/flow-viewer/components/internal-picker.ts
new file mode 100644
index 000000000..d1e46a902
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/components/internal-picker.ts
@@ -0,0 +1,252 @@
+import { LitElement, property, customElement, html, css, TemplateResult } from "lit-element";
+import { Node, PickerType, AssetAttributeInternalValue, AssetState, MetaItemType, Asset, NodeDataType } from "@openremote/model";
+import { nodeConverter } from "../converters/node-converter";
+import { OrInputChangedEvent } from "@openremote/or-input";
+import rest from "@openremote/rest";
+import { OrAssetTreeRequestSelectEvent } from "@openremote/or-asset-tree";
+import { ResizeObserver } from "resize-observer";
+import { project, modal } from "./flow-editor";
+import { NodeUtilities } from "../node-structure";
+import { translate, i18next } from "@openremote/or-translate";
+import { PickerStyle } from "../styles/picker-styles";
+
+@customElement("internal-picker")
+export class InternalPicker extends translate(i18next)(LitElement) {
+ @property({ converter: nodeConverter, reflect: true }) public node!: Node;
+ @property({ type: Number, reflect: true }) public internalIndex!: number;
+
+ @property({ type: Array }) private attributeNames: { name: string, label: string }[] = [];
+ @property({ type: Object }) private selectedAsset!: Asset;
+ @property({ type: Boolean }) private assetIntialised = false;
+
+ private resizeObserver!: ResizeObserver;
+
+ constructor() {
+ super();
+ }
+
+ public get internal() {
+ return this.node.internals![this.internalIndex];
+ }
+
+ public static get styles() {
+ return [css`
+ :host{
+ padding: 0;
+ margin: 0;
+ display: flex;
+ flex-direction: column;
+ }`,
+ PickerStyle];
+ }
+
+ protected firstUpdated() {
+ this.addEventListener("contextmenu", (e) => e.stopPropagation());
+ this.addEventListener("mousedown", (e) => {
+ project.createUndoSnapshot();
+ return project.notifyChange();
+ });
+ this.resizeObserver = new ResizeObserver((a, b) => {
+ const rect = a[0]!.contentRect;
+ this.node.size = { x: rect.width - 20, y: rect.height - 20 };
+ });
+ this.resizeObserver.observe(this);
+ }
+
+ protected render() {
+ switch (this.internal.picker!.type) {
+ case PickerType.ASSET_ATTRIBUTE:
+ if (this.internal.value && !this.assetIntialised) { this.readAssetOnCreation(); }
+ return this.assetAttributeInput;
+ case PickerType.COLOR:
+ return this.colorInput;
+ case PickerType.DOUBLE_DROPDOWN:
+ return this.doubleDropdownInput;
+ case PickerType.CHECKBOX:
+ return this.checkBoxInput;
+ case PickerType.DROPDOWN:
+ return this.dropdownInput;
+ case PickerType.MULTILINE:
+ return this.multilineInput;
+ case PickerType.NUMBER:
+ return this.numberInput;
+ case PickerType.TEXT:
+ return this.textInput;
+ default:
+ return html`unimplemented picker`;
+ }
+ }
+
+ private async readAssetOnCreation() {
+ await this.populateAttributeNames();
+ }
+
+ private get assetTreeTemplate() {
+ return html`<or-asset-tree @or-asset-tree-request-select="${(e: OrAssetTreeRequestSelectEvent) => {
+ const value: AssetAttributeInternalValue = {
+ assetId: e.detail.detail.node.asset!.id,
+ attributeName: "nothing yet"
+ };
+ this.setValue(value);
+ this.populateAttributeNames();
+ modal.element.close();
+ }}"
+ style="width: auto; height: 80vh;"
+ ></or-asset-tree>`;
+ }
+
+ private async populateAttributeNames() {
+ const response = await rest.api.AssetResource.queryAssets({
+ ids: [this.internal.value.assetId],
+ select: {
+ excludeAttributes: false, excludeAttributeMeta: false
+ }
+ });
+
+ if (response.data.length === 0) {
+ this.assetIntialised = true;
+ console.warn(`Asset with id ${this.internal.value.assetId} is missing`);
+ return;
+ }
+ this.selectedAsset = response.data[0];
+ if (this.selectedAsset.attributes != null) {
+ this.attributeNames = [];
+ for (const att of Object.keys(this.selectedAsset.attributes)) {
+ const meta = (this.selectedAsset.attributes[att] as AssetState).meta;
+ if (!meta) { continue; }
+ if (meta.find((m) => m.name === MetaItemType.RULE_STATE.urn && m.value === true)) {
+ const foundLabel = meta.find((b) => b.name === MetaItemType.LABEL.urn && b.value);
+ let label = att;
+ if (foundLabel) { label = foundLabel.value; }
+ this.attributeNames.push({
+ name: att,
+ label
+ });
+ }
+ }
+ if (this.attributeNames.length !== 0) {
+ if (this.internal.value && this.internal.value.attributeName) {
+ this.assetIntialised = true;
+ await this.updateComplete;
+ (this.shadowRoot!.getElementById("attribute-select") as HTMLSelectElement).value = this.internal.value.attributeName;
+ return;
+ }
+ this.internal.value.attributeName = this.attributeNames[0].name;
+ }
+ } else {
+ this.attributeNames = [];
+ }
+ this.assetIntialised = true;
+ }
+
+ private async setSocketTypeDynamically(value: AssetAttributeInternalValue) {
+ const results = (await rest.api.AssetResource.queryAssets({
+ ids: [value.assetId!],
+ select: {
+ excludeAttributeTimestamp: false,
+ excludeAttributeValue: false,
+ excludeAttributeType: false,
+ excludeAttributes: false,
+ attributes: [
+ value.attributeName!
+ ]
+ }
+ })).data;
+
+ const socket = this.node.outputs![0] || this.node.inputs![0];
+ socket.type = NodeDataType.ANY;
+ if (results == null) { return; }
+ if (results[0] == null) { return; }
+ if (results[0].attributes == null) { return; }
+ try {
+ const relevantAttribute = results[0].attributes[value.attributeName!];
+ const descriptors = (await rest.api.AssetModelResource.getAttributeValueDescriptors()).data;
+ const relevantDescriptor = descriptors.find((c) => c.name === relevantAttribute.type);
+ socket.type = NodeUtilities.convertValueTypeToSocketType(relevantDescriptor!.valueType!);
+ } catch (e) {
+ console.error(e);
+ }
+ }
+
+ private get assetAttributeInput(): TemplateResult {
+ const hasAssetSelected = this.selectedAsset;
+ return html`
+ <or-input type="button" fullwidth label="${hasAssetSelected ? this.selectedAsset.name! : (i18next.t("selectAsset", "Select asset")!)}"
+ icon="format-list-bulleted-square"
+ @click="${() => {
+ modal.element.content = this.assetTreeTemplate;
+ modal.element.header = i18next.t("assets", "Assets");
+ modal.element.open();
+ }}"></or-input>
+ ${
+ hasAssetSelected ? (
+ this.attributeNames.length === 0 ?
+ html`<span>${i18next.t("noRuleStateAttributes", "No rule state attributes")}</span>` :
+ html`
+ <select id="attribute-select" style="margin-top: 10px" @input="${async (e: any) => {
+ const value: AssetAttributeInternalValue = {
+ assetId: this.selectedAsset.id,
+ attributeName: e.target.value
+ };
+ await this.setSocketTypeDynamically(value);
+ return this.setValue(value);
+ }}">
+ ${this.attributeNames.map((a) => html`<option value="${a.name}" title="${a.name}">${a.label}</option>`)}
+ </select>`) :
+ null
+ }
+ `;
+ }
+
+ private get colorInput(): TemplateResult {
+ return html`<or-input type="color"></or-input>`; // looks strange
+ }
+
+ private get doubleDropdownInput(): TemplateResult {
+ return html`unimplemented`;
+ }
+
+ private get dropdownInput(): TemplateResult {
+ return html`<writable-dropdown @input="${(e: any) => this.setValue(e.target.value)}" .value="${this.internal.value}" .options="${this.internal.picker!.options}">
+ </writable-dropdown>`;
+ }
+
+ private get checkBoxInput(): TemplateResult {
+ return html`<input type="checkbox" ?checked="${this.internal.value || false}" @input="${(e: any) => this.setValue(e.target.checked)}"/>`;
+ return html`<or-input type="checkbox"
+ @or-input-changed="${(e: OrInputChangedEvent) => {
+ this.setValue(e.detail.value);
+ }}"></or-input>`;
+ }
+
+ private get multilineInput(): TemplateResult {
+ const sizeString = this.node.size ? `width:${this.node.size.x}px; height:${this.node.size.y}px` : ``;
+ return html`<textarea @wheel="${(e: any) => {
+ if (e.target.clientHeight < e.target.scrollHeight) {
+ return e.stopPropagation();
+ }
+ }}" style="${sizeString}" @input="${(e: any) => this.setValue(e.target.value)}" placeholder="${this.internal.name!}">${this.internal.value || ""}</textarea>`;
+ }
+
+ private get numberInput(): TemplateResult {
+ return html`<input @wheel="${(e: any) => {
+ if (e.target === this.shadowRoot!.activeElement) {
+ return e.stopPropagation();
+ }
+ }}" @input="${(e: any) => this.setValue(parseFloat(e.target.value))}" value="${this.internal.value || 0}" type="number" placeholder="${this.internal.name!}"/>`;
+ }
+
+ private get textInput(): TemplateResult {
+ return html`<input @input="${(e: any) => this.setValue(e.target.value)}" value="${this.internal.value || ""}" type="text" placeholder="${this.internal.name!}"/>`;
+ }
+
+ private setValue(value: any) {
+ this.node.internals![this.internalIndex].value = value;
+ this.onPicked();
+ }
+
+ private async onPicked() {
+ await this.updateComplete;
+ this.dispatchEvent(new CustomEvent("picked"));
+ }
+}
diff --git a/ui/component/or-rules/src/flow-viewer/components/node-menu-item.ts b/ui/component/or-rules/src/flow-viewer/components/node-menu-item.ts
new file mode 100644
index 000000000..8b6f4689f
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/components/node-menu-item.ts
@@ -0,0 +1,127 @@
+import { LitElement, html, customElement, css, property } from "lit-element";
+import { Node, NodeType } from "@openremote/model";
+import { EditorWorkspace } from "./editor-workspace";
+import { Utilities } from "../utils";
+import { i18next, translate } from "@openremote/or-translate";
+import { newIds, project } from "./flow-editor";
+import { CopyMachine } from "../node-structure";
+
+@customElement("node-menu-item")
+export class NodeMenuItem extends translate(i18next)(LitElement) {
+ @property({ attribute: false }) public node!: Node;
+ @property({ attribute: false }) private isDragging = false;
+
+ @property({ attribute: false }) private x = 0;
+ @property({ attribute: false }) private y = 0;
+
+ @property({ attribute: false }) private workspace !: EditorWorkspace;
+
+ private xOffset = 0;
+ private yOffset = 0;
+
+ constructor() {
+ super();
+ this.addEventListener("mousedown", this.startDrag);
+ }
+ static get styles() {
+ return css`
+ :host, .node-drag-item{
+ padding: 4px;
+ margin: 0 0 15px 0;
+ display: inline-block;
+ text-align: center;
+ color: white;
+ border-radius: var(--roundness);
+ box-shadow: rgba(0, 0, 0, 0.2) 0px 5px 5px -5px;
+
+ width: calc(var(--nodepanel-width) - 4px * 2);
+ height: 22px;
+ line-height: 22px;
+ cursor:grab;
+ transition: box-shadow 150ms;
+ }
+ :host(.small), .small{
+ width: 26px;
+ height: 26px;
+ line-height: 26px;
+ margin: 0;
+ }
+ .node-drag-item{
+ z-index: 5000;
+ position: fixed;
+ background: inherit;
+ box-shadow: rgba(0, 0, 0, 0.2) 0 2px 15px;
+ filter: opacity(90%);
+ pointer-events: none;
+ }
+ `;
+ }
+
+ protected render() {
+ switch (this.node.type) {
+ case NodeType.INPUT:
+ this.classList.add("input-node");
+ break;
+ case NodeType.PROCESSOR:
+ this.classList.add("processor-node");
+ break;
+ case NodeType.OUTPUT:
+ this.classList.add("output-node");
+ break;
+ }
+
+ if (this.node.displayCharacter) {
+ this.classList.add("small");
+ }
+ this.title = i18next.t(this.node.name!, Utilities.humanLike(this.node.name!));
+ return html`
+ <div class="label">${this.flowNodeName}</div>
+ ${this.isDragging ? this.dragNodeTemplate : null}
+ `;
+ }
+
+ private get dragNodeTemplate() {
+ return html`<div class="node-drag-item ${(this.node.displayCharacter ? "small" : null)}" style="top: ${this.y - this.yOffset}px; left: ${this.x - this.xOffset}px"><div class="label">${this.flowNodeName}</div></div>`;
+ }
+
+ private get flowNodeName() {
+ const n = this.node.displayCharacter || this.node.name;
+ return i18next.t(n!, Utilities.humanLike(n!));
+ }
+
+ private startDrag = (e: MouseEvent) => {
+ this.xOffset = e.offsetX;
+ this.yOffset = e.offsetY;
+ this.x = e.clientX;
+ this.y = e.clientY;
+
+ this.isDragging = true;
+ window.addEventListener("mouseup", this.stopDrag);
+ window.addEventListener("mousemove", this.onMove);
+ }
+
+ private onMove = (e: MouseEvent) => {
+ this.x = e.clientX;
+ this.y = e.clientY;
+ }
+
+ private stopDrag = (e: MouseEvent) => {
+ window.removeEventListener("mouseup", this.stopDrag);
+ window.removeEventListener("mousemove", this.onMove);
+ this.isDragging = false;
+
+ if (Utilities.isPointInsideBox(e.offsetX, e.offsetY, {
+ x: this.workspace.clientRect.left,
+ y: this.workspace.clientRect.top,
+ width: this.workspace.clientRect.width,
+ height: this.workspace.clientRect.height,
+ })) {
+ const copy = CopyMachine.copy(this.node);
+ newIds.add(copy.id!);
+ copy.position = this.workspace.offsetToWorld({ x: e.offsetX - this.workspace.clientRect.left, y: e.offsetY - this.workspace.clientRect.top });
+ project.createUndoSnapshot();
+ project.addNode(copy);
+ project.notifyChange();
+ }
+ }
+}
diff --git a/ui/component/or-rules/src/flow-viewer/components/node-panel.ts b/ui/component/or-rules/src/flow-viewer/components/node-panel.ts
new file mode 100644
index 000000000..d65b42ad1
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/components/node-panel.ts
@@ -0,0 +1,92 @@
+import { LitElement, html, customElement, css, property, query } from "lit-element";
+import { NodeType, Node } from "@openremote/model";
+import { i18next, translate } from "@openremote/or-translate";
+import { OrMwcDrawer } from "@openremote/or-mwc-components/dist/or-mwc-drawer";
+import { FlowEditor } from "./flow-editor";
+import { OrInputChangedEvent } from "@openremote/or-input";
+
+@customElement("node-panel")
+export class NodePanel extends translate(i18next)(LitElement) {
+ @property({ type: Array }) public nodes: Node[] = [];
+ static get styles() {
+ return css`
+ .list{
+ overflow-x: hidden;
+ overflow-y: auto;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ height: 100%;
+ background: #F9F9F9;
+ }
+ .category{
+ display: flex;
+ width: 80%;
+ flex-direction: column;
+ align-items: center;
+ text-align: center;
+ padding: 15px 15px 0 15px;
+ }
+ .category span{
+ margin:0;
+ color: rgb(125,125,125);
+ padding: 0 0 15px 0 ;
+ }
+ .small-node-grid{
+ display: grid;
+ grid-template-columns: repeat(5, 1fr);
+ grid-template-rows: repeat(2, 1fr);
+ grid-gap: 6px;
+ justify-items: stretch;
+ align-items: stretch;
+ margin-bottom: 15px;
+ width: var(--nodepanel-width);
+ }
+ .input-node{ background-color: var(--input-color); }
+ .processor-node{ background-color: var(--processor-color); }
+ .output-node{ background-color: var(--output-color); }
+ .input-node:hover{ background-color: var(--input-color-h); }
+ .processor-node:hover{ background-color: var(--processor-color-h); }
+ .output-node:hover{ background-color: var(--output-color-h); }`;
+ }
+
+ @query("or-mwc-drawer") public drawer!: OrMwcDrawer;
+ @property({ attribute: false }) public application!: FlowEditor;
+
+ protected firstUpdated() {
+ this.drawer.open = true;
+ }
+
+ protected render() {
+ return html`
+ <!-- <or-mwc-drawer rightsided dismissible transparent> -->
+ ${this.listTemplate}
+ <!-- </or-mwc-drawer> -->
+ `;
+ }
+
+ private nodeTemplate(node: Node) {
+ return html`<node-menu-item class="node-item" .node="${node}" .workspace="${this.application.editorWorkspace}"></node-menu-item>`;
+ }
+
+ private get listTemplate() {
+ return html`
+ <div class="list">
+ <div class="category"> <span>${i18next.t("input", "Input")}</span>
+ ${this.nodes.filter((n) => n.type === NodeType.INPUT).map((n) => this.nodeTemplate(n))}
+ </div>
+
+ <div class="category"><span>${i18next.t("processors", "Processors")}</span>
+ <div class="small-node-grid">
+ ${this.nodes.filter((n) => n.type === NodeType.PROCESSOR && n.displayCharacter).map((n) => this.nodeTemplate(n))}
+ </div>
+ ${this.nodes.filter((n) => n.type === NodeType.PROCESSOR && !n.displayCharacter).map((n) => this.nodeTemplate(n))}
+ </div>
+
+ <div class="category"> <span>${i18next.t("output", "Output")}</span>
+ ${this.nodes.filter((n) => n.type === NodeType.OUTPUT).map((n) => this.nodeTemplate(n))}
+ </div>
+ </div>
+ `;
+ }
+}
diff --git a/ui/component/or-rules/src/flow-viewer/components/notification-dialog.ts b/ui/component/or-rules/src/flow-viewer/components/notification-dialog.ts
new file mode 100644
index 000000000..33805f981
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/components/notification-dialog.ts
@@ -0,0 +1,38 @@
+import { LitElement, html, customElement, css, property } from "lit-element";
+import { i18next, translate } from "@openremote/or-translate";
+
+@customElement("notification-dialog")
+export class NotificationDialog extends translate(i18next)(LitElement) {
+ @property({ type: String }) public buttonText = i18next.t("ok");
+ @property({ type: String }) public message = " ";
+
+ public static get styles() {
+ return css`
+ .message{
+ width: 100%;
+ padding: 15px 5px 25px 5px;
+ text-align: center;
+ max-width: 50vw;
+ overflow: auto;
+ user-select: text;
+ }
+ .container{
+ display: flex;
+ flex-direction: row;
+ justify-content: space-between;
+ justify-content: space-evenly;
+ justify-content: space-around;
+ }`;
+ }
+
+ protected render() {
+ return html`
+ <div class="message">${this.message}</div>
+ <div class="container">
+ <or-input type="button" unElevated label="${this.buttonText}"
+ @click="${() => { this.dispatchEvent(new CustomEvent("closed")); }}">
+ </or-input>
+ </div>
+ `;
+ }
+}
diff --git a/ui/component/or-rules/src/flow-viewer/components/popup-modal.ts b/ui/component/or-rules/src/flow-viewer/components/popup-modal.ts
new file mode 100644
index 000000000..38581db94
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/components/popup-modal.ts
@@ -0,0 +1,101 @@
+import { customElement, LitElement, css, html, property, TemplateResult } from "lit-element";
+import { modal } from "./flow-editor";
+import { translate, i18next } from "@openremote/or-translate";
+
+@customElement("popup-modal")
+export class PopupModal extends translate(i18next)(LitElement) {
+ @property({ type: Boolean }) public closeButton = true;
+ @property({ type: String }) public header?: string;
+ @property({ attribute: false }) public content?: TemplateResult;
+
+ @property({ type: Boolean, reflect: true }) private isOpen = false;
+
+ constructor() {
+ super();
+ }
+
+ public close() {
+ this.isOpen = false;
+ }
+
+ public open() {
+ this.isOpen = true;
+ }
+
+ public static get styles() {
+ return css`
+ :host{
+ position: absolute;
+ left: 0;
+ right: 0;
+ top: 0;
+ bottom: 0;
+
+ display: flex;
+ justify-content: center;
+ align-items: center;
+
+ background: rgba(0, 0, 0, 0.2);
+ z-index: 10000;
+
+ --topbar-height: 42px;
+ --closebutton-padding: 12px;
+ --modal-padding: 10px;
+ }
+ :host(:not([isopen])){
+ display: none;
+ }
+ .modal{
+ min-width: 300px;
+ min-height: 64px;
+ width: auto;
+ height: auto;
+ display: inline-block;
+ background: white;
+ border-radius: var(--roundness);
+ position: relative;
+ padding: var(--modal-padding);
+ }
+ .close-button{
+ position: absolute;
+ top: 0;
+ right: 0;
+ width: calc(var(--topbar-height) - var(--closebutton-padding) * 2);
+ height: calc(var(--topbar-height) - var(--closebutton-padding) * 2);
+ padding: var(--closebutton-padding);
+ cursor: pointer;
+ }
+ .title{
+ margin: 0;
+ height: calc(var(--topbar-height) - var(--modal-padding));
+ width: 100%;
+ text-transform: uppercase;
+ font-weight: bold;
+ }`;
+ }
+
+ protected firstUpdated() {
+ modal.element = this;
+ this.addEventListener("mousedown", this.close);
+ window.addEventListener("keyup", (e: KeyboardEvent) => {
+ if (e.key === "Escape") {
+ this.close();
+ }
+ });
+ }
+
+ protected render() {
+ if (!this.isOpen) {
+ this.style.display = "none";
+ return html``;
+ }
+ this.style.display = "";
+ return html`
+ <div class="modal" @mousedown="${(e: MouseEvent) => { e.stopPropagation(); }}">
+ <div class="title">${this.header}</div>
+ ${this.content}
+ ${this.closeButton ? html`<or-icon class="close-button" icon="window-close" @click="${this.close}"></or-icon>` : null}
+ </div>
+ `;
+ }
+}
diff --git a/ui/component/or-rules/src/flow-viewer/components/rule-browser.ts b/ui/component/or-rules/src/flow-viewer/components/rule-browser.ts
new file mode 100644
index 000000000..3fc4005f8
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/components/rule-browser.ts
@@ -0,0 +1,98 @@
+import { LitElement, customElement, css, property, html } from "lit-element";
+import { GlobalRuleset } from "@openremote/model";
+import rest from "@openremote/rest";
+import { i18next, translate } from "@openremote/or-translate";
+import { Utilities } from "../utils";
+import { Status } from "../models/status";
+import { exporter, project, modal } from "./flow-editor";
+
+@customElement("rule-browser")
+export class RuleBrowser extends translate(i18next)(LitElement) {
+ @property({ type: Number }) private status = Status.Idle;
+ private retrievedRules: GlobalRuleset[] = [];
+
+ public static get styles() {
+ return css`
+ .list-button {
+ cursor: pointer;
+ padding: 8px 0 8px 8px;
+ }
+ .list-button:hover {
+ background: whitesmoke;
+ }
+ .list-button:active {
+ background: none;
+ }
+ or-icon{
+ width: 18px;
+ vertical-align: text-top;
+ }
+ or-icon[icon=loading]{
+ animation: spin 600ms infinite linear;
+ }
+ @keyframes spin{
+ 0%{
+ transform: rotateZ(0deg);
+ }
+ 100%{
+ transform: rotateZ(360deg);
+ }
+ }`;
+ }
+
+ protected async firstUpdated() {
+ this.status = Status.Loading;
+ try {
+ const response = await rest.api.RulesResource.getGlobalRulesets();
+ this.retrievedRules = response.data;
+ this.status = Status.Success;
+ } catch (error) {
+ this.status = Status.Failure;
+ }
+ }
+
+ protected render() {
+ let result = html``;
+ switch (this.status) {
+ case Status.Loading:
+ result = html`<span style="text-align: center;"><or-icon icon="loading"></or-icon></span>`;
+ break;
+ case Status.Success:
+ result = html`${this.retrievedRules.length === 0 ?
+ html`<span>No rules to display</span>` :
+ this.retrievedRules.map((r: GlobalRuleset) => this.getButton(r))}`;
+ break;
+ case Status.Failure:
+ result = html`<span>Failed to load rules</span>`;
+ break;
+ }
+ return html`
+ <div style="display: flex; flex-direction: column; width: auto; align-items: stretch;">
+ ${result}
+ </div>`;
+ }
+
+ private loadRule = async (r: GlobalRuleset) => {
+ this.status = Status.Loading;
+ let response: { data: GlobalRuleset };
+ try {
+ response = await rest.api.RulesResource.getGlobalRuleset(r.id!);
+ } catch (error) {
+ modal.notification("Failure", "Something went wrong loading " + r.name);
+ this.status = Status.Failure;
+ return;
+ }
+ const ruleset = response.data;
+ const collection = exporter.jsonToFlow(ruleset.rules!);
+ project.fromNodeCollection(collection);
+ project.setCurrentProject(r.id!, r.name!, collection.description!);
+ this.dispatchEvent(new CustomEvent("ruleloaded"));
+ }
+
+ private getButton = (r: GlobalRuleset) => {
+ return html`<div class="list-button" @click="${() => { this.loadRule(r); }}">${Utilities.ellipsis(r.name!, 50)}
+ ${r.error ? html`<or-icon title="${Utilities.humanLike(r.status!)}" icon="alert-outline"></or-icon>` : null}
+ ${r.enabled ? null : html`<or-icon title="${i18next.t("disabled") as string}" icon="sleep"></or-icon>`}
+ </div>`;
+ }
+}
diff --git a/ui/component/or-rules/src/flow-viewer/components/selectable-element.ts b/ui/component/or-rules/src/flow-viewer/components/selectable-element.ts
new file mode 100644
index 000000000..e4e0e74e6
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/components/selectable-element.ts
@@ -0,0 +1,62 @@
+import { LitElement, property } from "lit-element";
+import { input } from "./flow-editor";
+import { i18next, translate } from "@openremote/or-translate";
+
+export class SelectableElement extends translate(i18next)(LitElement) {
+ public get selected() {
+ return this.isSelected;
+ }
+
+ public get handle() {
+ return this.selectableHandle;
+ }
+ @property({ type: Boolean }) private isSelected = false;
+ @property({ attribute: false }) private selectableHandle!: HTMLElement;
+
+ public disconnectedCallback() {
+ super.disconnectedCallback();
+ if (this.selected) {
+ input.selected.splice(input.selected.indexOf(this), 1);
+ }
+ this.isSelected = false;
+ input.removeListener("selected", this.onSelected);
+ input.removeListener("deselected", this.onDeselected);
+ input.selectables.splice(input.selectables.indexOf(this), 1);
+ }
+
+ public setHandle(element: HTMLElement) {
+ if (this.selectableHandle) {
+ this.selectableHandle.removeEventListener("mousedown", this.handleSelection);
+ }
+ element.addEventListener("mousedown", this.handleSelection);
+ this.selectableHandle = element;
+ }
+
+ protected firstUpdated() {
+ this.setHandle(this);
+ input.selectables.push(this);
+ input.addListener("selected", this.onSelected);
+ input.addListener("deselected", this.onDeselected);
+ }
+
+ private readonly onSelected = (e: HTMLElement) => {
+ if (e === this) {
+ this.isSelected = true;
+ }
+ }
+
+ private readonly onDeselected = (e: HTMLElement) => {
+ if (e === this) {
+ this.isSelected = false;
+ }
+ }
+
+ private readonly handleSelection = (event: MouseEvent) => {
+ if (event.buttons === 1) {
+ input.handleSelection(this);
+ event.stopPropagation();
+ } else if (event.buttons === 2) {
+ input.handleSelection(this, true);
+ }
+ }
+}
diff --git a/ui/component/or-rules/src/flow-viewer/components/selection-box.ts b/ui/component/or-rules/src/flow-viewer/components/selection-box.ts
new file mode 100644
index 000000000..e9fd727dd
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/components/selection-box.ts
@@ -0,0 +1,102 @@
+import { LitElement, customElement, property, html, css } from "lit-element";
+import { Utilities } from "../utils";
+import { EditorWorkspace } from "./editor-workspace";
+import { input } from "./flow-editor";
+
+@customElement("selection-box")
+export class SelectionBox extends LitElement {
+
+ public static get styles() {
+ return css`
+ svg{
+ fill: none;
+ overflow: visible;
+ position: absolute;
+ pointer-events: all;
+ stroke-linejoin: round;
+ transition: stroke-width 120ms;
+ z-index: 1000;
+ width: 100vw;
+ height: 100vh;
+ }
+ rect{
+ fill: var(--highlight-faded);
+ outline: solid 1px var(--highlight);
+ }`;
+ }
+ @property({ attribute: false }) public workspace!: EditorWorkspace;
+
+ public readonly distanceTreshold = 20;
+
+ @property({ attribute: false }) private isSelecting = false;
+
+ @property({ attribute: false }) private selectionStartPosition = { x: 0, y: 0 };
+ @property({ attribute: false }) private selectionBox = { x: 0, y: 0, width: 0, height: 0 };
+
+ protected firstUpdated() {
+ this.workspace.addEventListener("mousedown", this.workspaceMouseDown);
+ window.addEventListener("mouseup", this.workspaceMouseUp);
+ }
+
+ protected render() {
+ if (!this.isSelecting) { return html``; }
+ return html`<svg><rect x="${this.selectionBox.x}px" y="${this.selectionBox.y}px" width="${this.selectionBox.width}px" height="${this.selectionBox.height}px"></rect></svg>`;
+ }
+
+ private workspaceMouseDown = (e: MouseEvent) => {
+ if (e.buttons !== 1) { return; }
+ this.selectionBox.x = e.offsetX;
+ this.selectionBox.y = e.offsetY;
+ this.selectionStartPosition.x = this.selectionBox.x;
+ this.selectionStartPosition.y = this.selectionBox.y;
+ window.addEventListener("mousemove", this.mouseMove);
+ }
+
+ private mouseMove = (e: MouseEvent) => {
+ const width = e.pageX - this.workspace.clientRect.left - this.selectionStartPosition.x;
+ const height = e.pageY - this.workspace.clientRect.top - this.selectionStartPosition.y;
+
+ if (width < 0) {
+ this.selectionBox.x = e.pageX - this.workspace.clientRect.left;
+ this.selectionBox.width = Math.abs(this.selectionBox.x - this.selectionStartPosition.x);
+ } else {
+ this.selectionBox.x = this.selectionStartPosition.x;
+ this.selectionBox.width = Math.abs(width);
+ }
+
+ if (height < 0) {
+ this.selectionBox.y = e.pageY - this.workspace.clientRect.top;
+ this.selectionBox.height = Math.abs(this.selectionBox.y - this.selectionStartPosition.y);
+ } else {
+ this.selectionBox.y = this.selectionStartPosition.y;
+ this.selectionBox.height = Math.abs(height);
+ }
+ if (this.selectionBox.width + this.selectionBox.height > this.distanceTreshold) { this.isSelecting = true; }
+
+ this.requestUpdate();
+ }
+
+ private workspaceMouseUp = () => {
+ window.removeEventListener("mousemove", this.mouseMove);
+ if (this.isSelecting) {
+ this.selectInBounds();
+ this.isSelecting = false;
+ }
+ }
+
+ private selectInBounds() {
+ input.clearSelection();
+ const offsetBox = {
+ x: this.selectionBox.x + this.workspace.clientRect.left,
+ y: this.selectionBox.y + this.workspace.clientRect.top,
+ width: this.selectionBox.width,
+ height: this.selectionBox.height,
+ };
+ for (const selectable of input.selectables) {
+ const rect = selectable.handle.getBoundingClientRect();
+ if (Utilities.isBoxInsideBox({ x: rect.left, y: rect.top, width: rect.width, height: rect.height }, offsetBox)) {
+ input.select(selectable, true);
+ }
+ }
+ }
+}
diff --git a/ui/component/or-rules/src/flow-viewer/components/top-bar.ts b/ui/component/or-rules/src/flow-viewer/components/top-bar.ts
new file mode 100644
index 000000000..681c03568
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/components/top-bar.ts
@@ -0,0 +1,112 @@
+import { LitElement, html, customElement, css, property } from "lit-element";
+import { IdentityDomLink } from "../node-structure";
+import { OrInputChangedEvent } from "@openremote/or-input";
+import { Utilities } from "../utils";
+import { i18next, translate } from "@openremote/or-translate";
+import { project, modal, input, exporter, FlowEditor } from "./flow-editor";
+import { NodePanel } from "./node-panel";
+
+@customElement("top-bar")
+export class TopBar extends translate(i18next)(LitElement) {
+ static get styles() {
+ return css`
+ :host{
+ display: flex;
+ width: 100%;
+ justify-content: flex-start;
+ align-items: center;
+ box-shadow: rgba(0, 0, 0, 0.2) 0px 5px 5px -5px;
+ line-height: var(--topbar-height);
+ z-index: 150;
+ }
+ .button{
+ padding: 0 25px 0 25px;
+ cursor: pointer;
+ }
+ .button:hover{
+ background: #fafafa;
+ }
+ .button:active{
+ background: whitesmoke;
+ }
+ .debug.button{
+ background: yellow;
+ }
+ .title{
+ margin: 0 15px 0 15px;
+ text-transform: uppercase;
+ font-weight: bold;
+ }
+ .right{
+ margin-left: auto;
+ }`;
+ }
+
+ @property({ attribute: false }) public application!: FlowEditor;
+
+ protected firstUpdated() {
+ project.addListener("unsavedstateset", () => {
+ this.requestUpdate();
+ });
+ }
+
+ protected render() {
+ return html`
+ <span class="title">${i18next.t("flowEditor")}</span>
+ <a class="button" @click="${() => {
+ if (project.unsavedState) {
+ modal.confirmation(() => { project.clear(true); }, "New project");
+ } else {
+ project.clear(true);
+ }
+ }}">New</a>
+ <a class="button" @click="${this.save}">${i18next.t("save")} <i>${Utilities.ellipsis(project.existingFlowRuleName!)}</i>${project.unsavedState && project.existingFlowRuleId !== -1 ? "*" : ""}</a>
+ ${project.existingFlowRuleId === -1 ? null : html`<a @click="${this.showSaveAsDialog}" class="button">Save as...</a>`}
+ <a class="button" @click="${this.showRuleBrowser}">Open</a>
+ <a class="button right" @click="${() => {
+ this.application.nodePanel.drawer.toggle();
+ }}"><or-icon icon="menu"></or-icon></a>
+ `;
+ }
+
+ private save() {
+ if (project.existingFlowRuleId === -1) {
+ this.showSaveAsDialog();
+ } else {
+ exporter.exportAsExisting(
+ project.existingFlowRuleId,
+ project.toNodeCollection(project.existingFlowRuleName!, project.existingFlowRuleDesc!));
+ }
+ }
+
+ private showRuleBrowser() {
+ modal.element.content = html`<rule-browser @ruleloaded="${() => modal.element.close()}"></rule-browser>`;
+ modal.element.header = "Select a Flow rule";
+ modal.element.open();
+ }
+
+ private showSaveAsDialog() {
+ let chosenName = "";
+ let chosenDesc = "";
+ modal.element.content = html`
+ <div style="display: flex; flex-direction: column; width: auto; justify-content: space-between; align-items: stretch;">
+ <or-input style="margin-bottom: 16px; width:100%;" required type="text" label="${i18next.t("name", "Name")!}"
+ @or-input-changed="${(e: OrInputChangedEvent) => { chosenName = e.detail.value; }}"
+ ></or-input>
+ <or-input style="margin-bottom: 16px; width:100%;" fullwidth type="textarea" label="${i18next.t("description", "Description")!}"
+ @or-input-changed="${(e: OrInputChangedEvent) => { chosenDesc = e.detail.value; }}"
+ ></or-input>
+ <div>
+ <or-input style="text-align: left; margin-right: 10px" type="button" label="${i18next.t("cancel", "Cancel")!}" @click="${modal.element.close}"></or-input>
+ <or-input style="text-align: right" type="button" unelevated label="${i18next.t("save", "Save")!}" @click="${() => {
+ if (!chosenName) { return; }
+ exporter.exportAsNew(project.toNodeCollection(chosenName, chosenDesc));
+ modal.element.close();
+ }}"></or-input>
+ </div>
+ </div>
+ `;
+ modal.element.header = "Save project";
+ modal.element.open();
+ }
+}
diff --git a/ui/component/or-rules/src/flow-viewer/components/workspace-contextmenu-options.ts b/ui/component/or-rules/src/flow-viewer/components/workspace-contextmenu-options.ts
new file mode 100644
index 000000000..021184904
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/components/workspace-contextmenu-options.ts
@@ -0,0 +1,131 @@
+import { EditorWorkspace } from "./editor-workspace";
+import { FlowNode } from "./flow-node";
+import { ConnectionLine } from "../flow-viewer";
+import { NodeType } from "@openremote/model";
+import { ContextMenuButton, ContextMenuSeparator } from "../models/context-menu-button";
+import { integration, project, copyPasteManager, input, exporter, modal } from "./flow-editor";
+import i18next from "i18next";
+import { Utilities } from "../utils";
+import { CopyMachine } from "../node-structure";
+import { ContextMenu } from "./context-menu";
+import { html } from "lit-element";
+
+export const createContextMenuButtons = (workspace: EditorWorkspace, e: MouseEvent) => {
+ const selectedNodes = input.selected.filter((s) => s instanceof FlowNode && s.selected) as FlowNode[];
+ const selectedConnections = input.selected.filter((s) => s instanceof ConnectionLine && s.selected) as ConnectionLine[];
+ const createNodeButtons = (type: NodeType) => {
+ let nB: (ContextMenuButton | ContextMenuSeparator)[] = [
+ {
+ type: "button",
+ label: "",
+ icon: "arrow-left",
+ action: () => { workspace.dispatchEvent(new MouseEvent("contextmenu", e)); }
+ }
+ ];
+ nB = nB.concat(integration.nodes.filter((n) => n.type === type).map((node) => {
+ const b: ContextMenuButton = {
+ type: "button",
+ label: i18next.t(node.name!, Utilities.humanLike(node.name!)),
+ action: () => {
+ const copy = CopyMachine.copy(node);
+ copy.position = workspace.offsetToWorld({ x: e.offsetX - workspace.offsetLeft, y: e.offsetY - workspace.offsetTop });
+ project.createUndoSnapshot();
+ project.addNode(copy);
+ }
+ };
+ return b;
+ }));
+ return nB;
+ };
+
+ let buttons: (ContextMenuButton | ContextMenuSeparator)[] = [
+ {
+ type: "button",
+ label: i18next.t("input", "Input"),
+ icon: "arrow-collapse-right",
+ action: () => { ContextMenu.open(e.pageX, e.pageY, workspace, createNodeButtons(NodeType.INPUT)); }
+ },
+ {
+ type: "button",
+ label: i18next.t("processors", "Processors"),
+ icon: "settings",
+ action: () => { ContextMenu.open(e.pageX, e.pageY, workspace, createNodeButtons(NodeType.PROCESSOR)); }
+ },
+ {
+ type: "button",
+ label: i18next.t("output", "Ouput"),
+ icon: "arrow-expand-right",
+ action: () => { ContextMenu.open(e.pageX, e.pageY, workspace, createNodeButtons(NodeType.OUTPUT)); }
+ },
+ ];
+
+ buttons = buttons.concat([
+ { type: "separator" },
+ {
+ type: "button",
+ icon: "content-copy",
+ label: i18next.t("copy", "Copy"),
+ action: () => {
+ const pos = workspace.offsetToWorld({ x: e.offsetX, y: e.offsetY });
+ copyPasteManager.copy(pos.x, pos.y);
+ },
+ disabled: selectedNodes.length === 0
+ },
+ {
+ type: "button",
+ icon: "content-paste",
+ label: i18next.t("paste", "Paste"),
+ action: () => {
+ project.createUndoSnapshot();
+ const pos = workspace.offsetToWorld({ x: e.offsetX, y: e.offsetY });
+ project.notifyChange();
+ workspace.pasteAt(pos.x, pos.y);
+ },
+ disabled: copyPasteManager.isFull
+ },
+ {
+ type: "button",
+ icon: "delete",
+ label: i18next.t("delete", "Delete"),
+ action: () => {
+ project.createUndoSnapshot();
+ selectedNodes.forEach((n) => {
+ if (n.frozen) { return; }
+ project.removeNode(n.node);
+ });
+ selectedConnections.forEach((n) => project.removeConnection(n.connection));
+ project.notifyChange();
+ },
+ disabled: (selectedNodes.length === 0 && selectedConnections.length === 0) || (selectedNodes.length !== 0 && selectedNodes.every((n) => n.frozen))
+ },
+ { type: "separator" },
+ {
+ type: "button",
+ icon: "fit-to-page-outline",
+ label: i18next.t("fitViewToSelectedNodes", "Fit view to selected nodes"),
+ action: () => workspace.fitCamera(selectedNodes.map((n) => n.node)),
+ disabled: selectedNodes.length === 0
+ },
+ {
+ type: "button",
+ icon: "snowflake",
+ label: "TOGGLE FROZEN [DEBUG FUNCTION]",
+ action: () => selectedNodes.forEach((n) => n.frozen = !n.frozen),
+ disabled: selectedNodes.length === 0
+ },
+ {type: "separator"},
+ {
+ type: "button",
+ icon: "export",
+ label: "Export to JSON",
+ action: () => {
+ modal.anything("Export result", html`
+ <div style="user-select: all;font-family: monospace; padding: 5px; overflow: auto; background: whitesmoke; max-width:50vw; max-height:50vh">
+ ${exporter.flowToJson(project.toNodeCollection("Exported on " + new Date(), ""))}
+ </div>
+ `);
+ },
+ },
+ ]);
+ return buttons;
+};
diff --git a/ui/component/or-rules/src/flow-viewer/components/writable-dropdown.ts b/ui/component/or-rules/src/flow-viewer/components/writable-dropdown.ts
new file mode 100644
index 000000000..645f01880
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/components/writable-dropdown.ts
@@ -0,0 +1,37 @@
+import { LitElement, customElement, property, html, query, PropertyValues } from "lit-element";
+import { PickerStyle } from "../styles/picker-styles";
+
+@customElement("writable-dropdown")
+export class WritableDropdown extends LitElement {
+ @property({ type: Object, reflect: true }) public value?: any;
+ @property({ type: Array }) public options: { value: any, name: string }[] = [];
+
+ @query("#select-element") public selectElement!: HTMLSelectElement;
+
+ public static get styles() {
+ return PickerStyle;
+ }
+
+ protected firstUpdated() {
+ if (this.options.length > 0 && !this.value) {
+ this.value = this.options[0].value;
+ }
+ this.selectElement.value = this.value;
+ }
+
+ protected shouldUpdate(_changedProperties: PropertyValues) {
+ if (this.selectElement && _changedProperties.has("value")) {
+ this.selectElement.value = this.value;
+ }
+
+ return super.shouldUpdate(_changedProperties);
+ }
+
+ protected render() {
+ return html`
+ <select id="select-element" @change=${(e: Event) => this.dispatchEvent(new Event("onchange", e))} @input=${(e: InputEvent) => { this.dispatchEvent(new InputEvent("oninput", e)); this.value = this.selectElement.value; }}>
+ ${this.options.map((o) => html`<option value="${o.value}">${o.name}</option>`)}
+ </select>
+ `;
+ }
+}
diff --git a/ui/component/or-rules/src/flow-viewer/converters/node-converter.ts b/ui/component/or-rules/src/flow-viewer/converters/node-converter.ts
new file mode 100644
index 000000000..9d110b74d
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/converters/node-converter.ts
@@ -0,0 +1,13 @@
+import { ComplexAttributeConverter } from "lit-element";
+import { Node } from "@openremote/model";
+import { project } from "../components/flow-editor";
+
+export const nodeConverter: ComplexAttributeConverter<unknown, unknown> = {
+ fromAttribute: (value: string) => {
+ return project.nodes.find((n) => n.id === value);
+ },
+
+ toAttribute: (node: Node) => {
+ return node.id;
+ },
+};
diff --git a/ui/component/or-rules/src/flow-viewer/flow-viewer.ts b/ui/component/or-rules/src/flow-viewer/flow-viewer.ts
new file mode 100644
index 000000000..9f9803c71
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/flow-viewer.ts
@@ -0,0 +1,18 @@
+export { FlowEditor } from "./components/flow-editor";
+export { NodePanel } from "./components/node-panel";
+export { EditorWorkspace } from "./components/editor-workspace";
+export { TopBar } from "./components/top-bar";
+export { NodeMenuItem } from "./components/node-menu-item";
+export { SelectableElement } from "./components/selectable-element";
+export { FlowNode } from "./components/flow-node";
+export { FlowNodeSocket } from "./components/flow-node-socket";
+export { ConnectionLine } from "./components/connection-line";
+export { ConnectionContainer } from "./components/connection-container";
+export { SelectionBox } from "./components/selection-box";
+export { ContextMenu } from "./components/context-menu";
+export { InternalPicker } from "./components/internal-picker";
+export { PopupModal } from "./components/popup-modal";
+export { RuleBrowser } from "./components/rule-browser";
+export { WritableDropdown } from "./components/writable-dropdown";
+export { ConfirmationDialog } from "./components/confirmation-dialog";
+export { NotificationDialog } from "./components/notification-dialog";
diff --git a/ui/component/or-rules/src/flow-viewer/models/camera.ts b/ui/component/or-rules/src/flow-viewer/models/camera.ts
new file mode 100644
index 000000000..811351cb3
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/models/camera.ts
@@ -0,0 +1,5 @@
+export interface Camera {
+ x: number;
+ y: number;
+ zoom: number;
+}
diff --git a/ui/component/or-rules/src/flow-viewer/models/context-menu-button.ts b/ui/component/or-rules/src/flow-viewer/models/context-menu-button.ts
new file mode 100644
index 000000000..611ef004d
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/models/context-menu-button.ts
@@ -0,0 +1,15 @@
+export interface ContextMenuEntry {
+ type: "button" | "separator";
+}
+
+export interface ContextMenuButton extends ContextMenuEntry {
+ type: "button";
+ label?: string;
+ icon?: string;
+ action?: () => void;
+ disabled?: boolean;
+}
+
+export interface ContextMenuSeparator extends ContextMenuEntry {
+ type: "separator";
+}
diff --git a/ui/component/or-rules/src/flow-viewer/models/light-node-collection.ts b/ui/component/or-rules/src/flow-viewer/models/light-node-collection.ts
new file mode 100644
index 000000000..7ed661a50
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/models/light-node-collection.ts
@@ -0,0 +1,6 @@
+import { Node, NodeConnection } from "@openremote/model";
+
+export interface LightNodeCollection {
+ nodes: Node[];
+ connections: NodeConnection[];
+}
diff --git a/ui/component/or-rules/src/flow-viewer/models/status.ts b/ui/component/or-rules/src/flow-viewer/models/status.ts
new file mode 100644
index 000000000..1bf86a441
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/models/status.ts
@@ -0,0 +1,6 @@
+export enum Status {
+ Idle,
+ Loading,
+ Success,
+ Failure
+}
diff --git a/ui/component/or-rules/src/flow-viewer/node-structure/copy.machine.ts b/ui/component/or-rules/src/flow-viewer/node-structure/copy.machine.ts
new file mode 100644
index 000000000..b18514f92
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/node-structure/copy.machine.ts
@@ -0,0 +1,42 @@
+import { IdentityAssigner } from "./identity.assigner";
+import { Node, NodeSocket } from "@openremote/model";
+
+export class CopyMachine {
+ public static copy(node: Node): Node {
+ const minimalNode: Node = {};
+
+ minimalNode.inputs = (node.inputs || []).map((i: NodeSocket) => {
+ return {
+ name: i.name, type: i.type
+ };
+ });
+
+ minimalNode.internals = node.internals || [];
+ minimalNode.name = node.name;
+ minimalNode.displayCharacter = node.displayCharacter;
+
+ minimalNode.outputs = (node.outputs || []).map((i) => {
+ return {
+ name: i.name, type: i.type
+ };
+ });
+
+ minimalNode.type = node.type;
+ minimalNode.position = { x: 0, y: 0 };
+ minimalNode.size = { x: 0, y: 0 };
+
+ const clone: Node = JSON.parse(JSON.stringify(minimalNode));
+ clone.id = IdentityAssigner.generateIdentity();
+ clone.inputs!.forEach((socket) => {
+ socket.nodeId = clone.id;
+ socket.id = IdentityAssigner.generateIdentity();
+ });
+
+ clone.outputs!.forEach((socket) => {
+ socket.nodeId = clone.id;
+ socket.id = IdentityAssigner.generateIdentity();
+ });
+
+ return clone;
+ }
+}
diff --git a/ui/component/or-rules/src/flow-viewer/node-structure/identity.assigner.ts b/ui/component/or-rules/src/flow-viewer/node-structure/identity.assigner.ts
new file mode 100644
index 000000000..dcc642ddc
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/node-structure/identity.assigner.ts
@@ -0,0 +1,13 @@
+import ShortID from "shortid";
+import { NodeSocket } from "@openremote/model";
+
+export class IdentityAssigner {
+
+ public static generateIdentity(): string {
+ return ShortID.generate();
+ }
+
+ public static getSocketElementIdentity(socket: NodeSocket) {
+ return socket.id;
+ }
+}
diff --git a/ui/component/or-rules/src/flow-viewer/node-structure/identity.dom.link.ts b/ui/component/or-rules/src/flow-viewer/node-structure/identity.dom.link.ts
new file mode 100644
index 000000000..63e9ae68c
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/node-structure/identity.dom.link.ts
@@ -0,0 +1,3 @@
+export class IdentityDomLink {
+ public static map: { [id: string]: any } = {};
+}
diff --git a/ui/component/or-rules/src/flow-viewer/node-structure/index.ts b/ui/component/or-rules/src/flow-viewer/node-structure/index.ts
new file mode 100644
index 000000000..4de14ca28
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/node-structure/index.ts
@@ -0,0 +1,5 @@
+export { NodeUtilities } from "./utils";
+export { IdentityAssigner } from "./identity.assigner";
+export { IdentityDomLink } from "./identity.dom.link";
+export { SocketTypeMatcher } from "./socket.type.matcher";
+export { CopyMachine } from "./copy.machine";
diff --git a/ui/component/or-rules/src/flow-viewer/node-structure/socket.type.matcher.ts b/ui/component/or-rules/src/flow-viewer/node-structure/socket.type.matcher.ts
new file mode 100644
index 000000000..c18273876
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/node-structure/socket.type.matcher.ts
@@ -0,0 +1,47 @@
+import { NodeDataType } from "@openremote/model";
+
+// TODO this should be defined in the back end
+
+export class SocketTypeMatcher {
+
+ public static match(a: NodeDataType, b: NodeDataType) {
+ return a === NodeDataType.ANY ||
+ b === NodeDataType.ANY ||
+ SocketTypeMatcher.matches.find((t) => t.type === a)!.matches.includes(b);
+ }
+ private static readonly matches: { type: NodeDataType, matches: NodeDataType[] }[] = [
+ {
+ type: NodeDataType.NUMBER,
+ matches: [
+ NodeDataType.NUMBER,
+ NodeDataType.STRING,
+ ]
+ },
+ {
+ type: NodeDataType.STRING,
+ matches: [
+ NodeDataType.STRING,
+ ]
+ },
+ {
+ type: NodeDataType.TRIGGER,
+ matches: [
+ NodeDataType.TRIGGER,
+ ]
+ },
+ {
+ type: NodeDataType.BOOLEAN,
+ matches: [
+ NodeDataType.BOOLEAN,
+ NodeDataType.STRING,
+ ]
+ },
+ {
+ type: NodeDataType.COLOR,
+ matches: [
+ NodeDataType.COLOR,
+ NodeDataType.STRING,
+ ]
+ },
+ ];
+}
diff --git a/ui/component/or-rules/src/flow-viewer/node-structure/utils.ts b/ui/component/or-rules/src/flow-viewer/node-structure/utils.ts
new file mode 100644
index 000000000..393de8fb1
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/node-structure/utils.ts
@@ -0,0 +1,97 @@
+import { Node, ValueType, NodeDataType, NodePosition, NodeConnection, NodeCollection, NodeType } from "@openremote/model";
+
+export class NodeUtilities {
+ public static getNodeFromID(id: string, nodes: Node[]) {
+ const node = nodes.find((n) => n.id === id);
+ if (!node) { console.warn(`Node with ID ${id} not found`); }
+ return node;
+ }
+
+ public static getSocketFromID(id: string, nodes: Node[]) {
+ for (const node of nodes) {
+ for (const input of node.inputs!) {
+ if (input.id === id) { return input; }
+ }
+ for (const output of node.outputs!) {
+ if (output.id === id) { return output; }
+ }
+ }
+ }
+
+ public static convertValueTypeToSocketType(value: ValueType): NodeDataType {
+ switch (value) {
+ case ValueType.BOOLEAN: return NodeDataType.BOOLEAN;
+ case ValueType.NUMBER: return NodeDataType.NUMBER;
+ case ValueType.STRING: return NodeDataType.STRING;
+ default: return NodeDataType.ANY;
+ }
+ }
+
+ public static backtrackFrom(collection: NodeCollection, nodeId: string): Node[] {
+ if (!collection) { throw new Error("Collection has to exist"); }
+ if (!collection.nodes) { throw new Error("Collection has to have existing nodes"); }
+ if (!collection.connections) { throw new Error("Collection has to have existing connections"); }
+
+ const node = this.getNodeFromID(nodeId, collection.nodes);
+
+ if (!node) { throw new Error("Node has to exist"); }
+ if (!node.inputs) { throw new Error("Node has to have existing inputs"); }
+ if (!node.outputs) { throw new Error("Node has to have existing outputs"); }
+
+ let total: Node[] = [];
+ let children: Node[] = [];
+
+ for (const s of node.inputs) {
+ children = children.concat(collection.connections.
+ filter((c) => c.to === s.id).
+ map((c) => this.getNodeFromID(this.getSocketFromID(c.from!, collection.nodes!)!.nodeId!, collection.nodes!)!));
+ }
+
+ for (const child of children) {
+ total.push(child);
+ const result = this.backtrackFrom(collection, child.id!);
+ total = total.concat(result);
+ }
+
+ return total;
+ }
+
+ public static validate(collection: NodeCollection) {
+ if (!collection) { return false; }
+ if (!collection.nodes) { return false; }
+ if (!collection.connections) { return false; }
+ const outputNodes = collection.nodes.filter((n) => n.type === NodeType.OUTPUT);
+ if (outputNodes.length === 0) { return false; }
+
+ for (const output of outputNodes) {
+ const tree = this.backtrackFrom(collection, output.id!);
+ if (tree.length === 0) { return false; }
+ if (tree.filter((n) => n.type === NodeType.INPUT).length === 0) { return false; }
+ }
+
+ return true;
+ }
+
+ public static add(a: NodePosition, b: NodePosition): NodePosition {
+ return { x: a.x! + b.x!, y: a.y! + b.y! };
+ }
+
+ public static subtract(a: NodePosition, b: NodePosition): NodePosition {
+ return { x: a.x! - b.x!, y: a.y! - b.y! };
+ }
+
+ public static multiply(a: NodePosition, b: number): NodePosition {
+ return { x: a.x! * b, y: a.y! * b };
+ }
+
+ public static lerpNumber(x: number, y: number, t: number) {
+ return x * (1 - t) + y * t;
+ }
+
+ public static lerp(a: NodePosition, b: NodePosition, t: number): NodePosition {
+ const x = this.lerpNumber(a.x!, b.x!, t);
+ const y = this.lerpNumber(a.y!, b.y!, t);
+
+ return { x, y };
+ }
+}
diff --git a/ui/component/or-rules/src/flow-viewer/services/copy-paste-manager.ts b/ui/component/or-rules/src/flow-viewer/services/copy-paste-manager.ts
new file mode 100644
index 000000000..d8bcce22b
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/services/copy-paste-manager.ts
@@ -0,0 +1,72 @@
+import { Node, NodeConnection, NodePosition } from "@openremote/model";
+import { LightNodeCollection } from "../models/light-node-collection";
+import { IdentityAssigner } from "../node-structure";
+import { input } from "../components/flow-editor";
+import { FlowNode, ConnectionLine } from "../flow-viewer";
+
+export class CopyPasteManager {
+ private clipboard!: LightNodeCollection;
+ private copyOrigin!: NodePosition;
+
+ public get isFull() { return !!!this.clipboard; }
+
+ public putInClipboard(obj: LightNodeCollection, origin: NodePosition) {
+ this.copyOrigin = origin;
+ this.clipboard = obj;
+ }
+
+ public getFromClipboard(newOrigin: NodePosition) {
+ const clone = this.cloneIsolated(this.clipboard, 0);
+ const offset = {
+ x: newOrigin.x! - this.copyOrigin.x!,
+ y: newOrigin.y! - this.copyOrigin.y!,
+ };
+ clone.nodes.forEach((node) => {
+ node.position!.x! += offset.x;
+ node.position!.y! += offset.y;
+ });
+ return clone;
+ }
+
+ public cloneIsolated(obj: LightNodeCollection, positionOffset = 50) {
+ const remapped: { [id: string]: string } = {};
+
+ const clone: LightNodeCollection = JSON.parse(JSON.stringify(obj));
+
+ clone.nodes.forEach((node: Node) => {
+ const newNodeID = IdentityAssigner.generateIdentity();
+ remapped[node.id!] = newNodeID;
+ node.position!.x! += positionOffset;
+ node.position!.y! += positionOffset;
+ node.id = newNodeID;
+ node.inputs!.forEach((inputSocket) => {
+ const newSocketID = IdentityAssigner.generateIdentity();
+ remapped[inputSocket.id!] = newSocketID;
+ inputSocket.id = newSocketID;
+ inputSocket.nodeId = newNodeID;
+ });
+ node.outputs!.forEach((outputSocket) => {
+ const newSocketID = IdentityAssigner.generateIdentity();
+ remapped[outputSocket.id!] = newSocketID;
+ outputSocket.id = newSocketID;
+ outputSocket.nodeId = newNodeID;
+ });
+ });
+
+ clone.connections.forEach((connection: NodeConnection) => {
+ connection.from = remapped[connection.from!];
+ connection.to = remapped[connection.to!];
+ });
+
+ return clone;
+ }
+
+ public copy(x: number, y: number) {
+ const selectedNodes = input.selected.filter((s) => s instanceof FlowNode && s.selected) as FlowNode[];
+ const selectedConnections = input.selected.filter((s) => s instanceof ConnectionLine && s.selected) as ConnectionLine[];
+ this.putInClipboard({
+ nodes: selectedNodes.map((n) => n.node),
+ connections: selectedConnections.map((c) => c.connection)
+ }, { x, y });
+ }
+}
diff --git a/ui/component/or-rules/src/flow-viewer/services/exporter.ts b/ui/component/or-rules/src/flow-viewer/services/exporter.ts
new file mode 100644
index 000000000..5ad660ca2
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/services/exporter.ts
@@ -0,0 +1,73 @@
+import { NodeCollection, GlobalRuleset, RulesetLang, Ruleset } from "@openremote/model";
+import manager from "@openremote/core";
+import { project, modal } from "../components/flow-editor";
+
+export class Exporter {
+ public flowToJson(collection: NodeCollection) {
+ return JSON.stringify(collection);
+ }
+
+ public jsonToFlow(json: string): NodeCollection {
+ return JSON.parse(json);
+ }
+
+ public collectionToRuleset(collection: NodeCollection, type: "global" | "asset" | "tenant") {
+ const ruleset: Ruleset = {
+ lang: RulesetLang.FLOW,
+ name: collection.name,
+ type,
+ rules: this.flowToJson(collection),
+ };
+ return ruleset;
+ }
+
+ public rulesetToCollection(ruleset: Ruleset) {
+ return this.jsonToFlow(ruleset.rules!);
+ }
+
+ public exportAsNew(collection: NodeCollection) {
+ const json = this.flowToJson(collection);
+ const ruleApi = manager.rest.api.RulesResource;
+
+ const rs: GlobalRuleset = {
+ lang: RulesetLang.FLOW,
+ name: collection.name,
+ type: "global",
+ rules: json
+ };
+
+ ruleApi.createGlobalRuleset(rs).then((e) => {
+ if (e.status === 200) {
+ project.setCurrentProject(e.data, collection.name!, collection.description!);
+ console.log("Successfully saved new ruleset");
+ } else {
+ console.log("Something went wrong while saving NEW ruleset\nHTTP status " + e.status);
+ modal.notification("Failure", `Something went wrong while saving ${rs.name}`);
+ }
+ }).catch((e) => {
+ console.log("Something went wrong while saving NEW ruleset\nHTTP status " + e);
+ modal.notification("Failure", `Something went wrong while saving ${rs.name}`);
+ });
+ }
+
+ public exportAsExisting(id: number, collection: NodeCollection) {
+ const json = this.flowToJson(collection);
+ const ruleApi = manager.rest.api.RulesResource;
+ ruleApi.getGlobalRuleset(project.existingFlowRuleId).then((response) => {
+ const existing = response.data;
+ existing.rules = json;
+ ruleApi.updateGlobalRuleset(existing.id!, existing).then((e: any) => {
+ if (e.status === 204) {
+ project.unsavedState = false;
+ console.log("Successfully saved ruleset");
+ } else {
+ console.log("Something went wrong while saving EXISTING ruleset\n" + e.status);
+ modal.notification("Failure", `Something went wrong while saving ${collection.name}`);
+ }
+ });
+ }).catch((e) => {
+ console.log("Something went wrong while saving EXISTING ruleset\n" + e);
+ modal.notification("Failure", `Something went wrong while saving ${collection.name}`);
+ });
+ }
+}
diff --git a/ui/component/or-rules/src/flow-viewer/services/input.ts b/ui/component/or-rules/src/flow-viewer/services/input.ts
new file mode 100644
index 000000000..a5cf120c2
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/services/input.ts
@@ -0,0 +1,78 @@
+import { EventEmitter } from "events";
+import { SelectableElement } from "../components/selectable-element";
+import { project } from "../components/flow-editor";
+
+export class Input extends EventEmitter {
+ public selected: SelectableElement[] = [];
+ public selectables: SelectableElement[] = [];
+ private keysCurrentlyHeld: string[] = [];
+
+ constructor() {
+ super();
+ window.addEventListener("keydown", this.onkeydown);
+ window.addEventListener("keyup", this.onkeyup);
+ window.addEventListener("blur", () => {
+ this.clearSelection();
+ this.keysCurrentlyHeld = [];
+ });
+ project.addListener("cleared", () => { this.clearSelection(); });
+ this.setMaxListeners(1024);
+ }
+
+ public select(element: SelectableElement, forceMultipleSelection = false) {
+ if (!this.multiSelectedEnabled && !forceMultipleSelection) { this.clearSelection(); }
+ if (this.selected.includes(element)) { return; }
+ this.emit("selected", element);
+ if (element.selected) {
+ this.selected.push(element);
+ }
+ }
+
+ public deselect(element: SelectableElement) {
+ const index = this.selected.indexOf(element);
+ if (index === -1) {
+ console.warn("Attempt to deselect nonexistent node");
+ return;
+ }
+ this.emit("deselected", element);
+ if (!element.selected) {
+ this.selected.splice(index, 1);
+ }
+ }
+
+ public handleSelection(element: SelectableElement, neverDeselect = false) {
+ if (!this.multiSelectedEnabled && this.selected.length > 1) {
+ this.select(element);
+ } else if (this.selected.includes(element) && !neverDeselect) {
+ this.deselect(element);
+ } else {
+ this.select(element);
+ }
+ }
+
+ public clearSelection(ignoreMultiselect = false) {
+ if (this.multiSelectedEnabled && !ignoreMultiselect) { return; }
+ this.selected.forEach((e) => this.emit("deselected", e));
+ this.selected = [];
+ this.emit("selectioncleared");
+ }
+
+ public isHeld(key: string) {
+ return this.keysCurrentlyHeld.includes(key);
+ }
+
+ public get multiSelectedEnabled() {
+ return this.isHeld("Shift") || this.isHeld("Control");
+ }
+
+ private onkeydown = (e: KeyboardEvent) => {
+ if (this.keysCurrentlyHeld.includes(e.key)) { return; }
+ this.keysCurrentlyHeld.push(e.key);
+ }
+
+ private onkeyup = (e: KeyboardEvent) => {
+ const index = this.keysCurrentlyHeld.indexOf(e.key);
+ if (index === -1) { return; }
+ this.keysCurrentlyHeld.splice(index, 1);
+ }
+}
diff --git a/ui/component/or-rules/src/flow-viewer/services/integration.ts b/ui/component/or-rules/src/flow-viewer/services/integration.ts
new file mode 100644
index 000000000..b389e30e7
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/services/integration.ts
@@ -0,0 +1,15 @@
+import rest from "@openremote/rest";
+import { Node } from "@openremote/model";
+import { EventEmitter } from "events";
+
+export class Integration extends EventEmitter {
+ public nodes: Node[] = [];
+
+ public async refreshNodes() {
+ this.nodes = [];
+ const allNodes = (await rest.api.FlowResource.getAllNodeDefinitions()).data;
+ for (const n of allNodes) {
+ this.nodes.push(n);
+ }
+ }
+}
diff --git a/ui/component/or-rules/src/flow-viewer/services/modal.ts b/ui/component/or-rules/src/flow-viewer/services/modal.ts
new file mode 100644
index 000000000..ba4f6d159
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/services/modal.ts
@@ -0,0 +1,32 @@
+import { PopupModal } from "../components/popup-modal";
+import { html, TemplateResult } from "lit-element";
+import { i18next } from "@openremote/or-translate";
+
+export class ModalService {
+ public element!: PopupModal;
+
+ public confirmation(agreeCallback: () => void, header: string = i18next.t("flowEditor", "Flow editor"), question: string = i18next.t("areYouSure", "Are you sure?")) {
+ this.element.content = html`<confirmation-dialog
+ .question = "${question}"
+ @agreed="${() => { if (agreeCallback) { agreeCallback(); } this.element.close(); }}"
+ @disagreed="${this.element.close}"
+ ></confirmation-dialog>`;
+ this.element.header = header;
+ this.element.open();
+ }
+
+ public notification(header: string, message: string, buttonText: string = i18next.t("ok", "OK")) {
+ this.element.content = html`<notification-dialog
+ .message = "${message}"
+ @closed = "${this.element.close}"
+ ></notification-dialog>`;
+ this.element.header = header;
+ this.element.open();
+ }
+
+ public anything(header: string, content: TemplateResult){
+ this.element.content = content;
+ this.element.header = header;
+ this.element.open();
+ }
+}
diff --git a/ui/component/or-rules/src/flow-viewer/services/project.ts b/ui/component/or-rules/src/flow-viewer/services/project.ts
new file mode 100644
index 000000000..fc654b542
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/services/project.ts
@@ -0,0 +1,225 @@
+import { Node, NodeConnection, NodeSocket, NodeCollection, RulesetUnion } from "@openremote/model";
+import { EventEmitter } from "events";
+import { SocketTypeMatcher, NodeUtilities } from "../node-structure";
+import { EditorWorkspace } from "../components/editor-workspace";
+import { input } from "../components/flow-editor";
+
+export class Project extends EventEmitter {
+ public nodes: Node[] = [];
+ public connections: NodeConnection[] = [];
+ public workspace!: EditorWorkspace;
+
+ public existingFlowRuleId = -1;
+ public existingFlowRuleName: string | null = null;
+ public existingFlowRuleDesc: string | null = null;
+ private isInUnsavedState = false;
+
+ private isConnecting = false;
+ private connectionStartSocket!: NodeSocket | null;
+ private connectionEndSocket!: NodeSocket | null;
+
+ private history: NodeCollection[] = [];
+ private historyIndex = 0;
+
+ constructor() {
+ super();
+ this.setMaxListeners(1024);
+ }
+
+ public get isCurrentlyConnecting() {
+ return this.isConnecting;
+ }
+
+ public set unsavedState(state: boolean) {
+ this.isInUnsavedState = state;
+ this.emit("unsavedstateset", state);
+ }
+
+ public get unsavedState() {
+ return this.isInUnsavedState;
+ }
+
+ public setCurrentProject(id: number, name: string | null, desc: string | null) {
+ this.unsavedState = false;
+ this.existingFlowRuleId = id;
+ this.existingFlowRuleName = name;
+ this.existingFlowRuleDesc = desc;
+ this.history = [];
+ this.emit("projectset", id);
+ }
+
+ public notifyChange() {
+ this.unsavedState = true;
+ this.emit("changed");
+ }
+
+ public createUndoSnapshot() {
+ this.history = this.history.splice(0, this.historyIndex + 1);
+ this.history.push(JSON.parse(JSON.stringify(this.toNodeCollection("", ""))));
+ this.historyIndex = this.history.length - 1;
+ }
+
+ public async undo() {
+ if (this.history.length === 0 || this.historyIndex === -1) { return; }
+ if (this.historyIndex === this.history.length - 1) {
+ this.history.push(JSON.parse(JSON.stringify(this.toNodeCollection("", ""))));
+ }
+ await this.fromNodeCollection(this.history[this.historyIndex]);
+ this.historyIndex--;
+ this.notifyChange();
+ }
+
+ public async redo() {
+ if (this.history.length === 0 || this.historyIndex >= (this.history.length - 2)) { return; }
+ this.historyIndex++;
+ await this.fromNodeCollection(this.history[this.historyIndex + 1]);
+ this.notifyChange();
+ }
+
+ public async fromNodeCollection(collection: NodeCollection) {
+ await this.clear();
+ collection.nodes!.forEach((node) => {
+ this.addNode(node);
+ });
+ await this.workspace.updateComplete;
+ collection.connections!.forEach((conn) => {
+ this.createConnection(conn.from!, conn.to!);
+ });
+ this.emit("nodecollectionloaded", collection);
+ this.unsavedState = false;
+ }
+
+ public toNodeCollection(name: string, description: string): NodeCollection {
+ return {
+ name,
+ description,
+ connections: this.connections,
+ nodes: this.nodes
+ };
+ }
+
+ public async clear(alsoResetProject = false) {
+ input.clearSelection();
+ this.nodes.forEach((n) => {
+ this.removeNode(n);
+ });
+ if (this.workspace) {
+ await this.workspace.updateComplete;
+ }
+ this.nodes = [];
+ this.connections = [];
+ this.unsavedState = !alsoResetProject;
+ if (alsoResetProject) {
+ this.setCurrentProject(-1, null, null);
+ }
+ this.emit("cleared");
+ }
+
+ public addNode(node: Node) {
+ if (this.nodes.filter((n) => n.id === node.id).length > 0) {
+ throw new Error("Node with identical identity already exists in the project");
+ }
+ this.nodes.push(node);
+ this.emit("nodeadded", node);
+ }
+
+ public removeNode(node: Node) {
+ input.clearSelection();
+ this.connections.filter((c) => {
+ const from = NodeUtilities.getSocketFromID(c.from!, this.nodes);
+ const to = NodeUtilities.getSocketFromID(c.to!, this.nodes);
+ return from!.nodeId === node.id || to!.nodeId === node.id;
+ }).forEach((c) => {
+ this.removeConnection(c);
+ });
+ this.nodes.filter((n) => n.id === node.id).forEach((n) => {
+ this.nodes.splice(this.nodes.indexOf(n), 1);
+ this.emit("noderemoved", n);
+ });
+ }
+
+ public startConnectionDrag = (e: MouseEvent, socket: NodeSocket, isInputNode: boolean) => {
+ this.connectionStartSocket = null;
+ this.connectionEndSocket = null;
+
+ if (isInputNode) {
+ this.connectionEndSocket = socket;
+ } else {
+ this.connectionStartSocket = socket;
+ }
+
+ this.isConnecting = true;
+ this.emit("connectionstart", e, socket);
+ }
+
+ public connectionDragging = (e: MouseEvent) => {
+ this.emit("connecting", e);
+ }
+
+ public endConnectionDrag = (e: MouseEvent, socket: NodeSocket | null, isInputNode: boolean) => {
+ if (!this.isConnecting) { return; }
+ if (isInputNode) {
+ this.connectionEndSocket = socket;
+ } else {
+ this.connectionStartSocket = socket;
+ }
+
+ this.isConnecting = false;
+ this.emit("connectionend", e, socket);
+ if (this.connectionEndSocket && this.connectionStartSocket) {
+ this.createConnection(this.connectionStartSocket.id!, this.connectionEndSocket.id!);
+ }
+ }
+
+ public removeConnection(connection: NodeConnection) {
+ input.clearSelection();
+ this.connections.filter((c) => c.from === connection.from && c.to === connection.to).forEach((c) => {
+ const index = this.connections.indexOf(c);
+ if (index === -1) {
+ console.warn("attempt to delete nonexistent connection");
+ } else {
+ this.connections.splice(index, 1);
+ this.emit("connectionremoved", c);
+ }
+ });
+ }
+
+ public isValidConnection(connection: NodeConnection) {
+ const fromSocket = NodeUtilities.getSocketFromID(connection.from!, this.nodes);
+ const toSocket = NodeUtilities.getSocketFromID(connection.to!, this.nodes);
+ if (!fromSocket ||
+ !toSocket) {
+ return false;
+ }
+
+ if (!SocketTypeMatcher.match(fromSocket.type!, toSocket.type!) ||
+ fromSocket.id === toSocket.id ||
+ fromSocket.nodeId === toSocket.nodeId) {
+ return false;
+ }
+ return true;
+ }
+
+ public createConnection(fromSocket: string, toSocket: string): boolean {
+ const connection = {
+ from: fromSocket,
+ to: toSocket
+ };
+
+ if (!this.isValidConnection(connection)) { return false; }
+
+ for (const c of this.connections.filter((j) => j.to === toSocket)) {
+ this.removeConnection(c);
+ }
+
+ this.connections.push(connection);
+ this.emit("connectioncreated", fromSocket, toSocket);
+ return true;
+ }
+
+ public removeInvalidConnections() {
+ for (const c of this.connections.filter((j) => !this.isValidConnection(j))) {
+ this.removeConnection(c);
+ }
+ }
+}
diff --git a/ui/component/or-rules/src/flow-viewer/services/shortcuts.ts b/ui/component/or-rules/src/flow-viewer/services/shortcuts.ts
new file mode 100644
index 000000000..a4d068920
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/services/shortcuts.ts
@@ -0,0 +1,57 @@
+import { FlowNode } from "../components/flow-node";
+import { ConnectionLine } from "../components/connection-line";
+import { input, project } from "../components/flow-editor";
+
+export class Shortcuts {
+ public actions: { keys: string[], requireCtrl?: boolean, action: () => void }[] = [
+ {
+ keys: ["Delete", "Backspace"],
+ action: () => {
+ project.createUndoSnapshot();
+ const selectedNodes = input.selected.filter((s) => s instanceof FlowNode && s.selected && !s.frozen) as FlowNode[];
+ const selectedConnections = input.selected.filter((s) => s instanceof ConnectionLine && s.selected) as ConnectionLine[];
+ selectedConnections.forEach((n) => project.removeConnection(n.connection));
+ selectedNodes.forEach((n) => project.removeNode(n.node));
+ project.notifyChange();
+ }
+ },
+ {
+ keys: ["KeyA"],
+ requireCtrl: true,
+ action: () => {
+ if (input.selected.length > 0) {
+ input.clearSelection(true);
+ } else {
+ input.selectables.forEach((s) => {
+ input.select(s, true);
+ });
+ }
+ }
+ },
+ {
+ keys: ["KeyZ"],
+ requireCtrl: true,
+ action: () => {
+ project.undo();
+ }
+ },
+ {
+ keys: ["KeyY"],
+ requireCtrl: true,
+ action: () => {
+ project.redo();
+ }
+ }
+ ];
+
+ constructor() {
+ window.addEventListener("keydown", (e: KeyboardEvent) => {
+ if (!(document.activeElement instanceof HTMLBodyElement)) { return; }
+ this.actions.forEach((a) => {
+ if (!a.keys.includes(e.key) && !a.keys.includes(e.code)) { return; }
+ if (a.requireCtrl && !e.ctrlKey) { return; }
+ a.action();
+ });
+ });
+ }
+}
diff --git a/ui/component/or-rules/src/flow-viewer/styles/editor-workspace-style.ts b/ui/component/or-rules/src/flow-viewer/styles/editor-workspace-style.ts
new file mode 100644
index 000000000..5b469d071
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/styles/editor-workspace-style.ts
@@ -0,0 +1,55 @@
+import { css } from "lit-element";
+
+export const EditorWorkspaceStyle = css`
+:host{
+ background: whitesmoke;
+ position: relative;
+ display: block;
+ overflow: hidden;
+ box-shadow: rgba(0, 0, 0, 0.2) 0 0 4px inset;
+ height: 100%;
+}
+
+.view-options{
+ position: absolute;
+ left: 0;
+ top: 0;
+ display: flex;
+ flex-direction: row;
+}
+
+.button{
+ padding: 10px;
+ margin: 10px;
+ cursor:pointer;
+ background: rgba(0,0,0,0.02);
+}
+
+or-input[type=button]
+{
+ margin: 10px;
+ color: inherit;
+}
+
+.button:hover{
+ background: rgba(0,0,0,0.04);
+}
+
+.button:active{
+ background: rgba(0,0,0,0.06);
+}
+
+svg, connection-container {
+ pointer-events: none;
+ position: absolute;
+ display: block;
+ right: 0;
+ top: 0;
+ left: 0;
+ bottom: 0;
+ width: 100%;
+ height: 100%;
+ stroke-width: 4px;
+ stroke: rgb(80,80,80);
+}
+`;
diff --git a/ui/component/or-rules/src/flow-viewer/styles/flow-node-style.ts b/ui/component/or-rules/src/flow-viewer/styles/flow-node-style.ts
new file mode 100644
index 000000000..414ef10fd
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/styles/flow-node-style.ts
@@ -0,0 +1,103 @@
+import { css } from "lit-element";
+
+export const FlowNodeStyle = css`
+:host{
+ white-space: nowrap;
+ min-width: 80px;
+ min-height: 80px;
+ background: rgba(200,200,200, 0.85);
+
+ display: grid;
+ grid-template-columns: auto auto auto;
+ grid-template-rows: auto 1fr;
+ grid-template-areas:
+ "title title title"
+ "input internal output";
+
+ position: absolute;
+ border-radius: var(--roundness);
+ transform-origin: 0 0;
+ z-index: 0;
+}
+:host([minimal]){
+ min-width: 60px;
+ min-height: 60px;
+ grid-template-columns: var(--socket-display-size) 1fr var(--socket-display-size);
+ grid-template-rows: auto;
+ grid-template-areas:
+ "input title output";
+}
+.internal-container{
+ grid-area: internal;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ padding: 8px 0 8px 0;
+}
+.socket-side{
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ justify-content: space-evenly;
+}
+.inputs{
+ grid-area: input;
+ align-items: flex-start;
+}
+.inputs flow-node-socket{
+ transform: translateX(calc(var(--socket-size) / -2));
+}
+.outputs{
+ grid-area: output;
+ align-items: flex-end;
+}
+.outputs flow-node-socket{
+ transform: translateX(calc(var(--socket-size) / 2));
+}
+.title{
+ grid-area: title;
+ padding: 3px 6px 3px 6px;
+ background: rgb(180,180,180);
+ border-radius: inherit;
+ border-bottom-left-radius: 0;
+ border-bottom-right-radius: 0;
+ color: white;
+ cursor: grab;
+}
+.title.input{
+ background: var(--input-color);
+ text-align: right;
+}
+.title.processor{
+ background: var(--processor-color);
+ text-align: center;
+}
+.title.output{
+ background: var(--output-color);
+ text-align: left;
+}
+.title.minimal{
+ background: transparent;
+ font-size: 20px;
+ line-height: 50%;
+ display: table;
+ padding: 15px 0 15px 0;
+ text-align: center;
+ margin-top: auto;
+ margin-bottom: auto;
+}
+.title.minimal[singlechar]{
+ font-size: 32px;
+}
+.lock-icon{
+ position: absolute;
+ top: 0px;
+ right: 0px;
+ color: rgba(255,255,255,0.8);
+ transform: scale(.7);
+}
+.lock-icon.input{
+ left: 0;
+}
+`;
diff --git a/ui/component/or-rules/src/flow-viewer/styles/picker-styles.ts b/ui/component/or-rules/src/flow-viewer/styles/picker-styles.ts
new file mode 100644
index 000000000..a791456de
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/styles/picker-styles.ts
@@ -0,0 +1,19 @@
+import { css } from "lit-element";
+
+export const PickerStyle = css`
+input{
+ border: 0;
+}
+textarea{
+ min-width: 150px;
+ min-height: 37px;
+}
+textarea, input[type=text], input[type=number], select
+{
+ font-family: inherit;
+ padding: 10px;
+ border-radius: var(--roundness);
+ width: auto;
+ border: none;
+}
+`;
diff --git a/ui/component/or-rules/src/flow-viewer/utils.ts b/ui/component/or-rules/src/flow-viewer/utils.ts
new file mode 100644
index 000000000..8333bbf07
--- /dev/null
+++ b/ui/component/or-rules/src/flow-viewer/utils.ts
@@ -0,0 +1,51 @@
+export class Utilities {
+ public static getCenter(bounds: ClientRect) {
+ return {
+ x: bounds.left + bounds.width / 2,
+ y: bounds.top + bounds.height / 2
+ };
+ }
+
+ public static isPointInsideBox(x: number, y: number, box: { x: number, y: number, width: number, height: number }) {
+ return (x > box.x) && (x < box.x + box.width) && (y > box.y) && (y < box.y + box.height);
+ }
+
+ public static isBoxInsideBox(a: { x: number, y: number, width: number, height: number }, b: { x: number, y: number, width: number, height: number }) {
+ const deltaX = b.x - a.x;
+ const deltaY = b.y - a.y;
+
+ return a.x >= b.x && (a.width - deltaX <= b.width) &&
+ a.y >= b.y && (a.height - deltaY <= b.height);
+ }
+
+ public static humanLike(input: string) {
+ input = input.replace(/_+/gm, " ");
+ let n = input[0].toUpperCase();
+ for (let i = 1; i < input.length; i++) {
+ const character = input[i];
+ if (character.match("[A-z]") && character === character.toUpperCase() && input[i - 1].trim().length !== 0) {
+ n += " ";
+ }
+ n += character.toLowerCase();
+ }
+ return n;
+ }
+
+ public static ellipsis(input: string, maxLength = 15, ellipsis = "...") {
+ if (!input || !maxLength || !ellipsis) { return input; }
+ if (ellipsis.length > maxLength) {
+ console.warn("Invalid ellipsis parameters: given ellipsis is longer than the max length");
+ return input;
+ }
+ if (input.length < maxLength) {
+ return input;
+ }
+ if (!input) {
+ return "";
+ }
+ if (input.length > 8) {
+ return input.substr(0, maxLength - ellipsis.length) + ellipsis;
+ }
+ return input;
+ }
+}
diff --git a/ui/component/or-rules/src/index.ts b/ui/component/or-rules/src/index.ts
index 3d18a496d..cc8de5558 100644
--- a/ui/component/or-rules/src/index.ts
+++ b/ui/component/or-rules/src/index.ts
@@ -31,9 +31,11 @@ import {
ClientRole
} from "@openremote/model";
import "@openremote/or-translate";
+import "@openremote/or-mwc-components/dist/or-mwc-drawer";
import {translate} from "@openremote/or-translate";
import "./or-rule-list";
import "./or-rule-viewer";
+import "./flow-viewer/flow-viewer";
import {OrRuleList} from "./or-rule-list";
import {OrRuleViewer} from "./or-rule-viewer";
@@ -581,7 +583,7 @@ export class OrRules extends translate(i18next)(LitElement) {
protected render() {
return html`
- <or-rule-list id="rule-list" .realm="${this.realm}" .config="${this.config}" .language="${this.language}" .selectedIds="${this.selectedIds}"></or-rule-list>
+ <or-rule-list id="rule-list" .config="${this.config}" .language="${this.language}" .selectedIds="${this.selectedIds}"></or-rule-list>
<or-rule-viewer id="rule-viewer" .ruleset="${this._activeRuleset}" .config="${this.config}" .readonly="${this.isReadonly()}"></or-rule-viewer>
`;
}
@@ -599,7 +601,7 @@ export class OrRules extends translate(i18next)(LitElement) {
}
const name = this.config && this.config.rulesetName ? this.config.rulesetName : OrRules.DEFAULT_RULESET_NAME;
- const realm = this._rulesList.realm;
+ const realm = manager.isSuperUser() ? manager.displayRealm : manager.config.realm;
const ruleset: TenantRuleset = {
id: 0,
diff --git a/ui/component/or-rules/src/or-rule-list.ts b/ui/component/or-rules/src/or-rule-list.ts
index 636839f2e..eb3794efa 100644
--- a/ui/component/or-rules/src/or-rule-list.ts
+++ b/ui/component/or-rules/src/or-rule-list.ts
@@ -49,6 +49,11 @@ const style = css`
display: none;
}
+ .node-language{
+ padding-left: 10px;
+ opacity: 50%;
+ }
+
.bg-green {
background-color: #28b328;
}
@@ -69,14 +74,11 @@ const style = css`
@customElement("or-rule-list")
export class OrRuleList extends translate(i18next)(LitElement) {
- public static DEFAULT_ALLOWED_LANGUAGES = [RulesetLang.JSON, RulesetLang.GROOVY, RulesetLang.JAVASCRIPT];
+ public static DEFAULT_ALLOWED_LANGUAGES = [RulesetLang.JSON, RulesetLang.GROOVY, RulesetLang.JAVASCRIPT, RulesetLang.FLOW];
@property({type: Object})
public config?: RulesConfig;
- @property({type: String})
- public realm?: string;
-
@property({type: Boolean})
public readonly: boolean = false;
@@ -95,9 +97,6 @@ export class OrRuleList extends translate(i18next)(LitElement) {
@property({type: String})
public language?: RulesetLang;
- @property({attribute: false})
- protected _realms?: Tenant[];
-
@property({attribute: false})
protected _nodes?: RulesetNode[];
@@ -119,6 +118,11 @@ export class OrRuleList extends translate(i18next)(LitElement) {
this._nodes = undefined;
}
+ public disconnectedCallback() {
+ super.disconnectedCallback();
+ manager.removeListener(this.onManagerEvent);
+ }
+
protected get _allowedLanguages(): RulesetLang[] | undefined {
return this.config && this.config.controls && this.config.controls.allowedLanguages ? this.config.controls.allowedLanguages : OrRuleList.DEFAULT_ALLOWED_LANGUAGES;
}
@@ -134,24 +138,27 @@ export class OrRuleList extends translate(i18next)(LitElement) {
protected _onReady() {
this._ready = true;
- this._loadRealms();
this._loadRulesets();
}
protected firstUpdated(_changedProperties: PropertyValues): void {
super.firstUpdated(_changedProperties);
+ manager.addListener(this.onManagerEvent);
+ if (manager.ready) {
+ this._onReady();
+ }
+ }
- if (!manager.ready) {
- // Defer until openremote is initialised
- this._initCallback = (initEvent: OREvent) => {
- if (initEvent === OREvent.READY) {
+ protected onManagerEvent = (event: OREvent) => {
+ switch (event) {
+ case OREvent.READY:
+ if (!manager.ready) {
this._onReady();
- manager.removeListener(this._initCallback!);
}
- };
- manager.addListener(this._initCallback);
- } else {
- this._onReady();
+ break;
+ case OREvent.DISPLAY_REALM_CHANGED:
+ this._nodes = undefined;
+ break;
}
}
@@ -167,10 +174,6 @@ export class OrRuleList extends translate(i18next)(LitElement) {
}
if (manager.ready) {
- if (_changedProperties.has("realm")) {
- this._nodes = undefined;
- }
-
if (!this._nodes) {
this._loadRulesets();
return true;
@@ -196,13 +199,6 @@ export class OrRuleList extends translate(i18next)(LitElement) {
}
protected render() {
-
- const realm = this._getRealm();
-
- if (this.realm !== realm) {
- this._onRealmChanged(realm);
- }
-
if (!this.language) {
this._updateLanguage();
}
@@ -223,13 +219,11 @@ export class OrRuleList extends translate(i18next)(LitElement) {
addTemplate = html`<or-input type="${InputType.BUTTON}" icon="plus" @click="${() => this._onAddClicked(this.language!)}"></or-input>`;
}
}
-
return html`
<div id="wrapper" ?data-disabled="${this.disabled}">
<div id="header">
<div id="title-container">
<or-translate id="title" value="rule_plural"></or-translate>
- ${manager.isSuperUser() ? html `<or-input id="realm-picker" type="${InputType.SELECT}" .value="${this._getRealm()}" .options="${this._realms ? this._realms.map((tenant) => [tenant.realm, tenant.displayName]) : []}" @or-input-changed="${(evt: OrInputChangedEvent) => this._onRealmChanged(evt.detail.value)}"></or-input>` : ``}
</div>
<div id="header-btns">
@@ -239,24 +233,24 @@ export class OrRuleList extends translate(i18next)(LitElement) {
<or-input hidden type="${InputType.BUTTON}" icon="magnify" @click="${() => this._onSearchClicked()}"></or-input>
${getContentWithMenuTemplate(
- html`<or-input type="${InputType.BUTTON}" icon="sort-variant"></or-input>`,
- ["name", "createdOn"].map((sort) => { return {value: sort, text: i18next.t(sort)} as MenuItem; }),
- this.sortBy,
- (v) => this._onSortClicked(v as string))}
+ html`<or-input type="${InputType.BUTTON}" icon="sort-variant"></or-input>`,
+ ["name", "createdOn", "lang"].map((sort) => { return { value: sort, text: i18next.t(sort) } as MenuItem; }),
+ this.sortBy,
+ (v) => this._onSortClicked(v as string))}
</div>
</div>
${!this._nodes || this._showLoading
- ? html`
- <span id="loading">LOADING</span>`
- : html`
+ ? html`
+ <span id="loading">LOADING</span>`
+ : html`
<div id="list-container">
<ol id="list">
${this._nodes.map((treeNode) => this._nodeTemplate(treeNode))}
</ol>
</div>
`
- }
+ }
<div id="footer">
@@ -274,7 +268,7 @@ export class OrRuleList extends translate(i18next)(LitElement) {
<li ?data-selected="${node.selected}" @click="${(evt: MouseEvent) => this._onNodeClicked(evt, node)}">
<div class="node-container">
<span class="node-status ${OrRuleList._getNodeStatusClasses(node.ruleset)}"></span>
- <span class="node-name">${node.ruleset.name}</span>
+ <span class="node-name">${node.ruleset.name}<span class="node-language">${node.ruleset.lang}</span></span>
</div>
</li>
`;
@@ -283,40 +277,38 @@ export class OrRuleList extends translate(i18next)(LitElement) {
protected static _getNodeStatusClasses(ruleset: TenantRuleset): string {
let status = ruleset.enabled ? "bg-green" : "bg-red";
- if(ruleset.rules && ruleset.enabled) {
- const rule: JsonRule = JSON.parse(ruleset.rules).rules[0];
-
- // HACK/WIP: the status of a rule should be better thought over see issue #95
- // currently only checks the date of the first whenCondition
- if(rule && rule.when && rule.when.items && rule.when.items.length > 0) {
- const ruleCondition: RuleCondition = rule.when.items[0];
- if(ruleCondition.datetime) {
- const today = moment();
- const startDate = ruleCondition.datetime.value;
- const endDate = ruleCondition.datetime.rangeValue;
-
- if (today.diff(startDate) < 0) {
- // before startDate, show blue
- status = "bg-blue";
- } else if (today.diff(endDate) > 0) {
- // after endDate, show grey
- status = "bg-grey";
+ if (ruleset.rules && ruleset.enabled) {
+ switch (ruleset.lang) {
+ case RulesetLang.JSON:
+ const rule: JsonRule = JSON.parse(ruleset.rules).rules[0];
+
+ // HACK/WIP: the status of a rule should be better thought over see issue #95
+ // currently only checks the date of the first whenCondition
+ if (rule && rule.when && rule.when.items && rule.when.items.length > 0) {
+ const ruleCondition: RuleCondition = rule.when.items[0];
+ if (ruleCondition.datetime) {
+ const today = moment();
+ const startDate = ruleCondition.datetime.value;
+ const endDate = ruleCondition.datetime.rangeValue;
+
+ if (today.diff(startDate) < 0) {
+ // before startDate, show blue
+ status = "bg-blue";
+ } else if (today.diff(endDate) > 0) {
+ // after endDate, show grey
+ status = "bg-grey";
+ }
+ }
}
- }
+ break;
+ default:
+ break;
}
}
return status;
}
- protected _loadRealms() {
- if (manager.isSuperUser()) {
- manager.rest.api.TenantResource.getAll().then((response) => {
- this._realms = response.data;
- });
- }
- }
-
protected _updateSelectedNodes() {
const actuallySelectedIds: number[] = [];
const selectedNodes: RulesetNode[] = [];
@@ -413,32 +405,25 @@ export class OrRuleList extends translate(i18next)(LitElement) {
}
protected _getRealm(): string | undefined {
- if (manager.isSuperUser() && this.realm) {
- return this.realm;
+ if (manager.isSuperUser()) {
+ return manager.displayRealm;
}
return manager.getRealm();
}
- protected _onRealmChanged(realm: string | undefined) {
- this.realm = realm;
- }
-
protected _doRequest<T>(event: CustomEvent<RequestEventDetail<T>>, handler: (detail: T) => void) {
this.dispatchEvent(event);
window.setTimeout(() => {
if (event.detail.allow) {
handler(event.detail.detail);
}
- })
+ });
}
protected _loadRulesets() {
-
const sortFunction = this._getSortFunction();
-
- manager.rest.api.RulesResource.getTenantRulesets(manager.config.realm, {
- language: RulesetLang.JSON,
+ manager.rest.api.RulesResource.getTenantRulesets(this._getRealm() || manager.config.realm, {
fullyPopulate: true
}).then((response: any) => {
if (response && response.data) {
diff --git a/ui/component/or-rules/src/or-rule-viewer.ts b/ui/component/or-rules/src/or-rule-viewer.ts
index 6f5d6c4e5..29b075d25 100644
--- a/ui/component/or-rules/src/or-rule-viewer.ts
+++ b/ui/component/or-rules/src/or-rule-viewer.ts
@@ -11,6 +11,7 @@ import {ClientRole, RulesetLang, RulesetUnion} from "@openremote/model";
import manager from "@openremote/core";
import "./json-viewer/or-rule-json-viewer";
import "./or-rule-text-viewer";
+import "./flow-viewer/components/flow-editor";
import "@openremote/or-input";
import {translate} from "@openremote/or-translate";
import {InputType, OrInputChangedEvent} from "@openremote/or-input";
@@ -151,6 +152,9 @@ export class OrRuleViewer extends translate(i18next)(LitElement) {
case RulesetLang.JSON:
viewer = html`<or-rule-json-viewer id="rule-view" .ruleset="${this.ruleset}" .config="${this.config}" .readonly="${this.readonly}"></or-rule-json-viewer>`;
break;
+ case RulesetLang.FLOW:
+ viewer = html`<flow-editor id="rule-view" .ruleset="${this.ruleset}" .readonly="${this.readonly}"></flow-editor>`;
+ break;
default:
viewer = html`<div class="wrapper"><or-translate value="notSupported"></or-translate></div>`;
}
@@ -165,10 +169,9 @@ export class OrRuleViewer extends translate(i18next)(LitElement) {
<span id="active-wrapper">
<or-translate value="active"></or-translate>
-
<or-input .type="${InputType.SWITCH}" .value="${this.ruleset && this.ruleset.enabled}" ?disabled="${!this.ruleset.id}" @or-input-changed="${this._toggleEnabled}"></or-input>
</span>
-
+
<or-input .type="${InputType.BUTTON}" id="save-btn" .label="${i18next.t("save")}" raised ?disabled="${this._cannotSave()}" @click="${this._doSave}" @or-input-changed="${this._doSave}"></or-input>
</div>
</div>