Joeri Exelmans 3 лет назад
Родитель
Сommit
e06dd27a61

+ 3 - 3
src/frontend/d3graph/reducers/delta_graph.ts

@@ -59,8 +59,8 @@ export function deltaGraphReducer(prevState: DeltaGraphState, action: DeltaGraph
         nodes: prevState.nodes.concat(deltaToDepGraphNode(delta, /* active: */ action.active)),
         // for every dependency and conflict, add a link:
         links: prevState.links.concat(
-            ...delta.getTypedDependencies().map(([dep,depSummary]) => dependencyToDepGraphLink(delta, dep, depSummary)),
-            ...delta.getConflicts().filter(conflictingDelta => prevState.nodes.some(n => n.id === fullDeltaId(conflictingDelta))).map(conflictingDelta => conflictToDepGraphLink(delta, conflictingDelta)),
+            ...delta.getDependencies().map(([dep,depSummary]) => dependencyToDepGraphLink(delta, dep, depSummary)),
+            ...delta.conflictsWith.filter(([conflictingDelta]) => prevState.nodes.some(n => n.id === fullDeltaId(conflictingDelta))).map(([conflictingDelta]) => conflictToDepGraphLink(delta, conflictingDelta)),
           ),
       };
     }
@@ -68,7 +68,7 @@ export function deltaGraphReducer(prevState: DeltaGraphState, action: DeltaGraph
 }
 
 export function fullDeltaId(delta: Delta): string {
-  return delta.getHash().toString('hex');
+  return delta.hash.toString('hex');
 }
 
 // Helpers

+ 13 - 13
src/frontend/d3graph/reducers/onion_graph.ts

@@ -1,6 +1,6 @@
 // The React state and reducer of a D3Graph component showing an onion graph state.
 
-import {PrimitiveValue} from "onion/types";
+import {PrimitiveValue, UUID} from "onion/types";
 import {INodeState, IValueState, GraphStateListener} from "onion/graph_state";
 import {D3GraphData, D3NodeData, D3LinkData} from "../d3graph";
 
@@ -9,12 +9,12 @@ export type D3OnionLinkData = D3LinkData<null>;
 export type D3OnionGraphData = D3GraphData<INodeState|IValueState,null>;
 
 interface AddNode {type:'addNode', ns: INodeState, x: number, y: number}
-interface RemoveNode {type:'removeNode', id: PrimitiveValue}
+interface RemoveNode {type:'removeNode', id: UUID}
 interface AddValue {type:'addValue', vs: IValueState, x: number, y: number}
 interface RemoveValue {type:'removeValue', value: PrimitiveValue}
-interface AddLinkToNode {type:'addLinkToNode', sourceId: PrimitiveValue, label: string, targetId: PrimitiveValue}
-interface AddLinkToValue {type:'addLinkToValue', sourceId: PrimitiveValue, label: string, targetValue: PrimitiveValue}
-interface RemoveLink {type:'removeLink', sourceId: PrimitiveValue, label: string}
+interface AddLinkToNode {type:'addLinkToNode', sourceId: UUID, label: string, targetId: UUID}
+interface AddLinkToValue {type:'addLinkToValue', sourceId: UUID, label: string, targetValue: PrimitiveValue}
+interface RemoveLink {type:'removeLink', sourceId: UUID, label: string}
 
 export type D3OnionGraphAction =
     Readonly<AddNode>
@@ -30,8 +30,8 @@ export function onionGraphReducer(prevState: D3OnionGraphData, action: D3OnionGr
     case 'addNode': {
       return {
         nodes: [...prevState.nodes, {
-          id: nodeNodeId(action.ns.creation.id.value),
-          label: JSON.stringify(action.ns.creation.id.value),
+          id: nodeNodeId(action.ns.creation.id),
+          label: JSON.stringify(action.ns.creation.id),
           x: action.x,
           y: action.y,
           color: "darkturquoise",
@@ -94,13 +94,13 @@ export function onionGraphReducer(prevState: D3OnionGraphData, action: D3OnionGr
     case 'removeLink': {
       return {    
         nodes: prevState.nodes,
-        links: prevState.links.filter(l => l.source.obj.creation.id.value !== action.sourceId || l.label !== action.label),
+        links: prevState.links.filter(l => l.source.obj.creation.id !== action.sourceId || l.label !== action.label),
       };
     }
   }
 }
 
-function nodeNodeId(nodeId: PrimitiveValue) {
+function nodeNodeId(nodeId: UUID) {
   return "N"+JSON.stringify(nodeId);
 }
 
@@ -130,19 +130,19 @@ export class D3GraphUpdater implements GraphStateListener {
   createValue(vs: IValueState) {
     this.setGraph(prevGraph => onionGraphReducer(prevGraph, {type: 'addValue', vs, x: this.x, y: this.y}));
   }
-  deleteNode(id: PrimitiveValue) {
+  deleteNode(id: UUID) {
     this.setGraph(prevGraph => onionGraphReducer(prevGraph, {type: 'removeNode', id}));
   }
   deleteValue(value: PrimitiveValue) {
     this.setGraph(prevGraph => onionGraphReducer(prevGraph, {type: 'removeValue', value}));
   }
-  createLinkToNode(sourceId: PrimitiveValue, label: string, targetId: PrimitiveValue) {
+  createLinkToNode(sourceId: UUID, label: string, targetId: UUID) {
     this.setGraph(prevGraph => onionGraphReducer(prevGraph, {type: 'addLinkToNode', sourceId, label, targetId}));
   }
-  createLinkToValue(sourceId: PrimitiveValue, label: string, targetValue: PrimitiveValue) {
+  createLinkToValue(sourceId: UUID, label: string, targetValue: PrimitiveValue) {
     this.setGraph(prevGraph => onionGraphReducer(prevGraph, {type: 'addLinkToValue', sourceId, label, targetValue}));
   }
-  deleteLink(sourceId: PrimitiveValue, label: string) {
+  deleteLink(sourceId: UUID, label: string) {
     this.setGraph(prevGraph => onionGraphReducer(prevGraph, {type: 'removeLink', sourceId, label}));
   }
 }

+ 9 - 8
src/frontend/demos/demo_le.tsx

@@ -3,6 +3,7 @@ import {SimpleGrid, Text, Title, Stack, Center, Group, Space, Image, Button, Pap
 import {IconTrash, IconRowInsertTop, IconRowInsertBottom, IconAlertCircle} from '@tabler/icons';
 
 import {DeltaRegistry} from "onion/delta_registry";
+import {PrimitiveDelta, TargetNode, TargetValue} from "onion/delta";
 import {VersionRegistry} from "onion/version";
 import {mockUuid} from "../../util/test_helpers";
 import {PrimitiveValue} from "onion/types";
@@ -49,12 +50,12 @@ export function getDemoLE() {
             const listNodeCreation = deltaRegistry.newNodeCreation(listNodeId);
             reducer.createAndGotoNewVersion([
                 listNodeCreation,
-                deltaRegistry.newEdgeCreation(listNodeCreation, "next", listNodeCreation),
-                deltaRegistry.newEdgeCreation(listNodeCreation, "prev", listNodeCreation),
+                deltaRegistry.newEdgeUpdate(listNodeCreation.createOutgoingEdge("next"), listNodeCreation),
+                deltaRegistry.newEdgeUpdate(listNodeCreation.createOutgoingEdge("prev"), listNodeCreation),
             ], "createList", versionRegistry.initialVersion);
         }, []);
 
-        const listNode = onion.graphState.nodes.get(listNodeId.value) as INodeState;
+        const listNode = onion.graphState.nodes.get(listNodeId) as INodeState;
 
         // Inserts list item after prevNode and before nextNode.
         function insertBetween(prevNode: INodeState, nextNode: INodeState, val: PrimitiveValue) {
@@ -72,13 +73,13 @@ export function getDemoLE() {
             const updatePrev = nextNode.getDeltasForSetEdge(deltaRegistry, "prev", newItemCreation);
             updatePrev.forEach(d => onion.graphState.exec(d));
 
-            onion.graphState.exec(deltaRegistry.newEdgeCreation(newItemCreation, "value", val));
-            onion.graphState.exec(deltaRegistry.newEdgeCreation(newItemCreation, "prev", prevNode.creation));
-            onion.graphState.exec(deltaRegistry.newEdgeCreation(newItemCreation, "next", nextNode.creation));
+            onion.graphState.exec(deltaRegistry.newEdgeUpdate(newItemCreation.createOutgoingEdge("value"), val));
+            onion.graphState.exec(deltaRegistry.newEdgeUpdate(newItemCreation.createOutgoingEdge("prev"), prevNode.creation));
+            onion.graphState.exec(deltaRegistry.newEdgeUpdate(newItemCreation.createOutgoingEdge("next"), nextNode.creation));
 
             const deltas = onion.graphState.popState();
 
-            reducer.createAndGotoNewVersion(deltas, "insert"+JSON.stringify(val));
+            reducer.createAndGotoNewVersion(deltas as PrimitiveDelta[], "insert"+JSON.stringify(val));
         }
 
         function insertBefore(node: INodeState, val: PrimitiveValue) {
@@ -103,7 +104,7 @@ export function getDemoLE() {
 
             const deltas = onion.graphState.popState();
 
-            reducer.createAndGotoNewVersion(deltas, "delete"+JSON.stringify((node.getOutgoingEdges().get("value") as IValueState).value));
+            reducer.createAndGotoNewVersion(deltas as PrimitiveDelta[], "delete"+JSON.stringify((node.getOutgoingEdges().get("value") as IValueState).value));
         }
 
         // Alternative implementation of deletion - just add a property 'deleted' to the deleted node.

+ 14 - 14
src/frontend/demos/demo_live.tsx

@@ -10,7 +10,7 @@ import {InfoHoverCard, InfoHoverCardOverlay} from "../info_hover_card";
 import {OnionContext} from "../onion_context";
 
 import {mockUuid} from "../../util/test_helpers";
-import {NodeDeletion} from "onion/delta";
+import {NodeDeletion, TargetValue, TargetNode} from "onion/delta";
 import {DeltaRegistry} from "onion/delta_registry";
 import {VersionRegistry} from "onion/version";
 import {Delta} from "onion/delta";
@@ -80,7 +80,7 @@ export function getDemoLive() {
         const modelCreation = deltaRegistry.newNodeCreation(modelId);
         const newVersion = reducer.createAndGotoNewVersion([
             modelCreation,
-            deltaRegistry.newEdgeCreation(modelCreation, "type", "DesignModel"),
+            deltaRegistry.newEdgeUpdate(modelCreation.createOutgoingEdge("type"), "DesignModel"),
           ], "createDesignModel", versionRegistry.initialVersion,
           newDesignVersion => new Map([
             ["design", {version: newDesignVersion, overridings: new Map()}],
@@ -236,7 +236,7 @@ export function getDemoLive() {
         }
 
         const overridings: Map<Delta,Delta> = new Map(designDeltas
-          .map(d => runtimeDeltas.includes(d) ? null : [d, runtimeDeltas.find(rtd => rtd instanceof NodeDeletion && rtd.creation === d.creation)!])
+          .map(d => runtimeDeltas.includes(d) ? null : [d, runtimeDeltas.find(rtd => rtd instanceof NodeDeletion && rtd.node === d.creation)!])
           .filter(x => x!==null)
         );
         const newRtVersion = reducer.createAndGotoNewVersion(runtimeDeltas, "design:"+compositeLabel,
@@ -316,10 +316,10 @@ export function getDemoLive() {
         const nodeId = generateUUID();
         const nodeCreation = deltaRegistry.newNodeCreation(nodeId);
         graphState.exec(nodeCreation);
-        graphState.exec(deltaRegistry.newEdgeCreation(nodeCreation, "type", "State"));
-        graphState.exec(deltaRegistry.newEdgeCreation(nodeCreation, "name", addStateName));
+        graphState.exec(deltaRegistry.newEdgeUpdate(nodeCreation.createOutgoingEdge("type"), "State"));
+        graphState.exec(deltaRegistry.newEdgeUpdate(nodeCreation.createOutgoingEdge("name"), addStateName));
 
-        modelNode.getDeltasForSetEdge(deltaRegistry, "contains-"+JSON.stringify(nodeId.value), nodeCreation).forEach(d => graphState.exec(d));
+        modelNode.getDeltasForSetEdge(deltaRegistry, "contains-"+JSON.stringify(nodeId), nodeCreation).forEach(d => graphState.exec(d));
 
         // Bonus feature: Auto-increment state names
         if (addStateName.match(/[A-Z]/i)) {
@@ -334,12 +334,12 @@ export function getDemoLive() {
         const nodeId = generateUUID();
         const nodeCreation = deltaRegistry.newNodeCreation(nodeId);
         graphState.exec(nodeCreation);
-        graphState.exec(deltaRegistry.newEdgeCreation(nodeCreation, "type", "Transition"));
-        graphState.exec(deltaRegistry.newEdgeCreation(nodeCreation, "event", addTransitionEvent));
-        graphState.exec(deltaRegistry.newEdgeCreation(nodeCreation, "src", findState(graphState, addTransitionSrc!)!.creation));
-        graphState.exec(deltaRegistry.newEdgeCreation(nodeCreation, "tgt", findState(graphState, addTransitionTgt!)!.creation));
+        graphState.exec(deltaRegistry.newEdgeUpdate(nodeCreation.createOutgoingEdge("type"), "Transition"));
+        graphState.exec(deltaRegistry.newEdgeUpdate(nodeCreation.createOutgoingEdge("event"), addTransitionEvent));
+        graphState.exec(deltaRegistry.newEdgeUpdate(nodeCreation.createOutgoingEdge("src"), findState(graphState, addTransitionSrc!)!.creation));
+        graphState.exec(deltaRegistry.newEdgeUpdate(nodeCreation.createOutgoingEdge("tgt"), findState(graphState, addTransitionTgt!)!.creation));
 
-        modelNode.getDeltasForSetEdge(deltaRegistry, "contains-"+JSON.stringify(nodeId.value), nodeCreation).forEach(d => graphState.exec(d));
+        modelNode.getDeltasForSetEdge(deltaRegistry, "contains-"+JSON.stringify(nodeId), nodeCreation).forEach(d => graphState.exec(d));
 
         return {compositeLabel: "addTransition:"+addTransitionSrc+"--"+addTransitionEvent+"->"+addTransitionTgt};
       });
@@ -384,11 +384,11 @@ export function getDemoLive() {
           const runtimeId = generateUUID();
           const nodeCreation = deltaRegistry.newNodeCreation(runtimeId);
           graphState.exec(nodeCreation);
-          graphState.exec(deltaRegistry.newEdgeCreation(nodeCreation, "type", "RuntimeModel"));
-          graphState.exec(deltaRegistry.newEdgeCreation(nodeCreation, "design", runtimeStuff.modelNode!.creation));
+          graphState.exec(deltaRegistry.newEdgeUpdate(nodeCreation.createOutgoingEdge("type"), "RuntimeModel"));
+          graphState.exec(deltaRegistry.newEdgeUpdate(nodeCreation.createOutgoingEdge("design"), runtimeStuff.modelNode!.creation));
           // overwrite 'initial' pointer with its current value:
           // runtimeStuff.modelNode!.getDeltasForSetEdge(deltaRegistry, "initial", runtimeStuff.initial!.creation).forEach(d => graphState.exec(d));
-          graphState.exec(deltaRegistry.newEdgeCreation(nodeCreation, "current", runtimeStuff.initial!.creation));
+        graphState.exec(deltaRegistry.newEdgeUpdate(nodeCreation.createOutgoingEdge("current"), runtimeStuff.initial!.creation));
           return {compositeLabel: "initialize"};
         });
       }

+ 2 - 2
src/frontend/rountangleEditor/RountangleComponent.tsx

@@ -2,10 +2,10 @@ import * as React from "react";
 import {RountangleAction} from "./RountangleActions";
 import {RountangleResizeHandleComponent} from "./RountangleResizeHandleComponent";
 import {Rountangle} from "./RountangleEditor";
-import {PrimitiveValue} from "onion/types";
+import {UUID} from "onion/types";
 
 export interface RountangleProps extends Rountangle {
-    id:       PrimitiveValue;
+    id:       UUID;
     dispatch: (action: RountangleAction) => void;
     zoom:     number;
 }

+ 6 - 6
src/frontend/rountangleEditor/RountangleEditor.tsx

@@ -1,11 +1,11 @@
 import * as React from "react";
 import {RountangleComponent} from "./RountangleComponent";
 import {OnionContext, OnionContextType} from "../onion_context";
-import {PrimitiveValue} from "onion/types";
+import {PrimitiveValue, UUID} from "onion/types";
 import {D3OnionGraphData, D3OnionNodeData, D3OnionLinkData} from "../d3graph/reducers/onion_graph";
 import {RountangleAction} from "./RountangleActions";
 import {INodeState, IValueState, GraphState} from "onion/graph_state";
-import {PrimitiveDelta} from "onion/delta";
+import {PrimitiveDelta, TargetValue} from "onion/delta";
 import {assert, assertNever} from "../../util/assert";
 
 export interface Rountangle {
@@ -29,14 +29,14 @@ export function isRountangle(d3node: D3OnionNodeData) {
 }
 
 // Precondition: isRountangle(d3Node)
-export function graphStateToRountangle(d3node: D3OnionNodeData): [PrimitiveValue, Rountangle]  {
+export function graphStateToRountangle(d3node: D3OnionNodeData): [UUID, Rountangle]  {
     if (!isRountangle(d3node)) {
         throw new Error(`RountangleParser Cannot parse: ${d3node}`);
     }
 
     const nodeState = d3node.obj as INodeState;
     const outgoing = nodeState.getOutgoingEdges();
-    return [nodeState.creation.id.value, {
+    return [nodeState.creation.id, {
         posX: outgoing.get("x")!.asTarget() as number,
         posY: outgoing.get("y")!.asTarget() as number,
         width: outgoing.get("width")!.asTarget() as number,
@@ -101,7 +101,7 @@ export function RountangleEditor(props: RountangleEditorProps) {
                     ["height",action.height],
                 ];
                 deltas.push(... edgeSpec.map(([edgeLabel, value]) =>
-                    onionContext.deltaRegistry.newEdgeCreation(createRountangleNodeDelta, edgeLabel, value)));
+                    onionContext.deltaRegistry.newEdgeUpdate(createRountangleNodeDelta.createOutgoingEdge(edgeLabel), value)));
                 break;
             case 'moveRountangle':
                 // get nodeState from clicked node
@@ -265,7 +265,7 @@ export function RountangleEditor(props: RountangleEditorProps) {
                    .map(node => {
                     const [id, rountangle] = node;
                     return <RountangleComponent
-                        key={id.toString()}
+                        key={JSON.stringify(id)}
                         id={id}
                         posX={rountangle.posX}
                         posY={rountangle.posY}

+ 2 - 2
src/frontend/versioned_model/correspondence.tsx

@@ -207,8 +207,8 @@ export function newCorrespondence({deltaRegistry, generateUUID, versionRegistry}
               if (asNode?.type !== "node") {
                 continue; // corrNode is not a correspondence node
               }
-              csToAs.set(csNode.creation.id.value, asNode.creation.id.value);
-              asToCs.set(asNode.creation.id.value, csNode.creation.id.value);
+              csToAs.set(csNode.creation.id, asNode.creation.id);
+              asToCs.set(asNode.creation.id, csNode.creation.id);
             }
 
             return new Promise((resolve: (csDeltas: PrimitiveDelta[]) => void, reject: () => void) => {

+ 16 - 16
src/frontend/versioned_model/manual_renderer.tsx

@@ -14,8 +14,8 @@ import {Version} from "onion/version";
 import {InfoHoverCardOverlay} from "../info_hover_card";
 import {D3Graph, defaultGraphForces} from "../d3graph/d3graph";
 import {D3OnionGraphData, D3GraphUpdater} from "../d3graph/reducers/onion_graph";
-import {EdgeCreation, EdgeUpdate, NodeCreation, NodeDeletion} from "onion/delta";
-import {PrimitiveDelta} from "onion/delta";
+import {EdgeUpdate, NodeCreation, NodeDeletion} from "onion/delta";
+import {PrimitiveDelta, ExistingEdge} from "onion/delta";
 import {DeltaRegistry} from "onion/delta_registry";
 import {PrimitiveValue} from "onion/types";
 import {GraphState, INodeState} from "onion/graph_state";
@@ -51,7 +51,7 @@ function getInsidenesses(csGraphState: GraphState) {
   // get every CS node and its rountangle-geometry:
   const geometries: Array<[INodeState, Geometry2DRect]> = [];
   for (const csNode of csGraphState.nodes.values()) {
-    const geometry = getGeometry(csGraphState, csNode.creation.id.value);
+    const geometry = getGeometry(csGraphState, csNode.creation.id);
     if (geometry === undefined) continue;
     geometries.push([csNode, geometry]);
   }
@@ -65,7 +65,7 @@ function getInsidenesses(csGraphState: GraphState) {
   for (const [csNode1, geom1] of geometries) {
     for (const [csNode2, geom2] of geometries) {
       if (isInside(geom1, geom2)) {
-        insidenesses.push([csNode1.creation.id.value, csNode2.creation.id.value]);
+        insidenesses.push([csNode1.creation.id, csNode2.creation.id]);
         break; // we're only interested in the smallest other rountangle that we're inside
       }
     }
@@ -94,8 +94,8 @@ export function ManualRenderer(props: ManualRendererProps) {
     for (const childAs of asGraphState.nodes.values()) {
       const parentAs = childAs.getOutgoingEdges().get("hasParent");
       if (parentAs !== undefined) {
-        const insideCsId = props.asToCs.get(childAs.creation.id.value)!;
-        const outsideCsId = props.asToCs.get(parentAs.creation.id.value)!
+        const insideCsId = props.asToCs.get(childAs.creation.id)!;
+        const outsideCsId = props.asToCs.get(parentAs.creation.id)!
         const insideGeometry = getGeometry(csGraphState, insideCsId)!;
         const outsideGeometry = getGeometry(csGraphState, outsideCsId)!;
         if (!isInside(insideGeometry, outsideGeometry)) {
@@ -112,23 +112,23 @@ export function ManualRenderer(props: ManualRendererProps) {
 
   const changelog = props.asDeltasToRender.filter(d => !(d instanceof NodeDeletion)).map(d => {
     if (d instanceof NodeCreation) {
-      return "Newly created rountangle " + JSON.stringify(props.asToCs.get(d.id.value)!) + " needs geometry";
-    }
-    else if (d instanceof EdgeCreation) {
-      return "Rountangle " + JSON.stringify(props.asToCs.get(d.source.id.value)!) + " needs to be moved inside rountangle " + JSON.stringify((props.asToCs.get((d.target.getTarget() as NodeCreation).id.value)!));
+      return "Newly created rountangle " + JSON.stringify(props.asToCs.get(d.id)!) + " needs geometry";
     }
+    // else if (d instanceof EdgeCreation) {
+    //   return "Rountangle " + JSON.stringify(props.asToCs.get(d.source.id)!) + " needs to be moved inside rountangle " + JSON.stringify((props.asToCs.get((d.target.getTarget() as NodeCreation).id)!));
+    // }
     else if (d instanceof EdgeUpdate) {
-      const oldTarget = d.overwrites.target.getTarget();
-      const newTarget = d.target.getTarget();
-      const sourceId = d.getCreation().source.id.value;
+      const oldTarget = d.overwrites instanceof ExistingEdge ? d.overwrites.delta.target.value : null;
+      const newTarget = d.target.value;
+      const sourceId = d.overwrites.source.id;
       if (oldTarget === null && newTarget !== null) {
-        return "Rountangle " + JSON.stringify(props.asToCs.get(sourceId)!) + " needs to be moved inside rountangle " + JSON.stringify(props.asToCs.get((newTarget as NodeCreation).id.value));
+        return "Rountangle " + JSON.stringify(props.asToCs.get(sourceId)!) + " needs to be moved inside rountangle " + JSON.stringify(props.asToCs.get((newTarget as NodeCreation).id));
       }
       else if (oldTarget !== null && newTarget === null) {
-        return "Rountangle " + JSON.stringify(props.asToCs.get(sourceId)!) + " is no longer inside rountangle " + JSON.stringify(props.asToCs.get((oldTarget as NodeCreation).id.value)!);
+        return "Rountangle " + JSON.stringify(props.asToCs.get(sourceId)!) + " is no longer inside rountangle " + JSON.stringify(props.asToCs.get((oldTarget as NodeCreation).id)!);
       }
       else if (oldTarget !== null && newTarget !== null) {
-        return "Rountangle " + JSON.stringify(props.asToCs.get(sourceId)!) + " is no longer inside rountangle " + JSON.stringify(props.asToCs.get((oldTarget as NodeCreation).id.value)!) + " but instead inside rountangle " + JSON.stringify(props.asToCs.get((newTarget as NodeCreation).id.value)!);
+        return "Rountangle " + JSON.stringify(props.asToCs.get(sourceId)!) + " is no longer inside rountangle " + JSON.stringify(props.asToCs.get((oldTarget as NodeCreation).id)!) + " but instead inside rountangle " + JSON.stringify(props.asToCs.get((newTarget as NodeCreation).id)!);
       }
     }
   });

+ 22 - 22
src/onion/delta.test.ts

@@ -32,10 +32,10 @@ describe("Primitive Delta", () => {
     const target1Creation = registry.newNodeCreation(getId());
     const target2Creation = registry.newNodeCreation(getId());
 
-    const edge1Creation = registry.newEdgeUpdate(sourceCreation.createOutgoingEdge("label"), new TargetNode(target1Creation));
+    const edge1Creation = registry.newEdgeUpdate(sourceCreation.createOutgoingEdge("label"), target1Creation);
     assert(edge1Creation.conflictsWith.length === 0, "expected a single edge alone to not be involved in conflicts");
 
-    const edge2Creation = registry.newEdgeUpdate(sourceCreation.createOutgoingEdge("label"), new TargetNode(target2Creation));
+    const edge2Creation = registry.newEdgeUpdate(sourceCreation.createOutgoingEdge("label"), target2Creation);
     assert(edge1Creation.conflictsWith.length === 1, "expected conflict: same edge created twice, concurrently")
     assert(edge2Creation.conflictsWith.length === 1, "expected conflict: same edge created twice, concurrently")
   });
@@ -49,12 +49,12 @@ describe("Primitive Delta", () => {
     const newTarget1Creation = registry.newNodeCreation(getId());
     const newTarget2Creation = registry.newNodeCreation(getId());
 
-    const edgeCreation = registry.newEdgeUpdate(sourceCreation.createOutgoingEdge("label"), new TargetNode(targetCreation));
+    const edgeCreation = registry.newEdgeUpdate(sourceCreation.createOutgoingEdge("label"), targetCreation);
 
-    const update1 = registry.newEdgeUpdate(edgeCreation.overwrite(), new TargetNode(newTarget1Creation));
+    const update1 = registry.newEdgeUpdate(edgeCreation.overwrite(), newTarget1Creation);
     assert(update1.conflictsWith.length === 0, "expected no conflict with a single edge update.")
 
-    const update2 = registry.newEdgeUpdate(edgeCreation.overwrite(),new TargetNode(newTarget2Creation));
+    const update2 = registry.newEdgeUpdate(edgeCreation.overwrite(),newTarget2Creation);
     assert(update1.conflictsWith.length === 1, "expected conflict between concurrent edge updates.")
     assert(update2.conflictsWith.length === 1, "expected conflict between concurrent edge updates.")
   });
@@ -69,7 +69,7 @@ describe("Primitive Delta", () => {
     const sourceDeletion = registry.newNodeDeletion(sourceCreation, [], []);
     assert(sourceDeletion.conflictsWith.length === 0, "expected no conflicts so far");
 
-    const edgeCreation = registry.newEdgeUpdate(sourceCreation.createOutgoingEdge("label"), new TargetNode(targetCreation));
+    const edgeCreation = registry.newEdgeUpdate(sourceCreation.createOutgoingEdge("label"), targetCreation);
     assert(edgeCreation.conflictsWith.length === 1, "expected require/delete conflict, because edge source is concurrently deleted");
     assert(sourceDeletion.conflictsWith.length === 1, "expected require/delete conflict, because edge source is concurrently deleted");
   });
@@ -82,7 +82,7 @@ describe("Primitive Delta", () => {
     const sourceCreation = registry.newNodeCreation(getId());
     const targetCreation = registry.newNodeCreation(getId());
 
-    const edgeCreation = registry.newEdgeUpdate(sourceCreation.createOutgoingEdge("label"), new TargetNode(targetCreation));
+    const edgeCreation = registry.newEdgeUpdate(sourceCreation.createOutgoingEdge("label"), targetCreation);
     assert(edgeCreation.conflictsWith.length === 0, "expected no conflicts so far");
 
     const sourceDeletion = registry.newNodeDeletion(sourceCreation, [], []);
@@ -98,8 +98,8 @@ describe("Primitive Delta", () => {
     const sourceCreation = registry.newNodeCreation(getId());
     const targetCreation = registry.newNodeCreation(getId());
 
-    const edgeCreation = registry.newEdgeUpdate(sourceCreation.createOutgoingEdge("label"), new TargetNode(targetCreation));
-    const edgeDeletion = registry.newEdgeUpdate(edgeCreation.overwrite(), new TargetValue(null));
+    const edgeCreation = registry.newEdgeUpdate(sourceCreation.createOutgoingEdge("label"), targetCreation);
+    const edgeDeletion = registry.newEdgeUpdate(edgeCreation.overwrite(), null);
 
     const sourceDeletion = registry.newNodeDeletion(sourceCreation, [edgeDeletion], []);
     assert(sourceDeletion.conflictsWith.length === 0, "Since node deletion was aware of outgoing edge deletion, there should be no conflict");
@@ -113,9 +113,9 @@ describe("Primitive Delta", () => {
     // Only the earliest conflict, between EdgeCreation and source NodeDeletion, matters.
     const sourceCreation = registry.newNodeCreation(getId());
     const targetCreation = registry.newNodeCreation(getId());
-    const edgeCreation = registry.newEdgeUpdate(sourceCreation.createOutgoingEdge("label"), new TargetNode(targetCreation));
+    const edgeCreation = registry.newEdgeUpdate(sourceCreation.createOutgoingEdge("label"), targetCreation);
     const newTargetCreation = registry.newNodeCreation(getId());
-    const edgeUpdate = registry.newEdgeUpdate(edgeCreation.overwrite(), new TargetNode(newTargetCreation));
+    const edgeUpdate = registry.newEdgeUpdate(edgeCreation.overwrite(), newTargetCreation);
 
     // no conflicts so far
 
@@ -134,14 +134,14 @@ describe("Primitive Delta", () => {
     // create edge between 2 nodes, and then properly delete the source node
     const sourceCreation = registry.newNodeCreation(getId());
     const targetCreation = registry.newNodeCreation(getId());
-    const edgeCreation = registry.newEdgeUpdate(sourceCreation.createOutgoingEdge("label"), new TargetNode(targetCreation));
-    const edgeDeletion = registry.newEdgeUpdate(edgeCreation.overwrite(), new TargetValue(null));
+    const edgeCreation = registry.newEdgeUpdate(sourceCreation.createOutgoingEdge("label"), targetCreation);
+    const edgeDeletion = registry.newEdgeUpdate(edgeCreation.overwrite(), null);
     const sourceDeletion = registry.newNodeDeletion(sourceCreation, [edgeDeletion], []);
 
     // no conflicts so far
 
     const newTargetCreation = registry.newNodeCreation(getId()); // no conflict
-    const edgeUpdate = registry.newEdgeUpdate(edgeCreation.overwrite(), new TargetNode(newTargetCreation));
+    const edgeUpdate = registry.newEdgeUpdate(edgeCreation.overwrite(), newTargetCreation);
 
     // console.log("edgeUpdate.conflictsWith", edgeUpdate.conflictsWith, "edgeDeletion.conflictsWith", edgeDeletion.conflictsWith);
 
@@ -163,7 +163,7 @@ describe("Primitive Delta", () => {
 
     const targetDeletion = registry.newNodeDeletion(targetCreation, [], []);
 
-    const edgeCreation = registry.newEdgeUpdate(sourceCreation.createOutgoingEdge("label"), new TargetNode(targetCreation));
+    const edgeCreation = registry.newEdgeUpdate(sourceCreation.createOutgoingEdge("label"), targetCreation);
 
     assert(edgeCreation.conflictsWith.length === 1, "expected require/delete conflict");
     assert(targetDeletion.conflictsWith.length === 1, "expected require/delete conflict");
@@ -175,7 +175,7 @@ describe("Primitive Delta", () => {
 
     const sourceCreation = registry.newNodeCreation(getId());
     const targetCreation = registry.newNodeCreation(getId());
-    const edgeCreation = registry.newEdgeUpdate(sourceCreation.createOutgoingEdge("label"), new TargetNode(targetCreation));
+    const edgeCreation = registry.newEdgeUpdate(sourceCreation.createOutgoingEdge("label"), targetCreation);
 
     // delete target of edge, unaware that edge exists:
     const targetDeletion = registry.newNodeDeletion(targetCreation, [], []);
@@ -190,8 +190,8 @@ describe("Primitive Delta", () => {
 
     const sourceCreation = registry.newNodeCreation(getId());
     const targetCreation = registry.newNodeCreation(getId());
-    const edgeCreation = registry.newEdgeUpdate(sourceCreation.createOutgoingEdge("label"), new TargetNode(targetCreation));
-    const edgeUpdate = registry.newEdgeUpdate(edgeCreation.overwrite(), new TargetNode(sourceCreation)); // turn edge into self-edge
+    const edgeCreation = registry.newEdgeUpdate(sourceCreation.createOutgoingEdge("label"), targetCreation);
+    const edgeUpdate = registry.newEdgeUpdate(edgeCreation.overwrite(), sourceCreation); // turn edge into self-edge
 
     // because of the edgeUpdate, 'target' is no longer the target of the edge, and can be deleted:
     const targetDeletion = registry.newNodeDeletion(targetCreation, [], [edgeUpdate]);
@@ -207,8 +207,8 @@ describe("Primitive Delta", () => {
 
     const sourceCreation = registry.newNodeCreation(getId());
     const targetCreation = registry.newNodeCreation(getId());
-    const edgeCreation = registry.newEdgeUpdate(sourceCreation.createOutgoingEdge("label"), new TargetNode(targetCreation));
-    const edgeDeletion = registry.newEdgeUpdate(edgeCreation.overwrite(), new TargetValue(null));
+    const edgeCreation = registry.newEdgeUpdate(sourceCreation.createOutgoingEdge("label"), targetCreation);
+    const edgeDeletion = registry.newEdgeUpdate(edgeCreation.overwrite(), null);
     const sourceDeletion = registry.newNodeDeletion(sourceCreation, [edgeDeletion], []);
 
     assert(sourceDeletion.conflictsWith.length === 0, "expected no conflicts");
@@ -223,8 +223,8 @@ describe("Primitive Delta", () => {
     const getId = mockUuid();
 
     const nodeCreation = registry.newNodeCreation(getId());
-    const edgeCreation = registry.newEdgeUpdate(nodeCreation.createOutgoingEdge("label"), new TargetNode(nodeCreation));
-    const edgeDeletion = registry.newEdgeUpdate(edgeCreation.overwrite(), new TargetValue(null));
+    const edgeCreation = registry.newEdgeUpdate(nodeCreation.createOutgoingEdge("label"), nodeCreation);
+    const edgeDeletion = registry.newEdgeUpdate(edgeCreation.overwrite(), null);
     const nodeDeletion = registry.newNodeDeletion(nodeCreation, [edgeDeletion], [edgeDeletion]);
 
     // console.log(nodeDeletion.conflictsWith);

+ 9 - 9
src/onion/delta.ts

@@ -31,7 +31,7 @@ export abstract class Delta {
     }
   }
 
-  abstract iterPrimitiveDeltas(): Iterable<PrimitiveDelta>;
+  abstract iterPrimitiveDeltas(): Generator<PrimitiveDelta>;
 }
 
 export abstract class PrimitiveDelta extends Delta {
@@ -212,7 +212,7 @@ export abstract class Edge {
   }
 }
 
-// An Edge that has not yet necessarily been assigned a target
+// An Edge that does not yet have a target
 export class NewEdge extends Edge {
   constructor(source: NodeCreation, label: string) {
     super(source, label);
@@ -224,7 +224,7 @@ export class NewEdge extends Edge {
 
   serialize() {
     return {
-      type: "newEdge",
+      type: "NewEdge",
       source: this.source.hash.toString('base64'),
       label: this.label,
     };
@@ -246,7 +246,7 @@ export class ExistingEdge extends Edge {
 
   serialize() {
     return {
-      type: "existingEdge",
+      type: "ExistingEdge",
       overwrites: this.delta.hash.toString('base64'),
     };
   }
@@ -273,7 +273,7 @@ export class TargetNode implements Target {
     return [[this.value, "TGT"]];
   }
   serialize() {
-    return {type: "node", node: this.value.hash.toString('base64')};
+    return {type: "TargetNode", node: this.value.hash.toString('base64')};
   }
 }
 
@@ -288,7 +288,7 @@ export class TargetValue implements Target {
     return [];
   }
   serialize() {
-    return {type: "value", value: this.value};
+    return {type: "TargetValue", value: this.value};
   }
 }
 
@@ -329,8 +329,8 @@ export class EdgeUpdate extends PrimitiveDelta {
   serialize(): any {
     return {
       ...super.serialize(),
-      writes: this.overwrites.serialize(),
-      reads: this.reads.map(r => r.getDependencies()[0][0]),
+      overwrites: this.overwrites.serialize(),
+      reads: this.reads.map(r => r.serialize()),
       target: this.target.serialize(),
     };
   }
@@ -382,7 +382,7 @@ export class Transaction extends Delta {
     };
   }
 
-  *iterPrimitiveDeltas(): Iterable<PrimitiveDelta> {
+  *iterPrimitiveDeltas() {
     for (const d of this.deltas) {
       yield* d.iterPrimitiveDeltas();
     }

+ 32 - 25
src/onion/delta_parser.ts

@@ -1,11 +1,12 @@
+import {PrimitiveValue} from "./types";
 import {Delta, PrimitiveDelta} from "./delta";
 
 import {
   NodeCreation,
   NodeDeletion,
-  EdgeCreation,
   EdgeUpdate,
-  EdgeTargetType,
+  Edge, NewEdge, ExistingEdge,
+  Target, TargetValue, TargetNode,
 } from "./delta";
 
 import {DeltaRegistry} from "./delta_registry";
@@ -26,44 +27,50 @@ export class DeltaParser {
     return result as T;
   }
 
-  loadEdgeTarget({type, ...rest}): EdgeTargetType {
-    if (type === "value") {
+  private loadTarget({type, ...rest}): NodeCreation | PrimitiveValue {
+    if (type === "TargetValue") {
       const {value} = rest;
       return value;
     }
-    if (type === "node") {
-      const {creation} = rest;
-      return this.getDependency<NodeCreation>(creation);
+    if (type === "TargetNode") {
+      const {node} = rest;
+      return this.getDependency<NodeCreation>(node);
     }
     throw new Error("Unknown edge target type: " + type);
   }
 
+  private loadEdge({type, ...rest}): Edge {
+    if (type === "NewEdge") {
+      const {source, label} = rest;
+      return this.getDependency<NodeCreation>(source).createOutgoingEdge(label);
+    }
+    else if (type === "ExistingEdge") {
+      const {overwrites} = rest;
+      return this.getDependency<EdgeUpdate>(overwrites).overwrite();
+    }
+    throw new Error("Unknown edge type: " + type);
+  }
+
   loadDelta({type, ...rest}): Delta {
     if (type === "NodeCreation") {
       const {id} = rest;
-      return this.deltaRegistry.newNodeCreation(new UUID(id));
-    }
-    if (type === "EdgeCreation") {
-      const {source, label, target} = rest;
-      return this.deltaRegistry.newEdgeCreation(
-        this.getDependency<NodeCreation>(source),
-        label,
-        this.loadEdgeTarget(target));
+      return this.deltaRegistry.newNodeCreation(id);
     }
-    if (type === "EdgeUpdate") {
-      const {overwrites, target} = rest;
+    else if (type === "EdgeUpdate") {
+      const {overwrites, reads, target} = rest;
       return this.deltaRegistry.newEdgeUpdate(
-        this.getDependency<EdgeCreation|EdgeUpdate>(overwrites),
-        this.loadEdgeTarget(target));
+        this.loadEdge(overwrites),
+        this.loadTarget(target),
+        reads.map(r => this.loadEdge(r)));
     }
-    if (type === "NodeDeletion") {
-      const {creation, deletedOutgoingEdges, afterIncomingEdges} = rest;
+    else if (type === "NodeDeletion") {
+      const {node, afterSrc, afterTgt} = rest;
       return this.deltaRegistry.newNodeDeletion(
-        this.getDependency<NodeCreation>(creation),
-        deletedOutgoingEdges.map(d => this.getDependency<EdgeCreation|EdgeUpdate>(d)),
-        afterIncomingEdges.map(d => this.getDependency<EdgeUpdate|NodeDeletion>(d)));
+        this.getDependency<NodeCreation>(node),
+        afterSrc.map(a => this.getDependency<EdgeUpdate>(a)),
+        afterTgt.map(a => this.getDependency<EdgeUpdate>(a)));
     }
-    if (type === "Transaction") {
+    else if (type === "Transaction") {
       const {type, deltas, dependencies, description} = rest;
       return this.deltaRegistry.newTransaction(
         deltas.map(d => this.getDependency<Delta>(d)),

+ 8 - 7
src/onion/delta_registry.ts

@@ -1,5 +1,5 @@
-import {Delta, Transaction, findTxDependencies, NodeCreation, NodeDeletion, EdgeUpdate, Edge, ExistingEdge, Target} from "./delta";
-import {PrimitiveValue} from "./types";
+import {Delta, Transaction, findTxDependencies, NodeCreation, NodeDeletion, EdgeUpdate, Edge, ExistingEdge, TargetValue, TargetNode} from "./delta";
+import {PrimitiveValue, UUID} from "./types";
 import {createHash} from "crypto";
 import {Buffer} from "buffer";
 import {buffersXOR} from "./buffer_xor";
@@ -36,7 +36,7 @@ export class DeltaRegistry {
     })();
   }
 
-  newNodeCreation(id: PrimitiveValue): NodeCreation {
+  newNodeCreation(id: UUID): NodeCreation {
     const hash = createHash('sha256')
       .update('id=')
       .update(JSON.stringify(id)) // prevent collisions between 'true' (actual boolean) and '"true"' (string "true"), or 42 (number) and "42" (string)
@@ -56,17 +56,18 @@ export class DeltaRegistry {
     return this.createIdempotent(hash, () => new NodeDeletion(hash, creation, afterSrc, afterTgt));
   }
 
-  newEdgeUpdate(overwrites: Edge, target: Target, reads: ExistingEdge[] = []): EdgeUpdate {
-    let hash = createHash('sha256')
+  newEdgeUpdate(overwrites: Edge, target: NodeCreation | PrimitiveValue, reads: ExistingEdge[] = []): EdgeUpdate {
+    const wrappedTarget = target instanceof NodeCreation ? new TargetNode(target) : new TargetValue(target);
+    const hash = createHash('sha256')
       .update('overwrites=')
       .update(getHash(overwrites))
       .update('reads=')
       // XOR, because order in which 'reads' are specified shouldn't matter:
       .update(buffersXOR(...reads.map(getHash)))
       .update('target=')
-      .update(getHash(target))
+      .update(getHash(wrappedTarget))
       .digest();
-    return this.createIdempotent(hash, () => new EdgeUpdate(hash, overwrites, target, reads));
+    return this.createIdempotent(hash, () => new EdgeUpdate(hash, overwrites, wrappedTarget, reads));
   }
 
   newTransaction(deltas: Array<Delta>, description: string, dependencies: Array<Transaction> = findTxDependencies(deltas)): Transaction {

+ 7 - 7
src/onion/graph_state.test.ts

@@ -1,7 +1,7 @@
 import {GraphState, GraphStateListener, INodeState, IValueState} from "./graph_state";
-import {mockUuid} from "./test_helpers";
+import {mockUuid} from "../util/test_helpers";
 import {DeltaRegistry} from "./delta_registry";
-import {findTxDependencies} from "./delta";
+import {findTxDependencies, TargetValue} from "./delta";
 import {assert} from "../util/assert";
 
 class MyGraphStateListener implements GraphStateListener {
@@ -46,7 +46,7 @@ describe("GraphState", () => {
 
     // Better not to create these primitive deltas by hand (is hard!). Instead, use 'getDeltasForSetEdge' and 'getDeltasForDelete' (see below).
     
-    // const edgeCreation = registry.newEdgeCreation(nodeCreation, "label", nodeCreation);
+    // const edgeCreation = registry.newEdgeUpdate(nodeCreation.createOutgoingEdge("label"), nodeCreation);
     // const edgeUpdate = registry.newEdgeUpdate(edgeCreation, null);
     // const nodeDeletion = registry.newNodeDeletion(nodeCreation, [edgeUpdate], [edgeUpdate]);
 
@@ -60,16 +60,16 @@ describe("GraphState", () => {
 
     assert(graphState.nodes.size === 1, "Expected one node after NodeCreation");
 
-    const nodeState = graphState.nodes.get(nodeId.value);
+    const nodeState = graphState.nodes.get(nodeId);
     const deltasForSetEdge = nodeState!.getDeltasForSetEdge(registry, "x", 42);
     console.log({deltasForSetEdge});
     const comp1 = newTransaction(deltasForSetEdge, "set edge x == 42");
 
     graphState.exec(comp1, myListener);
 
-    assert(graphState.nodes.get(nodeId.value)!.outgoing.get("x") !== undefined, "Expected outgoing edge 'x' for node " + nodeId);
+    assert(graphState.nodes.get(nodeId)!.outgoing.get("x") !== undefined, "Expected outgoing edge 'x' for node " + nodeId);
 
-    assert((graphState.nodes.get(nodeId.value)!.getOutgoingEdges().get("x") as IValueState).value === 42, "Expected value of outgoing edge 'x' to be 42");
+    assert((graphState.nodes.get(nodeId)!.getOutgoingEdges().get("x") as IValueState).value === 42, "Expected value of outgoing edge 'x' to be 42");
 
     const deltasForDelete = nodeState!.getDeltasForDelete(registry);
     console.log({deltasForDelete})
@@ -83,7 +83,7 @@ describe("GraphState", () => {
 
     graphState.unexec(comp2, myListener);
 
-    // assert((graphState.nodes.get(nodeId.value)!.getOutgoingEdges().get("x") as IValueState).value === 42, "Expected value of outgoing edge 'x' to be 42");
+    // assert((graphState.nodes.get(nodeId)!.getOutgoingEdges().get("x") as IValueState).value === 42, "Expected value of outgoing edge 'x' to be 42");
 
 
     // assert(graphState.nodes.size === 0, "Expected no more nodes in graphState");

+ 196 - 232
src/onion/graph_state.ts

@@ -3,9 +3,9 @@ import {Delta, Transaction} from "./delta";
 import {
   NodeCreation,
   NodeDeletion,
-  EdgeCreation,
   EdgeUpdate,
-  EdgeTargetType,
+  Edge, NewEdge, ExistingEdge,
+  Target, TargetValue, TargetNode,
 } from "./delta";
 
 import {DeltaRegistry} from "./delta_registry";
@@ -55,9 +55,6 @@ export class FanOutListener implements GraphStateListener {
   }
 }
 
-
-type IncomingEdgeDelta = EdgeCreation|EdgeUpdate|NodeDeletion;
-
 export class DummyListener implements GraphStateListener {
   createNode(ns: NodeState) {}
   createValue(vs: ValueState) {}
@@ -72,74 +69,51 @@ const DUMMY = new DummyListener();
 
 
 abstract class Common {
-  // If there once was an incoming edge on this node (or value), this contains the Delta that (un)set the edge to point to this node (or value)
-  readonly incoming: Array<IncomingEdgeDelta> = [];
+  // For every currently incoming edge, the label of the edge, the delta that set the edge, and the source of the edge.
+  readonly currentlyIncoming: Array<[string, EdgeUpdate, NodeState]> = [];
+  // For every previously incoming edge, the delta that set the edge to point somewhere else.
+  readonly previouslyIncoming: Set<EdgeUpdate> = new Set();
 
-  // For every *currently* incoming edge, the pair (label, source)
-  readonly incomingStates: Array<[string, NodeState]> = [];
-
-  addIncoming(delta: IncomingEdgeDelta, listener: GraphStateListener) {
-    this.incoming.push(delta);
+  addIncoming(label: string, delta: EdgeUpdate, srcState: NodeState, listener: GraphStateListener) {
+    this.currentlyIncoming.push([label, delta, srcState]);
+  }
+  noLongerIncoming(overwritten: EdgeUpdate, overwriter: EdgeUpdate, listener: GraphStateListener) {
+    this.currentlyIncoming.splice(this.currentlyIncoming.findIndex(([_,d]) => d === overwritten), 1);
+    this.previouslyIncoming.add(overwriter);
   }
-  replaceIncoming(prevDelta: IncomingEdgeDelta, newDelta: IncomingEdgeDelta, listener: GraphStateListener) {
-    this.incoming.splice(this.incoming.indexOf(prevDelta), 1, newDelta);
+  // only called when undoing a Delta
+  unAddIncoming(delta: EdgeUpdate, listener: GraphStateListener) {
+    this.currentlyIncoming.splice(this.currentlyIncoming.findIndex(([_,d]) => d === delta), 1);
   }
   // only called when undoing a Delta
-  removeIncoming(delta: IncomingEdgeDelta, listener: GraphStateListener) {
-    this.incoming.splice(this.incoming.indexOf(delta), 1);
+  incomingAgain(label: string, unOverwritten: EdgeUpdate, srcState: NodeState, unOverwriter: EdgeUpdate, listener: GraphStateListener) {
+    this.currentlyIncoming.push([label, unOverwritten, srcState]);
+    this.previouslyIncoming.delete(unOverwriter);
   }
 
   getIncomingEdges(): [string, INodeState][] {
-    return this.incomingStates;
+    return this.currentlyIncoming.map(([label, _, srcState]) => [label, srcState]);
   }
 
   // pure
   abstract isNode(uuid: PrimitiveValue): boolean;
   abstract isValue(value: PrimitiveValue): boolean;
-  // abstract isTargetOf(setsTarget: SetsTarget): boolean;
-  abstract asTarget(): EdgeTargetType;
+  abstract asTarget(): NodeCreation | PrimitiveValue;
 
-  // will modify 'listener'
+  // will notify 'listener'
   abstract createLinkTo(sourceId: PrimitiveValue, label: string, listener: GraphStateListener);
 
   // pure
-  abstract getDeltasForSetEdge(registry: DeltaRegistry, label: string, target: EdgeTargetType): (EdgeCreation|EdgeUpdate)[];
+  abstract getDeltasForSetEdge(registry: DeltaRegistry, label: string, target: NodeCreation | PrimitiveValue): EdgeUpdate[];
   abstract getDeltasForDelete(registry: DeltaRegistry): (EdgeUpdate|NodeDeletion)[];
 
-  // pure
-  getIncomingEdgeDependenciesForDelete(registry: DeltaRegistry): [EdgeUpdate[], (EdgeUpdate|NodeDeletion)[]] {
-    const edgeUnsettings: EdgeUpdate[] = [];
-    const alreadySeen: NodeDeletion[] = [];
-    const incomingEdgeDependencies: (EdgeUpdate|NodeDeletion)[] = [];
-
-    this.incoming.forEach((incomingEdge) => {
-      // We also depend on incoming edges that were deleted (because their source node was deleted):
-      if (incomingEdge instanceof NodeDeletion) {
-        // A NodeDeletion can delete multiple incoming edges. In this case, the same NodeDeletion will appear multiple times in our this.incoming list. Of course, we only have to add it as a dependency once:
-        if (!alreadySeen.includes(incomingEdge)) {
-          alreadySeen.push(incomingEdge);
-          incomingEdgeDependencies.push(incomingEdge);
-          // return incomingEdge;
-        }
-      }
-      else if (incomingEdge.target.getTarget() === this.asTarget()) {
-          // Must set the value of every incoming edge to 'null' (with an EdgeUpdate):
-          const edgeUnsetting = registry.newEdgeUpdate(incomingEdge, null);
-          edgeUnsettings.push(edgeUnsetting);
-          incomingEdgeDependencies.push(edgeUnsetting);
-      }
-      else {
-        // Edge is already pointing somewhere else: just include the operation as a dependency for the deletion.
-        if (!(incomingEdge instanceof EdgeUpdate)) {
-          throw new Error("Assertion failed: incomingEdge must be EdgeUpdate here.")
-        }
-        incomingEdgeDependencies.push(incomingEdge);
-      }
+  // idempotent - may create some new deltas but does not execute them
+  getIncomingEdgeDependenciesForDelete(registry: DeltaRegistry): [EdgeUpdate[], EdgeUpdate[]]{
+    const newDeltas = this.currentlyIncoming.map(([_, u]) => {
+      return registry.newEdgeUpdate(u.overwrite(), null);
     });
 
-    // incomingEdgeDependencies are dependencies of the (future) deletion of this node.
-    // edgeUnsettings is the subset (of incomingEdgeDependencies) of NEW deltas.
-    return [edgeUnsettings, incomingEdgeDependencies];
+    return [[...this.previouslyIncoming].concat(newDeltas), newDeltas];
   }
 }
 
@@ -149,11 +123,11 @@ interface ICommon {
   // array of (label, NodeState) pairs
   getIncomingEdges(): [string, INodeState][];
 
-  getDeltasForSetEdge(registry: DeltaRegistry, label: string, target: EdgeTargetType): (EdgeCreation|EdgeUpdate)[];
+  getDeltasForSetEdge(registry: DeltaRegistry, label: string, target: NodeCreation | PrimitiveValue): EdgeUpdate[];
 
   getDeltasForDelete(registry: DeltaRegistry): (EdgeUpdate|NodeDeletion)[];
 
-  asTarget(): EdgeTargetType;
+  asTarget(): NodeCreation | PrimitiveValue;
 
   isNode(uuid: PrimitiveValue): boolean;
   isValue(value: PrimitiveValue): boolean;
@@ -184,7 +158,7 @@ class NodeState extends Common implements INodeState {
   readonly creation: NodeCreation;
 
   // For every *currently* outgoing edge, the Delta that set this edge to its current value
-  readonly outgoing: Map<string, EdgeCreation|EdgeUpdate> = new Map();
+  readonly outgoing: Map<string, EdgeUpdate> = new Map();
 
   readonly outgoingStates: Map<string, IValueState | INodeState> = new Map();
 
@@ -196,19 +170,19 @@ class NodeState extends Common implements INodeState {
   }
 
   isNode(uuid: PrimitiveValue): boolean {
-    return this.creation.id.value == uuid;
+    return this.creation.id == uuid;
   }
 
   isValue(value: PrimitiveValue): boolean {
     return false;
   }
 
-  asTarget(): EdgeTargetType {
+  asTarget() {
     return this.creation;
   }
 
   createLinkTo(sourceId: PrimitiveValue, label: string, listener: GraphStateListener) {
-    listener.createLinkToNode(sourceId, label, this.creation.id.value);
+    listener.createLinkToNode(sourceId, label, this.creation.id);
   }
 
   getOutgoingEdges(): Map<string, IValueState | INodeState> {
@@ -216,22 +190,24 @@ class NodeState extends Common implements INodeState {
   }
 
   // Has no side effects - instead returns the deltas that capture the creation or update of the given outgoing edge
-  getDeltasForSetEdge(registry: DeltaRegistry, label: string, target: EdgeTargetType): (EdgeCreation|EdgeUpdate)[] {
+  getDeltasForSetEdge(registry: DeltaRegistry, label: string, target: NodeCreation | PrimitiveValue): EdgeUpdate[] {
     const previousEdgeUpdate = this.outgoing.get(label);
-    if (previousEdgeUpdate !== undefined) {
-      return [registry.newEdgeUpdate(previousEdgeUpdate, target)];
+    if (previousEdgeUpdate === undefined) {
+      return [registry.newEdgeUpdate(this.creation.createOutgoingEdge(label), target)];
     }
     else {
-      return [registry.newEdgeCreation(this.creation, label, target)];
+      return [registry.newEdgeUpdate(previousEdgeUpdate.overwrite(), target)];
     }
   }
 
   // Has no side effects - instead returns the deltas that capture the deletion of this node (and its incoming+outgoing edges)
   getDeltasForDelete(registry: DeltaRegistry): (EdgeUpdate|NodeDeletion)[] {
-    const [edgeUnsettings, incomingEdgeDependencies] = this.getIncomingEdgeDependenciesForDelete(registry);
-    const outgoingEdgeDependencies = [...this.outgoing.values()];
-    const nodeDeletion = registry.newNodeDeletion(this.creation, outgoingEdgeDependencies, incomingEdgeDependencies);
-    return [...edgeUnsettings, nodeDeletion];
+    const [afterTgt, newDeltas] = this.getIncomingEdgeDependenciesForDelete(registry);
+    const afterSrc = [...this.outgoing.values()].map(u => {
+      return registry.newEdgeUpdate(u.overwrite(), null);
+    })
+    const nodeDeletion = registry.newNodeDeletion(this.creation, afterSrc, afterTgt);
+    return [...newDeltas, ...afterSrc, nodeDeletion];
   }
 }
 
@@ -256,7 +232,7 @@ class ValueState extends Common implements IValueState {
     return this.value === value;
   }
 
-  asTarget(): EdgeTargetType {
+  asTarget() {
     return this.value;
   }
 
@@ -264,33 +240,28 @@ class ValueState extends Common implements IValueState {
     listener.createLinkToValue(sourceId, label, this.value);
   }
 
-  addIncoming(delta: IncomingEdgeDelta, listener: GraphStateListener) {
-    super.addIncoming(delta, listener);
+  addIncoming(label: string, delta: EdgeUpdate, srcState: NodeState, listener: GraphStateListener) {
+    super.addIncoming(label, delta, srcState, listener);
     this._showOrHide(listener);
   }
-  replaceIncoming(prevDelta: IncomingEdgeDelta, newDelta: IncomingEdgeDelta, listener: GraphStateListener) {
-    super.replaceIncoming(prevDelta, newDelta, listener);
+  noLongerIncoming(overwritten: EdgeUpdate, overwriter: EdgeUpdate, listener: GraphStateListener) {
+    super.noLongerIncoming(overwritten, overwriter, listener);
     this._showOrHide(listener);
   }
-  removeIncoming(delta: IncomingEdgeDelta, listener: GraphStateListener) {
-    super.removeIncoming(delta, listener);
+  // only called when undoing a Delta
+  unAddIncoming(delta: EdgeUpdate, listener: GraphStateListener) {
+    super.unAddIncoming(delta, listener);
+    this._showOrHide(listener);
+  }
+  // only called when undoing a Delta
+  incomingAgain(label: string, unOverwritten: EdgeUpdate, srcState: NodeState, unOverwriter: EdgeUpdate, listener: GraphStateListener) {
+    super.incomingAgain(label, unOverwritten, srcState, unOverwriter, listener);
     this._showOrHide(listener);
   }
 
   // Value nodes are "always already there", but they are only rendered when they are currently the target of an edge. This function determines whether a value node should be rendered, and creates/deletes the corresponding node using the 'listener'.
   private _showOrHide(listener: GraphStateListener) {
-    const willShow = this.incoming.some(delta => {
-      // Does 'delta' require a value node to be displayed?
-      if (delta instanceof EdgeCreation) {
-        return true;
-      }
-      else if (delta instanceof EdgeUpdate) {
-        return delta.target.getTarget() === this.value;
-      }
-      else if (delta instanceof NodeDeletion) {
-        return false;
-      }
-    });
+    const willShow = this.currentlyIncoming.length > 0;
     if (!this.shown && willShow) {
       listener.createValue(this);
     }
@@ -300,7 +271,7 @@ class ValueState extends Common implements IValueState {
     this.shown = willShow;
   }
 
-  getDeltasForSetEdge(registry: DeltaRegistry, label: string, target: EdgeTargetType): (EdgeCreation|EdgeUpdate)[] {
+  getDeltasForSetEdge(registry: DeltaRegistry, label: string, target: NodeCreation | PrimitiveValue): EdgeUpdate[] {
     // A value cannot be the source of an edge, so we return no deltas.
     throw new Error("Assertion failed: A value cannot be the source of an edge.")
   }
@@ -345,9 +316,6 @@ export class GraphState {
     else if (delta instanceof NodeDeletion) {
       this.execNodeDeletion(delta, listener);
     }
-    else if (delta instanceof EdgeCreation) {
-      this.execEdgeCreation(delta, listener);
-    }
     else if (delta instanceof EdgeUpdate) {
       this.execEdgeUpdate(delta, listener);
     }
@@ -368,9 +336,6 @@ export class GraphState {
     else if (delta instanceof NodeDeletion) {
       this.unexecNodeDeletion(delta, listener);
     }
-    else if (delta instanceof EdgeCreation) {
-      this.unexecEdgeCreation(delta, listener);
-    }
     else if (delta instanceof EdgeUpdate) {
       this.unexecEdgeUpdate(delta, listener);
     }
@@ -389,12 +354,12 @@ export class GraphState {
     }
   }
 
-  private _getEdgeTargetState(target: EdgeTargetType): NodeState | ValueState | undefined {
-    if (target instanceof NodeCreation) {
-      return this.nodes.get(target.id.value); // may return undefined
+  private _getEdgeTargetState(target: Target): NodeState | ValueState | undefined {
+    if (target instanceof TargetNode) {
+      return this.nodes.get(target.value.id); // may return undefined
     }
-    else if (target !== null) { // target was a PrimitiveValue
-      return this.getValueState(target);
+    else if (target instanceof TargetValue && target.value !== null) {
+      return this.getValueState(target.value);
     }
   }
   private getValueState(value: PrimitiveValue): ValueState {
@@ -409,41 +374,41 @@ export class GraphState {
   private execNodeCreation(delta: NodeCreation, listener: GraphStateListener) {
     // console.log("execNodeCreation", delta)
     const nodeState = new NodeState(delta);
-    this.nodes.set(delta.id.value, nodeState);
+    this.nodes.set(delta.id, nodeState);
     listener.createNode(nodeState);
   }
   private unexecNodeCreation(delta: NodeCreation, listener: GraphStateListener) {
     // console.log("unexecNodeCreation", delta)
-    this.nodes.delete(delta.id.value);
-    listener.deleteNode(delta.id.value);
+    this.nodes.delete(delta.id);
+    listener.deleteNode(delta.id);
   }
 
   private execNodeDeletion(delta: NodeDeletion, listener: GraphStateListener) {
     // console.log("execNodeDeletion", delta)
-    const id = delta.creation.id.value;
+    const id = delta.node.id;
     const nodeState = this.nodes.get(id);
     if (nodeState === undefined) {
       throw new Error("Assertion failed: deleted node does not exist")
     }
     // For every outgoing edge of deleted node, replace in the target node the incoming edge operation by the deletion:
-    for (const outgoingEdgeOperation of nodeState.outgoing.values()) {
-      const target = outgoingEdgeOperation.target.getTarget();
-      const targetState = this._getEdgeTargetState(target);
-      if (targetState !== undefined) {
-        targetState.replaceIncoming(outgoingEdgeOperation, delta, listener);
-        const outgoingEdgeCreation = outgoingEdgeOperation.getCreation();
-        const sourceId = outgoingEdgeCreation.source.id.value;
-        const label = outgoingEdgeCreation.label;
-        targetState.incomingStates.splice(targetState.incomingStates.findIndex(([l,s]) => l===label && s===nodeState), 1);
-        listener.deleteLink(sourceId, label);
-      }
-    }
+    // for (const outgoingEdgeOperation of nodeState.outgoing.values()) {
+    //   const target = outgoingEdgeOperation.target;
+    //   const targetState = this._getEdgeTargetState(target);
+    //   if (targetState !== undefined) {
+    //     targetState.replaceIncoming(outgoingEdgeOperation, delta, listener);
+    //     const outgoingEdgeCreation = outgoingEdgeOperation.getCreation();
+    //     const sourceId = outgoingEdgeCreation.source.id;
+    //     const label = outgoingEdgeCreation.label;
+    //     targetState.incomingStates.splice(targetState.incomingStates.findIndex(([l,s]) => l===label && s===nodeState), 1);
+    //     listener.deleteLink(sourceId, label);
+    //   }
+    // }
     nodeState.isDeleted = true;
     listener.deleteNode(id);
   }
   private unexecNodeDeletion(delta: NodeDeletion, listener: GraphStateListener) {
     // restore outgoing links
-    const id = delta.creation.id.value;
+    const id = delta.node.id;
     const nodeState = this.nodes.get(id);
     if (nodeState === undefined) {
       throw new Error("Assertion failed: deleted node does not exist")
@@ -451,146 +416,145 @@ export class GraphState {
     nodeState.isDeleted = false;
     listener.createNode(nodeState);
     // For every outgoing edge of deleted node, restore in the target node the incoming edge operation by whatever was there before
-    for (const outgoingEdgeOperation of nodeState.outgoing.values()) {
-      const target = outgoingEdgeOperation.target.getTarget();
-      const targetState = this._getEdgeTargetState(target);
-      if (targetState !== undefined) {
-        targetState.replaceIncoming(delta, outgoingEdgeOperation, listener);
-        const outgoingEdgeCreation = outgoingEdgeOperation.getCreation();
-        const sourceId = outgoingEdgeCreation.source.id.value;
-        const label = outgoingEdgeCreation.label;
-        targetState.incomingStates.push([label, nodeState]);
-        targetState.createLinkTo(sourceId, label, listener);
-      }
-    }
-  }
+    // for (const outgoingEdgeOperation of nodeState.outgoing.values()) {
+    //   const target = outgoingEdgeOperation.target;
+    //   const targetState = this._getEdgeTargetState(target);
+    //   if (targetState !== undefined) {
+    //     targetState.replaceIncoming(delta, outgoingEdgeOperation, listener);
+    //     const outgoingEdgeCreation = outgoingEdgeOperation.getCreation();
+    //     const sourceId = outgoingEdgeCreation.source.id;
+    //     const label = outgoingEdgeCreation.label;
+    //     targetState.incomingStates.push([label, nodeState]);
+    //     targetState.createLinkTo(sourceId, label, listener);
+    //   }
+    // }
+  }
+
+  // private execEdgeCreation(delta: EdgeCreation, listener: GraphStateListener) {
+  //   // console.log("execEdgeCreation", delta)
+  //   const sourceId = delta.source.id;
+  //   const target = delta.target.getTarget();
+  //   if (target === null) {
+  //     throw new Error("Assertion failed: EdgeCreation never sets edge target to null.");
+  //   }
+  //   const targetState = this._getEdgeTargetState(target);
+  //   const label = delta.label;
+  //   const sourceState = this.nodes.get(sourceId);
+  //   if (sourceState === undefined) {
+  //     throw new Error("Assertion failed: Source node is non-existing.")
+  //   }
+  //   if (targetState === undefined) {
+  //     throw new Error("Assertion failed: Target node is non-existing.");
+  //   }
+  //   sourceState.outgoing.set(label, delta);
+  //   sourceState.outgoingStates.set(label, targetState);
+  //   targetState.addIncoming(delta, listener);
+  //   targetState.incomingStates.push([label, sourceState]);
+  //   targetState.createLinkTo(sourceId, label, listener);
+  // }
+  // private unexecEdgeCreation(delta: EdgeCreation, listener: GraphStateListener) {
+  //   const sourceId = delta.source.id;
+  //   const target = delta.target.getTarget();
+  //   if (target === null) {
+  //     throw new Error("Assertion failed: EdgeCreation never sets edge target to null.");
+  //   }
+  //   const label = delta.label;
+  //   const sourceState = this.nodes.get(sourceId);
+  //   const targetState = this._getEdgeTargetState(target);
+  //   if (sourceState === undefined) {
+  //     throw new Error("Assertion failed: Source node is non-existing.")
+  //   }
+  //   if (targetState === undefined) {
+  //     throw new Error("Assertion failed: Target node is non-existing.");
+  //   }
+  //   sourceState.outgoing.delete(label);
+  //   sourceState.outgoingStates.delete(label);
+  //   targetState.removeIncoming(delta, listener);
+  //   targetState.incomingStates.splice(targetState.incomingStates.findIndex(([l,s]) => l===label && s===sourceState), 1);
+  //   listener.deleteLink(sourceId, label);
+  // }
 
-  private execEdgeCreation(delta: EdgeCreation, listener: GraphStateListener) {
-    // console.log("execEdgeCreation", delta)
-    const sourceId = delta.source.id.value;
-    const target = delta.target.getTarget();
-    if (target === null) {
-      throw new Error("Assertion failed: EdgeCreation never sets edge target to null.");
-    }
-    const targetState = this._getEdgeTargetState(target);
-    const label = delta.label;
-    const sourceState = this.nodes.get(sourceId);
-    if (sourceState === undefined) {
-      throw new Error("Assertion failed: Source node is non-existing.")
-    }
-    if (targetState === undefined) {
-      throw new Error("Assertion failed: Target node is non-existing.");
-    }
-    sourceState.outgoing.set(label, delta);
-    sourceState.outgoingStates.set(label, targetState);
-    targetState.addIncoming(delta, listener);
-    targetState.incomingStates.push([label, sourceState]);
-    targetState.createLinkTo(sourceId, label, listener);
-  }
-  private unexecEdgeCreation(delta: EdgeCreation, listener: GraphStateListener) {
-    const sourceId = delta.source.id.value;
-    const target = delta.target.getTarget();
-    if (target === null) {
-      throw new Error("Assertion failed: EdgeCreation never sets edge target to null.");
-    }
-    const label = delta.label;
+  private execEdgeUpdate(delta: EdgeUpdate, listener: GraphStateListener) {
+    const edge = delta.overwrites;
+    const label = edge.label;
+    const sourceId = edge.source.id;
     const sourceState = this.nodes.get(sourceId);
-    const targetState = this._getEdgeTargetState(target);
+
     if (sourceState === undefined) {
-      throw new Error("Assertion failed: Source node is non-existing.")
-    }
-    if (targetState === undefined) {
-      throw new Error("Assertion failed: Target node is non-existing.");
+      throw new Error("Assertion failed: Must have sourceState -> cannot execute EdgeUpdate.");
     }
-    sourceState.outgoing.delete(label);
-    sourceState.outgoingStates.delete(label);
-    targetState.removeIncoming(delta, listener);
-    targetState.incomingStates.splice(targetState.incomingStates.findIndex(([l,s]) => l===label && s===sourceState), 1);
-    listener.deleteLink(sourceId, label);
-  }
 
-  private execEdgeUpdate(delta: EdgeUpdate, listener: GraphStateListener) {
-    // console.log("execEdgeUpdate", delta)
-    // Delete link to old target
-    const edgeCreation = delta.getCreation();
-    const sourceId = edgeCreation.source.id.value;
-    const label = edgeCreation.label;
-    const overwrittenEdgeOperation = delta.overwrites;
-    const sourceState = this.nodes.get(sourceId);
-    if (sourceState === undefined) {
-      throw new Error("Assertion failed: Must have sourceState.");
+    // Remove edge from old target
+    if (edge instanceof NewEdge) {
+      // Nothing was overwritten
     }
-    // Delete link to old target
-    const oldTarget = overwrittenEdgeOperation.target.getTarget();
-    if (oldTarget !== null) {
-      // The old target was a node
+    else if (edge instanceof ExistingEdge) {
+      const overwrittenUpdate = edge.delta;
+      const oldTarget = overwrittenUpdate.target;
       const oldTargetState = this._getEdgeTargetState(oldTarget);
-      // Delete from old target's incoming edges:
-      if (oldTargetState !== undefined) {
-        oldTargetState.replaceIncoming(overwrittenEdgeOperation, delta, listener);
-        oldTargetState.incomingStates.splice(oldTargetState.incomingStates.findIndex(([l,s]) => l===label && s===sourceState), 1);
+      if (oldTargetState === undefined) {
+        console.log("TODO: Check: Should this only be allowed when old target is null?");
+      }
+      else {
+        oldTargetState.noLongerIncoming(overwrittenUpdate, delta, listener);
         listener.deleteLink(sourceId, label);
       }
     }
-    // Create link to new target (if there is a target)
-    const newTarget = delta.target.getTarget();
-    if (newTarget !== null) {
-      // The new target is a node
-      const newTargetState = this._getEdgeTargetState(newTarget);
-      // Add to new target's incoming edges
-      if (newTargetState !== undefined) {
-        if (newTarget !== oldTarget) { // if newTarget === oldTarget, the 'delta' is already part of 'incoming'
-          newTargetState.addIncoming(delta, listener);
-        }
-        newTargetState.incomingStates.push([label, sourceState]);
-        newTargetState.createLinkTo(sourceId, label, listener);
-        sourceState.outgoingStates.set(label, newTargetState);
-      }
-    } else {
+
+    // Add edge to new target
+    const newTarget = delta.target;
+    const newTargetState = this._getEdgeTargetState(newTarget);
+    if (newTargetState === undefined) {
+      console.log("TODO: Check: Should this only be allowed when new target is null?");
       sourceState.outgoingStates.delete(label);
     }
+    else {
+      newTargetState.addIncoming(label, delta, sourceState, listener);
+      newTargetState.createLinkTo(sourceId, label, listener);
+      sourceState.outgoingStates.set(label, newTargetState);
+    }
     sourceState.outgoing.set(label, delta);
   }
   private unexecEdgeUpdate(delta: EdgeUpdate, listener: GraphStateListener) {
-    // console.log("execEdgeUpdate", delta)
-    // Delete link to old target
-    const edgeCreation = delta.getCreation();
-    const sourceId = edgeCreation.source.id.value;
-    const label = edgeCreation.label;
-    const overwrittenEdgeOperation = delta.overwrites;
+    const edge = delta.overwrites;
+    const label = edge.label;
+    const sourceId = edge.source.id;
     const sourceState = this.nodes.get(sourceId);
+
     if (sourceState === undefined) {
-      throw new Error("Assertion failed: Must have sourceState.");
+      throw new Error("Assertion failed: Must have sourceState -> cannot un-execute EdgeUpdate.");
     }
-    // Delete link to new target (if there is a target)
-    const newTarget = delta.target.getTarget();
-    const oldTarget = overwrittenEdgeOperation.target.getTarget();
-    if (newTarget !== null) {
-      // The new target is a node
-      const newTargetState = this._getEdgeTargetState(newTarget);
-      // Add to new target's incoming edges
-      if (newTargetState !== undefined) {
-        if (newTarget !== oldTarget) { // if newTarget === oldTarget, the 'delta' does not have to be removed from 'incoming' (it will be replaced when dealing with 'oldTarget')
-          newTargetState.removeIncoming(delta, listener);
-        }
-        newTargetState.incomingStates.splice(newTargetState.incomingStates.findIndex(([l,s]) => l===label && s===sourceState), 1);
-        listener.deleteLink(sourceId, label);
-      }
+
+    // Remove edge from new target
+    const newTarget = delta.target;
+    const newTargetState = this._getEdgeTargetState(newTarget);
+    if (newTargetState === undefined) {
+      console.log("TODO: Check: Should this only be allowed when new target is null?");
     }
-    // Restore link to old target
-    if (oldTarget !== null) {
-      // The old target was a node
+    else {
+      newTargetState.unAddIncoming(delta, listener);
+      listener.deleteLink(sourceId, label);
+    }
+
+    // Add edge to old target
+    if (edge instanceof NewEdge) {
+      // Nothing was overwritten
+      sourceState.outgoing.delete(label);
+    }
+    else if (edge instanceof ExistingEdge) {
+      const overwrittenUpdate = edge.delta;
+      const oldTarget = overwrittenUpdate.target;
       const oldTargetState = this._getEdgeTargetState(oldTarget);
-      // Delete from old target's incoming edges:
-      if (oldTargetState !== undefined) {
-        oldTargetState.replaceIncoming(delta, overwrittenEdgeOperation, listener);
-        oldTargetState.incomingStates.push([label, sourceState]);
+      if (oldTargetState === undefined) {
+        console.log("TODO: Check: Should this only be allowed when old target is null?");
+        sourceState.outgoingStates.delete(label);
+      }
+      else {
+        oldTargetState.incomingAgain(label, overwrittenUpdate, sourceState, delta, listener);
         oldTargetState.createLinkTo(sourceId, label, listener);
         sourceState.outgoingStates.set(label, oldTargetState);
       }
-    } else {
-      sourceState.outgoingStates.delete(label);
+      sourceState.outgoing.set(label, overwrittenUpdate);
     }
-    sourceState.outgoing.set(label, overwrittenEdgeOperation);
   }
 }

+ 3 - 3
src/onion/legacy/delta.ts.legacy

@@ -36,12 +36,12 @@ export abstract class PrimitiveDelta extends Delta {
 }
 
 export function isConflicting(a: Delta, b: Delta) {
-  return a.getConflicts().includes(b);
+  return a.conflictsWith.includes(b);
 }
 
 // Yields all elements of 'it' that are conflicting with 'd'.
 export function* iterConflicts(d: Delta, it: Iterable<Delta>) {
-  for (const conflictsWith of d.getConflicts()) {
+  for (const conflictsWith of d.conflictsWith) {
     for (const otherDelta of it) {
       if (conflictsWith === otherDelta) {
         yield conflictsWith;
@@ -97,7 +97,7 @@ export class Transaction extends Delta {
     // Figure out conflicts
     this.conflicts = [];
     for (const delta of deltas) {
-      for (const conflictingDelta of delta.getConflicts()) {
+      for (const conflictingDelta of delta.conflictsWith) {
         if (deltas.includes(conflictingDelta)) {
           // console.log("Conflict between", conflictingDelta, "and", delta);
           throw new Error("Cannot create a composite delta out of conflicting deltas");

+ 1 - 1
src/onion/legacy/delta_registry.ts.legacy

@@ -21,7 +21,7 @@ export class DeltaRegistry {
 
   newNodeCreation(id: UUID): NodeCreation {
     const hash = createHash('sha256')
-      .update(JSON.stringify(id.value)) // prevent collisions between 'true' (actual boolean) and '"true"' (string "true"), or 42 (number) and "42" (string)
+      .update(JSON.stringify.id)) // prevent collisions between 'true' (actual boolean) and '"true"' (string "true"), or 42 (number) and "42" (string)
       .digest();
     return this.createIdempotent(hash, () => new NodeCreation(hash, id));
   }

+ 3 - 3
src/onion/legacy/primitive_delta.ts.legacy

@@ -21,7 +21,7 @@ export class NodeCreation extends Delta {
     super();
     this.hash = hash;
     this.id = id;
-    this.description = "NEW("+this.id.value.toString().slice(0,8)+")";
+    this.description = "NEW("+this.id.toString().slice(0,8)+")";
   }
 
   getDependencies(): [] {
@@ -57,7 +57,7 @@ export class NodeCreation extends Delta {
     return {
       hash: this.hash.toString('base64'),
       type: "NodeCreation",
-      id: this.id.value,
+      id: this.id,
     }
   }
 
@@ -147,7 +147,7 @@ export class NodeDeletion extends Delta {
       }
     }
 
-    this.description = "DEL("+this.creation.id.value.toString().slice(0,8)+")"
+    this.description = "DEL("+this.creation.id.toString().slice(0,8)+")"
 
     // Detect conflicts
 

+ 1 - 2
src/onion/types.ts

@@ -2,8 +2,7 @@ import {inspect} from "util"; // NodeJS library
 
 export type PrimitiveValue = string | number | boolean | null;
 
-// All primitive values can also be used as UUIDs
-export type UUID = PrimitiveValue;
+export type UUID = string | number | boolean;
 
 // // This class is here to distinguish UUIDs from ordinary strings
 // export class UUID {

+ 8 - 9
src/onion/version.test.ts

@@ -14,7 +14,6 @@ import {
 import {
   NodeCreation,
   NodeDeletion,
-  EdgeCreation,
   EdgeUpdate,
 } from "./delta";
 
@@ -22,7 +21,7 @@ import {DeltaRegistry} from "./delta_registry";
 
 import {
   mockUuid,
-} from "./test_helpers";
+} from "../util/test_helpers";
 
 import {
   assert,
@@ -145,13 +144,13 @@ describe("Version", () => {
       const Z = deltaRegistry.newNodeCreation(getId());
 
       const A = deltaRegistry.newNodeDeletion(X, [], []);
-      const B = deltaRegistry.newEdgeCreation(X, "label", Y); // conflicts with A
-      assert(_.isEqual(B.getConflicts(), [A]), "Expected B to conflict with A");
-      const C = deltaRegistry.newEdgeCreation(Y, "label", Z);
-      const BB = deltaRegistry.newEdgeUpdate(B, null); // unset edge B.
+      const B = deltaRegistry.newEdgeUpdate(X.createOutgoingEdge("label"), Y); // conflicts with A
+      assert(_.isEqual(B.conflictsWith, [A]), "Expected B to conflict with A");
+      const C = deltaRegistry.newEdgeUpdate(Y.createOutgoingEdge("label"), Z);
+      const BB = deltaRegistry.newEdgeUpdate(B.overwrite(), null); // unset edge B.
       const D = deltaRegistry.newNodeDeletion(Y, [], [BB]); // conflicts with C
 
-      assert(_.isEqual(D.getConflicts(), [C]), "Expected D to conflict with C");
+      assert(_.isEqual(D.conflictsWith, [C]), "Expected D to conflict with C");
 
       const nameMap: Map<Delta, string> = new Map<Delta,string>([
         [X, "X"],
@@ -219,7 +218,7 @@ describe("Version", () => {
       for (let i=0; i<HOW_MANY; i++) {
         const creation = deltaRegistry.newNodeCreation(getId());
         const deletion = deltaRegistry.newNodeDeletion(creation, [], []);
-        const edge = deltaRegistry.newEdgeCreation(creation, "l", creation); // conflicts with deletion0
+        const edge = deltaRegistry.newEdgeUpdate(creation.createOutgoingEdge("l"), creation); // conflicts with deletion0
 
         creations.push(creation);
         deletions.push(deletion);
@@ -256,7 +255,7 @@ describe("Version", () => {
 
 
       const hostCreate = deltaRegistry.newNodeCreation(getId());
-      const hostLink = deltaRegistry.newEdgeCreation(hostCreate, "guest", guestCreate);
+      const hostLink = deltaRegistry.newEdgeUpdate(hostCreate.createOutgoingEdge("guest"), guestCreate);
       const compCreate = deltaRegistry.newTransaction([guestCreate, hostCreate, hostLink], "");
       const hostV1 = registry.createVersion(registry.initialVersion, compCreate, () => new Map([
         ["guest", {version: guestV1, overridings: new Map()}], // no overridings

+ 2 - 2
src/parser/rountangle_parser.test.ts

@@ -73,10 +73,10 @@ import {assert} from "../util/assert";
 //     const asV0 = asRegistry.initialVersion;
 
 //     const csCreation = deltaRegistry.newNodeCreation(getUuid());
-//     const csCreateEdge = deltaRegistry.newEdgeCreation(csCreation, "x", csCreation); // self-edge
+//     const csCreateEdge = deltaRegistry.newEdgeUpdate(csCreation.createOutgoingEdge("x"), csCreation); // self-edge
 //     const csUnsetEdge = deltaRegistry.newEdgeUpdate(csCreateEdge, null);
 //     const csDeletion = deltaRegistry.newNodeDeletion(csCreation, [csUnsetEdge], [csUnsetEdge]);
-//     assert(csDeletion.getConflicts().length === 0, "expected CS deletion to not have conflicts (yet).");
+//     assert(csDeletion.conflictsWith.length === 0, "expected CS deletion to not have conflicts (yet).");
 
 //     const csTransactions = [
 //       csLvl.createComposite([csCreation]),

+ 6 - 6
src/parser/rountangle_parser.ts

@@ -127,7 +127,7 @@ export class RountangleParser  {
         else if (sourceDelta instanceof NodeDeletion) {
           const sourceDeletion = sourceDelta; // alias for readability :)
           const sourceCreation = sourceDeletion.creation; // the NodeCreation of the deleted cs node
-          const sourceId = sourceCreation.id.value;
+          const sourceId = sourceCreation.id;
 
           // Follow 'cs'/'as' edges in correspondence model to find the corresponding node:
           const sourceNodeState = corrState.nodes.get(sourceId)!;
@@ -142,7 +142,7 @@ export class RountangleParser  {
 
           // We create 2 asDeletions:
           // one that is to be used only in the AS model, unaware of any CORR-stuff, and one that is to be used in the CORR model.
-          const targetDeletion = targetState.nodes.get(targetNodeState.creation.id.value)!.getDeltasForDelete(this.deltaRegistry);
+          const targetDeletion = targetState.nodes.get(targetNodeState.creation.id)!.getDeltasForDelete(this.deltaRegistry);
           const targetDeletion1 = targetNodeState.getDeltasForDelete(this.deltaRegistry);
 
           applyToState(corrState, targetDeletion1);
@@ -193,7 +193,7 @@ export class RountangleParser  {
           }
 
           if (geometryLabels.includes(label)) {
-            const updatedNodeId = edgeCreation.source.id.value;
+            const updatedNodeId = edgeCreation.source.id;
             const updatedGeometry = getGeometry(sourceState, updatedNodeId);
             if (updatedGeometry !== undefined) {
               const updatedSurface = updatedGeometry.w * updatedGeometry.h;
@@ -240,7 +240,7 @@ export class RountangleParser  {
               const otherAsNodeState = updatedAsNode.getOutgoingEdges().get("hasParent");
               if (otherAsNodeState !== undefined && otherAsNodeState.type === "node") {
                 const otherCsNodeState = findCorrespondingAsNode(otherAsNodeState, true);
-                const otherNodeId = otherCsNodeState.creation.id.value;
+                const otherNodeId = otherCsNodeState.creation.id;
                 const otherGeometry = getGeometry(sourceState, otherNodeId);
                 if (otherGeometry === undefined || !isInside(updatedGeometry, otherGeometry)) {
                   // parent relation no longer holds
@@ -254,7 +254,7 @@ export class RountangleParser  {
               // 1.b. incoming parent links
               for (const [_, otherAsNodeState] of updatedAsNode.getIncomingEdges().filter(([label, ns]) => label === "hasParent")) {
                 const otherCsNodeState = findCorrespondingAsNode(otherAsNodeState, true);
-                const otherNodeId = otherCsNodeState.creation.id.value;
+                const otherNodeId = otherCsNodeState.creation.id;
                 const otherGeometry = getGeometry(sourceState, otherNodeId);
                 if (otherGeometry === undefined) {
                   throw new Error("Assertion failed: The Corresponding CS node of an AS node that is target of 'hasParent' has no geometry.");
@@ -296,7 +296,7 @@ export class RountangleParser  {
                         return Infinity;
                       }
                       const otherCurrentParentCs = findCorrespondingAsNode(otherCurrentParent as INodeState, true);
-                      const otherCurrentParentGeometry = getGeometry(sourceState, otherCurrentParentCs.creation.id.value);
+                      const otherCurrentParentGeometry = getGeometry(sourceState, otherCurrentParentCs.creation.id);
                       if (otherCurrentParentGeometry === undefined) {
                         return Infinity;
                       }

+ 26 - 1
todo.txt

@@ -38,4 +38,29 @@ Todo, when I find the time:
 - A NodeDeletion also unsets all outgoing edges of a node. Incoming edges must be unset by EdgeUpdates, and the NodeDeletion must depend on these EdgeUpdates. Maybe it will make the implementation (of conflict checking) simpler if a NodeDeletion would *not* automatically unset outgoing edges, and instead also would have to depend on EdgeUpdates that un-set the nodes?
    Pro: Simpler conflict-checking code
    Pro: Related to the previous, will also make the addition of read-dependencies easier to implement.
-   Pro: Easier to explain to people
+   Pro: Easier to explain to people
+
+
+- Add meta-models and conformance checking
+- Add action language to FSA
+- Add concrete syntax
+- Add neutral action language for graph operations
+   see ModelVerse specification.
+  implement VF2, ... on top of this action language.
+  -. Then bootstrap.
+      => look at Scheme
+
+
+Cip:
+   - maybe when live modeling alone, don't need to know dependencies, conflicts, between deltas
+   - maybe only need two kinds of dependencies: Reads and Writes.
+   - consistency checking on append-only set:
+         look into database theory, eventual consistency to enable concurrent read/write access
+
+
+   - nicer visualization for graphs:
+         render them as objects/tables (can be done with graphviz)
+   - interaction nets:
+       the optimal implementatoin of functional languages
+       (nice rabbit hole)
+       garbage collection for free