refactor(node-watcher): adapt to new DI architecture
This commit moves the node watcher code to the presentation layer and
adapts it to be ready to use DI. Thus, the node watcher is separated
into a port and adapter.
Bug: twpowertools:226
Change-Id: Id36d5407ff478006eb8c057db1dcad05fd30b7d6
diff --git a/src/presentation/nodeWatcher/NodeWatcher.port.ts b/src/presentation/nodeWatcher/NodeWatcher.port.ts
new file mode 100644
index 0000000..83372b6
--- /dev/null
+++ b/src/presentation/nodeWatcher/NodeWatcher.port.ts
@@ -0,0 +1,23 @@
+import { NodeWatcherHandler } from "./NodeWatcherHandler";
+
+export interface NodeWatcherPort {
+ /**
+ * Start watching mutations to nodes.
+ */
+ start(): void;
+
+ /**
+ * Pause watching mutations to nodes.
+ */
+ pause(): void;
+
+ /**
+ * Add a handler to watch certain mutations.
+ */
+ setHandler(key: string, handler: NodeWatcherHandler): void;
+
+ /**
+ * Remove a handler by key.
+ */
+ removeHandler(key: string): boolean;
+}
diff --git a/src/presentation/nodeWatcher/NodeWatcherHandler.ts b/src/presentation/nodeWatcher/NodeWatcherHandler.ts
new file mode 100644
index 0000000..b6c3a25
--- /dev/null
+++ b/src/presentation/nodeWatcher/NodeWatcherHandler.ts
@@ -0,0 +1,52 @@
+export enum NodeMutationType {
+ /**
+ * The node was found during initial discovery.
+ */
+ InitialDiscovery,
+ /**
+ * The node has been added.
+ */
+ NewNode,
+ /**
+ * The node was removed
+ */
+ RemovedNode,
+}
+
+export interface NodeMutation {
+ /**
+ * Node being mutated.
+ */
+ node: Node;
+ /**
+ * Which mutation has occurred to the node.
+ */
+ type: NodeMutationType;
+ /**
+ * MutationRecord from which this node mutation has been extracted. It is null
+ * if the type is {@link NodeMutationType.InitialDiscovery}.
+ */
+ mutationRecord: MutationRecord | null;
+}
+
+export interface NodeWatcherHandler {
+ /**
+ * Only node mutations which pass this filter (it returns true) will be passed
+ * to {@link onMutatedNode}.
+ */
+ nodeFilter: (nodeMutation: NodeMutation) => boolean;
+
+ /**
+ * Optional CSS selector used to discover nodes existing prior to the handler
+ * being established. These matching nodes will be evaluated by
+ * {@link onMutatedNode} if they pass {@link nodeFilter}.
+ *
+ * This is useful when watching an node but it has already been created.
+ */
+ initialDiscoverySelector?: string;
+
+ /**
+ * Function which will be called with each of the filtered node mutations.
+ */
+ onMutatedNode: (nodeMutation: NodeMutation) => void;
+}