All files / src/components graph-view.js

50.93% Statements 220/432
38.61% Branches 144/373
46.34% Functions 38/82
51.16% Lines 220/430
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228                                                                                                                                                            76x 76x 76x 76x 76x     76x       76x         76x 76x 76x 76x     76x                                 76x                               54x   54x 54x 54x 54x   54x   54x 54x     54x                                           54x 54x   54x               54x               54x       54x   54x                       98x               22x   76x       22x   22x 22x 22x 22x               22x         22x         22x         22x       22x           12x       2x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         6x   6x                   5x       1x 1x 1x     1x     1x 1x 1x       1x 1x 1x   1x       2x 2x 2x 1x     1x 1x       1x 1x 1x 1x 1x               4x 4x   4x 3x     3x 2x           2x     1x 1x 1x         4x   4x 4x 2x     1x       2x         2x     2x 2x               2x 2x     2x     2x 2x           2x 2x 2x                             5x 5x 5x 5x   5x 5x 5x 5x   5x           5x   4x 4x 4x 4x 4x   4x 1x 3x 1x     4x 4x     5x         4x 4x       4x 4x   4x           4x 4x   4x 2x     2x         2x         2x 2x 2x 2x                                   55x   55x 55x       78x 78x 1x   77x         3x 3x                                               2x 2x   2x 1x 1x 1x         2x 2x       2x 1x     1x 1x   1x 1x         1x 1x 1x 1x 1x         1x 1x 1x 1x 1x 1x 1x         2x 1x     1x 2x         5x             3x 3x 3x 3x 3x 3x   3x                               2x 2x 2x 2x 2x 2x       2x 1x 1x 1x 1x     2x 1x 1x 1x 1x       2x 2x 2x             1x     1x 1x 1x 1x           2x         2x 2x 2x 2x         3x 2x     1x 2x                     2x 1x     1x 1x 1x                             76x 76x                                                        
// @flow
/*
  Copyright(c) 2018 Uber Technologies, Inc.
 
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at
 
          http://www.apache.org/licenses/LICENSE-2.0
 
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/
 
import * as d3 from 'd3';
import * as React from 'react';
import ReactDOM from 'react-dom';
import '../styles/main.scss';
 
import { LayoutEngines } from '../utilities/layout-engine/layout-engine-config';
import { type LayoutEngineType } from '../utilities/layout-engine/layout-engine-types';
import { type IGraphViewProps } from './graph-view-props';
import Background from './background';
import Defs from './defs';
import Edge, { type IEdge, type ITargetPosition } from './edge';
import GraphControls from './graph-controls';
import GraphUtils, { type INodeMapNode } from './graph-util';
import Node, { type INode } from './node';
import { Transform } from 'stream';
 
type IViewTransform = {
  k: number,
  x: number,
  y: number
}
 
type IGraphViewState = {
  viewTransform?: IViewTransform;
  hoveredNode: boolean;
  nodesMap: any;
  edgesMap: any;
  nodes: any[];
  edges: any[];
  selectingNode: boolean;
  hoveredNodeData: INode | null;
  edgeEndNode: INode | null;
  draggingEdge: boolean;
  draggedEdge: any;
  componentUpToDate: boolean;
  selectedEdgeObj: any;
  selectedNodeObj: any;
  documentClicked: boolean;
  svgClicked: boolean;
  focused: boolean;
};
 
class GraphView extends React.Component<IGraphViewProps, IGraphViewState> {
  static defaultProps = {
    canCreateEdge: (startNode?:INode, endNode?:INode) => true,
    canDeleteEdge: () => true,
    canDeleteNode: () => true,
    edgeArrowSize: 8,
    gridSpacing: 36,
    layoutEngineType: 'None',
    maxTitleChars: 9,
    maxZoom: 1.5,
    minZoom: 0.15,
    nodeSize: 154,
    readOnly: false,
    showGraphControls: true,
    zoomDelay: 1000,
    zoomDur: 750
  };
 
  static getDerivedStateFromProps(nextProps: IGraphViewProps, prevState: IGraphViewState) {
    const { edges, nodeKey } = nextProps;
    let nodes = nextProps.nodes;
    const nodesMap = GraphUtils.getNodesMap(nodes, nodeKey);
    const edgesMap = GraphUtils.getEdgesMap(edges);
    GraphUtils.linkNodesAndEdges(nodesMap, edges);
 
    const selectedNodeMap =
      nextProps.selected && nodesMap[`key-${nextProps.selected[nodeKey]}`]
        ? nodesMap[`key-${nextProps.selected[nodeKey]}`]
        : null;
    const selectedEdgeMap =
      nextProps.selected && edgesMap[`${nextProps.selected.source}_${nextProps.selected.target}`]
        ? edgesMap[`${nextProps.selected.source}_${nextProps.selected.target}`]
        : null;
 
    // Handle layoutEngine on initial render
    Eif (prevState.nodes.length === 0 && nextProps.layoutEngineType && LayoutEngines[nextProps.layoutEngineType]) {
      const layoutEngine = new LayoutEngines[nextProps.layoutEngineType](nextProps);
      const newNodes = layoutEngine.adjustNodes(nodes, nodesMap);
      nodes = newNodes;
    }
 
    const nextState = {
      componentUpToDate: true,
      edges,
      edgesMap,
      nodes,
      nodesMap,
      readOnly: nextProps.readOnly,
      selectedEdgeObj: {
        edge: selectedEdgeMap ? edges[selectedEdgeMap.originalArrIndex] : null
      },
      selectedNodeObj: {
        index: selectedNodeMap ? selectedNodeMap.originalArrIndex : -1,
        node: selectedNodeMap ? nodes[selectedNodeMap.originalArrIndex] : null
      },
      selectionChanged: false
    };
 
    return nextState;
  }
 
  nodeTimeouts: any;
  edgeTimeouts: any;
  renderNodesTimeout: any;
  renderEdgesTimeout: any;
  zoom: any;
  viewWrapper: any;
  entities: any;
  selectedView: any;
  view: any;
  graphControls: any;
  layoutEngine: any;
 
  constructor(props: IGraphViewProps) {
    super(props);
 
    this.nodeTimeouts = {};
    this.edgeTimeouts = {};
    this.renderNodesTimeout = null;
    this.renderEdgesTimeout = null;
 
    this.graphControls = React.createRef();
 
    Eif (props.layoutEngineType) {
      this.layoutEngine = new LayoutEngines[props.layoutEngineType](props);
    }
 
    this.state = {
      componentUpToDate: false,
      draggedEdge: null,
      draggingEdge: false,
      edgeEndNode: null,
      edges: [],
      edgesMap: {},
      hoveredNode: false,
      hoveredNodeData: null,
      nodes: [],
      nodesMap: {},
      selectedEdgeObj: null,
      selectedNodeObj: null,
      selectingNode: false,
      documentClicked: false,
      svgClicked: false,
      focused: true
    };
  }
 
  componentDidMount() {
    // TODO: can we target the element rather than the document?
    document.addEventListener('keydown', this.handleWrapperKeydown);
    document.addEventListener('click', this.handleDocumentClick);
 
    this.zoom = d3
      .zoom()
      .filter(this.zoomFilter)
      .scaleExtent([this.props.minZoom || 0, this.props.maxZoom || 0])
      .on('start', this.handleZoomStart)
      .on('zoom', this.handleZoom)
      .on('end', this.handleZoomEnd);
 
    d3
      .select(this.viewWrapper)
      .on('touchstart', this.containZoom)
      .on('touchmove', this.containZoom)
      .on('click', this.handleSvgClicked) // handle element click in the element components
      .select('svg')
      .call(this.zoom);
 
    this.selectedView = d3.select(this.view);
 
    // On the initial load, the 'view' <g> doesn't exist until componentDidMount.
    // Manually render the first view.
    this.renderView();
 
    setTimeout(() => {
      if (this.viewWrapper != null) {
        this.handleZoomToFit();
      }
    }, this.props.zoomDelay);
  }
 
  componentWillUnmount() {
    document.removeEventListener('keydown', this.handleWrapperKeydown);
  }
 
  shouldComponentUpdate(nextProps: IGraphViewProps, nextState: IGraphViewState) {
    if (
      nextProps.nodes !== this.props.nodes ||
      nextProps.edges !== this.props.edges ||
      !nextState.componentUpToDate ||
      nextProps.selected !== this.props.selected ||
      nextProps.readOnly !== this.props.readOnly ||
      nextProps.layoutEngineType !== this.props.layoutEngineType
    ) {
      return true;
    }
    return false;
  }
 
  componentDidUpdate(prevProps: IGraphViewProps, prevState: IGraphViewState) {
    const { nodesMap, edgesMap, nodes } = this.state;
 
    Eif (this.props.layoutEngineType && LayoutEngines[this.props.layoutEngineType]) {
      this.layoutEngine = new LayoutEngines[this.props.layoutEngineType](this.props);
      const newNodes = this.layoutEngine.adjustNodes(nodes, nodesMap);
      this.setState({
        nodes: newNodes
      });
    }
 
    // Note: the order is intentional Do not save the timeouts to variables, as
    // subsequent render calls could overwrite timeouts and not render new additions
    // or deletions.
    setTimeout(() => {
      this.addNewNodes(this.state.nodes, prevState.nodesMap);
    });
 
    // add new edges
    setTimeout(() => {
      this.addNewEdges(this.state.edges, prevState.edgesMap);
    });
 
    // remove old edges
    setTimeout(() => {
      this.removeOldEdges(prevState.edges, edgesMap);
    });
 
    // remove old nodes
    setTimeout(() => {
      this.removeOldNodes(prevState.nodesMap, nodesMap);
    });
 
    this.setState({
      componentUpToDate: true
    });
  }
 
  getNodeById(id: string | null): INodeMapNode | null {
    return this.state.nodesMap ? this.state.nodesMap[`key-${id || ''}`] : null;
  }
 
  getEdgeBySourceTarget(source: string, target: string): IEdge | null {
    return this.state.edgesMap ? this.state.edgesMap[`${source}_${target}`] : null;
  }
 
  deleteNodeById(id: string) {
    if (this.state.nodesMap && this.state.nodesMap[`key-${id}`]) {
      delete this.state.nodesMap[`key-${id}`];
    }
  }
 
  deleteEdgeBySourceTarget(source: string, target: string) {
    if (this.state.edgesMap && this.state.edgesMap[`${source}_${target}`]) {
      delete this.state.edgesMap[`${source}_${target}`];
    }
  }
 
  addNewNodes(nodes: INode[], oldNodesMap: any) {
    if (this.state.draggingEdge) {
      return;
    }
    const nodeKey = this.props.nodeKey;
    nodes.forEach((node, i) => {
      const prevNode = oldNodesMap[`key-${node[nodeKey]}`];
      if (prevNode && node !== prevNode.node) {
        // Nodes must be immutable. A node with the same key must not have the same memory reference.
        // Update individual node
        this.asyncRenderNode(node, i);
      } else {
        // New node
        this.asyncRenderNode(node, i);
      }
    });
  }
 
  removeOldNodes(prevNodeMap: any, nodesMap: any) {
    const nodeKey = this.props.nodeKey;
    // remove old nodes
    Object.keys(prevNodeMap).forEach((nodeId) => {
      // Check for deletions
      if (!nodesMap[nodeId]) {
        // remove all outgoing edges
        prevNodeMap[nodeId].outgoingEdges.forEach((edge) => {
          this.removeEdgeElement(edge.source, edge.target);
        });
 
        // remove all incoming edges
        prevNodeMap[nodeId].incomingEdges.forEach((edge) => {
          this.removeEdgeElement(edge.source, edge.target);
        });
 
        // remove node
        const id = prevNodeMap[nodeId].node[nodeKey];
        GraphUtils.removeElementFromDom(`node-${id}-container`);
      }
    });
  }
 
  addNewEdges(edges: IEdge[], oldEdgesMap: any) {
    if (!this.state.draggingEdge) {
      edges.forEach((edge) => {
        if (!edge.source || !edge.target) {
          return;
        }
        const prevEdge = oldEdgesMap[`${edge.source}_${edge.target}`];
        if (!prevEdge) {
          // new edge
          this.asyncRenderEdge(edge);
        }
      });
    }
  }
 
  removeOldEdges = (prevEdges: IEdge[], edgesMap: any) => {
    // remove old edges
    prevEdges.forEach((edge) => {
      // Check for deletions
      if (!edge.source || !edge.target) {
        return;
      }
      if (!edgesMap[`${edge.source}_${edge.target}`]) {
        // remove edge
        this.removeEdgeElement(edge.source, edge.target);
      }
    });
  }
 
  removeEdgeElement(source: string, target: string) {
    const id = `${source}-${target}`;
    GraphUtils.removeElementFromDom(`edge-${id}-container`);
  }
 
  canSwap(sourceNode: INode, hoveredNode: INode | null, swapEdge: any) {
    return (
      hoveredNode &&
      sourceNode !== hoveredNode &&
      (swapEdge.source !== sourceNode[this.props.nodeKey] ||
        swapEdge.target !== hoveredNode[this.props.nodeKey])
    );
  }
 
  deleteNode(selectedNode: INode) {
    const { nodeKey } = this.props;
    const { nodes } = this.state;
 
    const nodeId = selectedNode[nodeKey];
    const originalArrIndex = (this.getNodeById(nodeId): any).originalArrIndex;
 
    // delete from local state
    this.deleteNodeById(nodeId);
    nodes.splice(originalArrIndex, 1);
    this.setState({
      componentUpToDate: false,
      hoveredNode: false,
      nodes
    });
 
    // remove from UI
    GraphUtils.removeElementFromDom(`node-${nodeId}-container`);
 
    // inform consumer
    this.props.onSelectNode(null);
    this.props.onDeleteNode(selectedNode, originalArrIndex, nodes);
  }
 
  deleteEdge(selectedEdge: IEdge) {
    const { edges } = this.state;
    if (!selectedEdge.source || !selectedEdge.target) {
      return;
    }
 
    const originalArrIndex = (this.getEdgeBySourceTarget(selectedEdge.source, selectedEdge.target): any).originalArrIndex;
 
    edges.splice(originalArrIndex, 1);
    if (selectedEdge.source && selectedEdge.target) {
      this.deleteEdgeBySourceTarget(selectedEdge.source, selectedEdge.target);
    }
 
    this.setState({
      componentUpToDate: false,
      edges
    });
 
    // remove from UI
    if (selectedEdge.source && selectedEdge.target) {
      GraphUtils.removeElementFromDom(`edge-${selectedEdge.source}-${selectedEdge.target}-container`);
    }
 
    // inform consumer
    this.props.onDeleteEdge(selectedEdge, originalArrIndex, edges);
  }
 
  handleDelete = (selected: IEdge | INode) => {
    const { canDeleteNode, canDeleteEdge, readOnly } = this.props;
 
    if (readOnly || !selected) { return; }
 
    if (!selected.source && canDeleteNode && canDeleteNode(selected)) {
      // node
      // $FlowFixMe
      this.deleteNode(selected);
    } else if (selected.source && canDeleteEdge && canDeleteEdge(selected)) {
      // edge
      // $FlowFixMe
      this.deleteEdge(selected);
    }
  }
 
  handleWrapperKeydown: KeyboardEventListener = (d) => {
    // Conditionally ignore keypress events on the window
    if (!this.state.focused) {
      return;
    }
    switch (d.key) {
      case 'Delete':
      case 'Backspace':
        if (this.state.selectedNodeObj) {
          this.handleDelete(this.state.selectedNodeObj.node || this.props.selected);
        }
        break;
      case 'z':
        if ((d.metaKey || d.ctrlKey) && this.props.onUndo) {
          this.props.onUndo();
        }
        break;
      case 'c':
        if ((d.metaKey || d.ctrlKey) && this.state.selectedNodeObj.node && this.props.onCopySelected) {
          this.props.onCopySelected();
        }
        break;
      case 'v':
        if ((d.metaKey || d.ctrlKey) && this.state.selectedNodeObj.node && this.props.onPasteSelected) {
          this.props.onPasteSelected();
        }
        break;
      default:
        break;
    }
  }
 
  handleEdgeSelected = (e) => {
    const { source, target } = e.target.dataset;
    let newState = {
      svgClicked: true
    };
    if (source && target) {
      const edge: IEdge | null = this.getEdgeBySourceTarget(source, target);
 
      if (!edge) {
        return;
      }
      const originalArrIndex = (this.getEdgeBySourceTarget(source, target): any).originalArrIndex;
      const previousSelection = (this.state.selectedEdgeObj && this.state.selectedEdgeObj.edge) || null;
      newState = {
        ...newState,
        selectedEdgeObj: {
          componentUpToDate: false,
          edge: this.state.edges[originalArrIndex]
        }
      }
      this.setState(newState);
      this.syncRenderEdge(this.state.edges[originalArrIndex]);
      if (previousSelection) {
        this.syncRenderEdge(previousSelection);
      }
      this.props.onSelectEdge(this.state.edges[originalArrIndex]);
    } else {
      this.setState(newState);
    }
  }
 
  handleSvgClicked = (d: any, i: any) => {
    if (this.isPartOfEdge(d3.event.target)) {
      this.handleEdgeSelected(d3.event);
      return; // If any part of the edge is clicked, return
    }
 
    if (this.state.selectingNode) {
      this.setState({
        selectingNode: false,
        svgClicked: true
      });
    } else {
      const previousSelection = (this.state.selectedNodeObj && this.state.selectedNodeObj.node) || null;
      const previousSelectionIndex = (this.state.selectedNodeObj && this.state.selectedNodeObj.index) || -1;
 
      // de-select the current selection
      this.setState({
        selectedNodeObj: null,
        focused: true,
        svgClicked: true
      });
      this.props.onSelectNode(null);
      if (previousSelection) {
        this.syncRenderNode(previousSelection, previousSelectionIndex);
      }
 
      if (!this.props.readOnly && d3.event.shiftKey) {
        const xycoords = d3.mouse(d3.event.target);
        this.props.onCreateNode(xycoords[0], xycoords[1]);
      }
    }
  }
 
 
  handleDocumentClick = () => {
    this.setState({
      documentClicked: true,
      focused: this.state.svgClicked,
      svgClicked: false
    });
  }
 
  isPartOfEdge(element) {
    return !!GraphUtils.findParent(element, '.edge-container');
  }
 
  handleNodeMove = (position: any, index: number, shiftKey: boolean) => {
    const node = this.state.nodes[index];
    const { nodeKey, canCreateEdge, readOnly } = this.props;
    if (readOnly) {
      return;
    }
    if (!shiftKey) {
      node.x = position.x;
      node.y = position.y;
 
      // Update edges synchronously because async doesn't update fast enough
      const nodeMapNode: INodeMapNode | null = this.getNodeById(node[nodeKey]);
 
      if (!nodeMapNode) {
        return;
      }
 
      this.syncRenderConnectedEdgesFromNode(nodeMapNode, true);
    } else if (canCreateEdge && canCreateEdge(node[nodeKey])) {
      // render new edge
      this.syncRenderEdge({ source: node[nodeKey], targetPosition: position });
      this.setState({ draggingEdge: true });
    }
  }
 
  createNewEdge() {
    const { canCreateEdge, nodeKey, onCreateEdge } = this.props;
    const { edgesMap, edgeEndNode, hoveredNodeData } = this.state;
    if (!hoveredNodeData) {
      return;
    }
    GraphUtils.removeElementFromDom('edge-custom-container');
    if (edgeEndNode) {
      const mapId1 = `${hoveredNodeData[nodeKey]}_${edgeEndNode[nodeKey]}`;
      const mapId2 = `${edgeEndNode[nodeKey]}_${hoveredNodeData[nodeKey]}`;
      if (
        edgesMap &&
        hoveredNodeData !== edgeEndNode &&
        canCreateEdge &&
        canCreateEdge(hoveredNodeData, edgeEndNode) &&
        !edgesMap[mapId1] &&
        !edgesMap[mapId2]
      ) {
        const edge: IEdge = {
          source: hoveredNodeData[nodeKey],
          target: edgeEndNode[nodeKey]
        };
        this.setState({
          componentUpToDate: false,
          draggedEdge: null,
          draggingEdge: false,
        });
 
        // this syncRenderEdge will render the edge as un-selected.
        this.syncRenderEdge(edge);
        // we expect the parent website to set the selected property to the new edge when it's created
        onCreateEdge(hoveredNodeData, edgeEndNode);
      } else {
        // make the system understand that the edge creation process is done even though it didn't work.
        this.setState({
          edgeEndNode: null,
          draggingEdge: false,
        });
      }
    }
  }
 
  handleNodeUpdate = (position: any, index: number, shiftKey: boolean) => {
    const { onUpdateNode } = this.props;
    const { nodes } = this.state;
 
    // Detect if edge is being drawn and link to hovered node
    // This will handle a new edge
    if (shiftKey) {
      this.createNewEdge();
    } else {
      const node = nodes[index];
      if (node) {
        Object.assign(node, position);
        onUpdateNode(node);
      }
    }
    // force a re-render
    this.setState({
      componentUpToDate: false,
      // Setting hoveredNode to false here because the layout engine doesn't
      // fire the mouseLeave event when nodes are moved.
      hoveredNode: false
    });
  }
 
  handleNodeMouseEnter = (event: any, data: any, hovered: boolean) => {
    // hovered is false when creating edges
    if (hovered && !this.state.hoveredNode) {
      this.setState({
        hoveredNode: true,
        hoveredNodeData: data
      });
    } else if (!hovered && this.state.hoveredNode && this.state.draggingEdge) {
      this.setState({
        edgeEndNode: data
      });
    } else {
      this.setState({
        hoveredNode: true,
        hoveredNodeData: data
      });
    }
  }
 
  handleNodeMouseLeave = (event: any, data: any) => {
    if (
      (d3.event && d3.event.toElement && GraphUtils.findParent(d3.event.toElement, '.node')) ||
      (event && event.relatedTarget && GraphUtils.findParent(event.relatedTarget, '.node')) ||
      (d3.event && d3.event.buttons === 1) ||
      (event && event.buttons === 1)
    ) {
      // still within a node
      return;
    }
    if (event && event.relatedTarget) {
      if (event.relatedTarget.classList.contains('edge-overlay-path')) {
        return;
      }
      this.setState({ hoveredNode: false, edgeEndNode: null });
    }
  }
 
  handleNodeSelected = (node: INode, index: number, creatingEdge: boolean) => {
    // if creatingEdge then de-select nodes and select new edge instead
    const previousSelection = (this.state.selectedNodeObj && this.state.selectedNodeObj.node) || null;
    const previousSelectionIndex = previousSelection ? this.state.selectedNodeObj.index : -1;
    const newState = {
      componentUpToDate: false,
      selectedNodeObj: {
        index,
        node
      }
    };
    this.setState(newState);
 
    // render both previous selection and new selection
    this.syncRenderNode(node, index);
    if (previousSelection) {
      this.syncRenderNode(previousSelection, previousSelectionIndex);
    }
 
    if (!creatingEdge) {
      this.props.onSelectNode(node);
    }
  }
 
  // One can't attach handlers to 'markers' or obtain them from the event.target
  // If the click occurs within a certain radius of edge target, assume the click
  // occurred on the arrow
  isArrowClicked(edge: IEdge | null) {
    const { nodeSize, edgeArrowSize } = this.props;
    const eventTarget = d3.event.sourceEvent.target;
    const arrowSize = edgeArrowSize || 0;
    if (!edge || eventTarget.tagName !== 'path') {
      return false; // If the handle is clicked
    }
 
    const xycoords = d3.mouse(eventTarget);
    if (!edge.target) {
      return false;
    }
    const targetNodeMapNode = this.getNodeById(edge.target);
    const source = {
      x: xycoords[0],
      y: xycoords[1]
    };
    const edgeCoords = Edge.parsePathToXY(Edge.getEdgePathElement(edge));
 
    // the arrow is clicked if the xycoords are within edgeArrowSize of edgeCoords.target[x,y]
    return (
      source.x < edgeCoords.target.x + arrowSize &&
      source.x > edgeCoords.target.x - arrowSize &&
      source.y < edgeCoords.target.y + arrowSize &&
      source.y > edgeCoords.target.y - arrowSize
    );
  }
 
  zoomFilter() {
    if (d3.event.button || d3.event.ctrlKey) {
      return false;
    }
    return true;
  }
 
  // Keeps 'zoom' contained
  containZoom() {
    const stop = d3.event.button || d3.event.ctrlKey;
    if (stop) {
      d3.event.stopImmediatePropagation(); // stop zoom
    }
    d3.event.preventDefault();
  }
 
  handleZoomStart = () => {
    // Zoom start events also handle edge clicks. We need to determine if an edge
    // was clicked and deal with that scenario.
    const sourceEvent = d3.event.sourceEvent;
 
    if (
      // graph can't be modified
      this.props.readOnly ||
      // no sourceEvent, not an action on an element
      !sourceEvent ||
      // not a click event
      (sourceEvent && !sourceEvent.buttons) ||
      // not an edge click area
      (sourceEvent && !sourceEvent.target.classList.contains('edge-overlay-path'))
    ) {
      return false;
    }
 
    // Clicked on the edge.
    const { target } = sourceEvent;
    const edgeId = target.id;
    const edge = this.state.edgesMap && this.state.edgesMap[edgeId] ? this.state.edgesMap[edgeId].edge : null;
 
    // Only move edges if the arrow is dragged
    Iif (!this.isArrowClicked(edge) || !edge) {
      return false;
    }
    this.removeEdgeElement(edge.source, edge.target);
    this.setState({ draggingEdge: true, draggedEdge: edge });
    this.dragEdge(edge);
  }
 
  getMouseCoordinates() {
    let mouseCoordinates = [0, 0];
    Eif (this.selectedView) {
      mouseCoordinates = d3.mouse(this.selectedView.node());
    }
    return mouseCoordinates;
  }
 
  dragEdge(draggedEdge?: IEdge) {
    const { nodeSize, nodeKey } = this.props;
    draggedEdge = draggedEdge || this.state.draggedEdge;
    if (!draggedEdge) {
      return;
    }
 
    const mouseCoordinates = this.getMouseCoordinates();
    const targetPosition = {
      x: mouseCoordinates[0],
      y: mouseCoordinates[1]
    };
    const off = Edge.calculateOffset(nodeSize, (this.getNodeById(draggedEdge.source): any).node, targetPosition, nodeKey);
    targetPosition.x += off.xOff;
    targetPosition.y += off.yOff;
    this.syncRenderEdge({ source: draggedEdge.source, targetPosition });
    this.setState({
      draggedEdge,
      draggingEdge: true
    });
  }
 
  // View 'zoom' handler
  handleZoom = () => {
    const { draggingEdge, draggedEdge, hoveredNode } = this.state;
    const transform: IViewTransform = d3.event.transform;
 
    if (!draggingEdge) {
      d3.select(this.view).attr('transform', transform);
 
      // prevent re-rendering on zoom
      if (this.state.viewTransform !== transform) {
        this.setState({
          viewTransform: transform,
          draggedEdge: null,
          draggingEdge: false
        }, () => {
          // force the child components which are related to zoom level to update
          this.renderGraphControls();
        });
      }
    } else Eif (draggingEdge) {
      this.dragEdge();
      return false;
    }
  }
 
  handleZoomEnd = () => {
    const { draggingEdge, draggedEdge, edgeEndNode, edgesMap } = this.state;
 
    const { nodeKey } = this.props;
    if (!draggingEdge || !draggedEdge) {
      if (draggingEdge && !draggedEdge) {
        // This is a bad case, sometimes when the graph loses focus while an edge
        // is being created it doesn't set draggingEdge to false. This fixes that case.
        this.setState({
          draggingEdge: false
        });
      }
      return;
    }
 
    // Zoom start events also handle edge clicks. We need to determine if an edge
    // was clicked and deal with that scenario.
    const draggedEdgeCopy = { ...this.state.draggedEdge };
 
    // remove custom edge
    GraphUtils.removeElementFromDom('edge-custom-container');
    this.setState(
      {
        draggedEdge: null,
        draggingEdge: false,
        hoveredNode: false
      },
      () => {
        // handle creating or swapping edges
        const sourceNodeById = this.getNodeById(draggedEdge.source);
        const targetNodeById = this.getNodeById(draggedEdge.target);
 
 
        Iif (!sourceNodeById || !targetNodeById) {
          return;
        }
        const sourceNode = sourceNodeById.node;
        Eif (
          edgeEndNode &&
          !this.getEdgeBySourceTarget(draggedEdge.source, edgeEndNode[nodeKey]) &&
          this.canSwap(sourceNode, edgeEndNode, draggedEdge)
        ) {
          // determine the target node and update the edge
          draggedEdgeCopy.target = edgeEndNode[nodeKey];
          this.syncRenderEdge(draggedEdgeCopy);
          this.props.onSwapEdge(
            sourceNodeById.node,
            edgeEndNode,
            draggedEdge
          );
        } else {
          // this resets the dragged edge back to its original position.
          this.syncRenderEdge(draggedEdge);
        }
      }
    );
  }
 
  // Zooms to contents of this.refs.entities
  handleZoomToFit = () => {
    const parent = d3.select(this.viewWrapper).node();
    const entities = d3.select(this.entities).node();
    const viewBBox = entities.getBBox ? entities.getBBox() : null;
    Iif (!viewBBox) { return; }
 
    const width = parent.clientWidth;
    const height = parent.clientHeight;
    const minZoom = this.props.minZoom || 0;
    const maxZoom = this.props.maxZoom || 2;
 
    const next = {
      k: (minZoom + maxZoom) / 2,
      x: 0,
      y: 0,
    };
 
    if (viewBBox.width > 0 && viewBBox.height > 0) {
      // There are entities
      const dx = viewBBox.width;
      const dy = viewBBox.height;
      const x = viewBBox.x + viewBBox.width / 2;
      const y = viewBBox.y + viewBBox.height / 2;
      next.k = 0.9 / Math.max(dx / width, dy / height);
 
      if (next.k < minZoom) {
        next.k = minZoom;
      } else if (next.k > maxZoom) {
        next.k = maxZoom;
      }
 
      next.x = width / 2 - next.k * x;
      next.y = height / 2 - next.k * y;
    }
 
    this.setZoom(next.k, next.x, next.y, this.props.zoomDur);
  }
 
  // Updates current viewTransform with some delta
  modifyZoom = (modK: number = 0, modX: number = 0, modY: number = 0, dur: number = 0) => {
    const parent = d3.select(this.viewWrapper).node();
    const center = {
      x: parent.clientWidth / 2,
      y: parent.clientHeight / 2
    };
    const extent = this.zoom.scaleExtent();
    const viewTransform: any = this.state.viewTransform;
 
    const next = {
      k: viewTransform.k,
      x: viewTransform.x,
      y: viewTransform.y
    };
 
    const targetZoom = next.k * (1 + modK);
    next.k = targetZoom;
 
    if (targetZoom < extent[0] || targetZoom > extent[1]) {
      return false;
    }
 
    const translate0 = {
      x: (center.x - next.x) / next.k,
      y: (center.y - next.y) / next.k
    };
 
    const l = {
      x: translate0.x * next.k + next.x,
      y: translate0.y * next.k + next.y
    };
 
    next.x += center.x - l.x + modX;
    next.y += center.y - l.y + modY;
    this.setZoom(next.k, next.x, next.y, dur);
    return true;
  }
 
  // Programmatically resets zoom
  setZoom(k: number = 1, x: number = 0, y: number = 0, dur: number = 0) {
    const t = d3.zoomIdentity.translate(x, y).scale(k);
 
    d3
      .select(this.viewWrapper)
      .select('svg')
      .transition()
      .duration(dur)
      .call(this.zoom.transform, t);
  }
 
  // Renders 'graph' into view element
  renderView() {
    // Update the view w/ new zoom/pan
    this.selectedView.attr('transform', this.state.viewTransform);
 
    clearTimeout(this.renderNodesTimeout);
    this.renderNodesTimeout = setTimeout(this.renderNodes);
  }
 
  renderBackground = () => {
    const { gridSize, backgroundFillId, renderBackground } = this.props;
    if (renderBackground) {
      return renderBackground(gridSize);
    } else {
      return <Background gridSize={gridSize} backgroundFillId={backgroundFillId} />;
    }
  }
 
  getNodeComponent = (id: string, node: INode, index: number) => {
    const { nodeTypes, nodeSubtypes, nodeSize, renderNode, renderNodeText, nodeKey } = this.props;
    return (
      <Node
        key={id}
        id={id}
        data={node}
        index={index}
        nodeTypes={nodeTypes}
        nodeSize={nodeSize}
        nodeKey={nodeKey}
        nodeSubtypes={nodeSubtypes}
        onNodeMouseEnter={this.handleNodeMouseEnter}
        onNodeMouseLeave={this.handleNodeMouseLeave}
        onNodeMove={this.handleNodeMove}
        onNodeUpdate={this.handleNodeUpdate}
        onNodeSelected={this.handleNodeSelected}
        renderNode={renderNode}
        renderNodeText={renderNodeText}
        isSelected={this.state.selectedNodeObj.node === node}
        layoutEngine={this.layoutEngine}
      />
    );
  }
 
  renderNode(id: string, element: Element) {
    const containerId = `${id}-container`;
    let nodeContainer: HTMLElement | Element | null = document.getElementById(containerId);
 
    if (!nodeContainer) {
      nodeContainer = document.createElementNS('http://www.w3.org/2000/svg', 'g');
      nodeContainer.id = containerId;
      this.entities.appendChild(nodeContainer);
    }
 
    // ReactDOM.render replaces the insides of an element This renders the element
    // into the nodeContainer
    const anyElement: any = element;
    ReactDOM.render(anyElement, nodeContainer);
  }
 
  syncRenderConnectedEdgesFromNode(node: INodeMapNode, nodeMoving: boolean = false) {
    if (this.state.draggingEdge) {
      return;
    }
 
    node.incomingEdges.forEach((edge) => {
      this.syncRenderEdge(edge, nodeMoving);
    });
    node.outgoingEdges.forEach((edge) => {
      this.syncRenderEdge(edge, nodeMoving);
    });
  }
 
  asyncRenderNode(node: INode, i: number) {
    const nodeKey = this.props.nodeKey;
    const timeoutId = `nodes-${node[nodeKey]}`;
    clearTimeout(this.nodeTimeouts[timeoutId]);
    this.nodeTimeouts[timeoutId] = setTimeout(() => {
      this.syncRenderNode(node, i);
    });
  }
 
  syncRenderNode(node: INode, i: number) {
    const nodeKey = this.props.nodeKey;
    const id = `node-${node[nodeKey]}`;
    const element: any = this.getNodeComponent(id, node, i);
    const nodesMapNode = this.getNodeById(node[nodeKey]);
    this.renderNode(id, element);
    Eif (nodesMapNode) {
      this.syncRenderConnectedEdgesFromNode(nodesMapNode);
    }
  }
 
  renderNodes = () => {
    if (!this.entities) {
      return;
    }
 
    this.state.nodes.forEach((node, i) => {
      this.asyncRenderNode(node, i);
    });
  }
 
  isEdgeSelected = (edge: IEdge) => {
    return !!this.state.selectedEdgeObj &&
      !!this.state.selectedEdgeObj.edge &&
      this.state.selectedEdgeObj.edge.source === edge.source &&
      this.state.selectedEdgeObj.edge.target === edge.target;
  }
 
  getEdgeComponent = (edge: IEdge | any) => {
    const sourceNodeMapNode = this.getNodeById(edge.source);
    const sourceNode = sourceNodeMapNode ? this.state.nodes[sourceNodeMapNode.originalArrIndex] : null;
    const targetNodeMapNode = this.getNodeById(edge.target);
    const targetNode = targetNodeMapNode ? this.state.nodes[targetNodeMapNode.originalArrIndex] : null;
    const targetPosition = edge.targetPosition;
    const { edgeTypes, edgeHandleSize, nodeSize, nodeKey} = this.props;
 
    return (
      <Edge
        data={edge}
        edgeTypes={edgeTypes}
        edgeHandleSize={edgeHandleSize}
        nodeSize={nodeSize}
        sourceNode={sourceNode}
        targetNode={targetNode || targetPosition}
        nodeKey={nodeKey}
        isSelected={this.isEdgeSelected(edge)}
      />
    );
  }
 
 
  renderEdge = (id: string, element: any, edge: IEdge, nodeMoving: boolean = false) => {
    let containerId = `${id}-container`;
    const customContainerId = `${id}-custom-container`;
    const { draggedEdge } = this.state;
    const { afterRenderEdge } = this.props;
    let edgeContainer = document.getElementById(containerId);
    Iif (nodeMoving && edgeContainer) {
      edgeContainer.style.display = 'none';
      containerId = `${id}-custom-container`;
      edgeContainer = document.getElementById(containerId);
    } else if (edgeContainer) {
      const customContainer = document.getElementById(customContainerId);
      edgeContainer.style.display = '';
      Eif (customContainer) {
        customContainer.remove();
      }
    }
    if (!edgeContainer && edge !== draggedEdge) {
      const newSvgEdgeContainer = document.createElementNS('http://www.w3.org/2000/svg', 'g');
      newSvgEdgeContainer.id = containerId;
      this.entities.appendChild(newSvgEdgeContainer);
      edgeContainer = newSvgEdgeContainer;
    }
    // ReactDOM.render replaces the insides of an element This renders the element
    // into the edgeContainer
    Eif (edgeContainer) {
      ReactDOM.render(element, edgeContainer);
      Iif (afterRenderEdge) {
        return afterRenderEdge(id, element, edge, edgeContainer, this.isEdgeSelected(edge));
      }
    }
  }
 
  asyncRenderEdge = (edge: IEdge) => {
    Iif (!edge.source || !edge.target) {
      return;
    }
    const timeoutId = `edges-${edge.source}-${edge.target}`;
    clearTimeout(this.edgeTimeouts[timeoutId]);
    this.edgeTimeouts[timeoutId] = setTimeout(() => {
      this.syncRenderEdge(edge);
    });
  }
 
 
  syncRenderEdge(edge: IEdge | any, nodeMoving: boolean = false) {
    Iif (!edge.source) {
      return;
    }
 
    // We have to use the 'custom' id when we're drawing a new node
    const idVar = edge.target ? `${edge.source}-${edge.target}` : 'custom';
    const id = `edge-${idVar}`;
    const element = this.getEdgeComponent(edge);
    this.renderEdge(id, element, edge, nodeMoving);
  }
 
 
  renderEdges = () => {
    if (!this.entities || this.state.draggingEdge) {
      return;
    }
 
    this.state.edges.forEach((edge) => {
      this.asyncRenderEdge(edge);
    });
  }
 
  /*
   * GraphControls is a special child component. To maximize responsiveness we disable
   * rendering on zoom level changes, but this component still needs to update.
   * This function ensures that it updates into the container quickly upon zoom changes
   * without causing a full GraphView render.
   */
  renderGraphControls() {
    if (!this.props.showGraphControls) {
      return;
    }
 
    const graphControlsWrapper = document.querySelector('.graph-controls-wrapper')
    Eif (graphControlsWrapper) {
      ReactDOM.render(
        <GraphControls
          ref={this.graphControls}
          minZoom={this.props.minZoom}
          maxZoom={this.props.maxZoom}
          zoomLevel={this.state.viewTransform ? this.state.viewTransform.k : 1}
          zoomToFit={this.handleZoomToFit}
          modifyZoom={this.modifyZoom}
        />,
        graphControlsWrapper
      );
    }
  }
 
  render() {
    const { edgeArrowSize, gridSpacing, gridDotSize, nodeTypes, nodeSubtypes, edgeTypes, renderDefs } = this.props;
    return (
      <div
        className="view-wrapper"
        ref={(el) => (this.viewWrapper = el)}
      >
        <svg className="graph">
          <Defs
            edgeArrowSize={edgeArrowSize}
            gridSpacing={gridSpacing}
            gridDotSize={gridDotSize}
            nodeTypes={nodeTypes}
            nodeSubtypes={nodeSubtypes}
            edgeTypes={edgeTypes}
            renderDefs={renderDefs}
          />
          <g className="view" ref={(el) => (this.view = el)}>
            {this.renderBackground()}
 
            <g className="entities" ref={(el) => (this.entities = el)} />
          </g>
        </svg>
        <div className="graph-controls-wrapper" />
      </div>
    );
  }
}
 
export default GraphView;