LineageLayoutView.js 44.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */

define(['require',
    'backbone',
    'hbs!tmpl/graph/LineageLayoutView_tmpl',
    'collection/VLineageList',
    'models/VEntity',
24
    'utils/Utils',
25
    'dagreD3',
26
    'd3-tip',
27
    'utils/Enums',
28
    'utils/UrlLinks',
29
    'utils/Globals',
30 31
    'platform',
    'jquery-ui'
32
], function(require, Backbone, LineageLayoutViewtmpl, VLineageList, VEntity, Utils, dagreD3, d3Tip, Enums, UrlLinks, Globals, platform) {
33 34 35 36 37 38 39 40
    'use strict';

    var LineageLayoutView = Backbone.Marionette.LayoutView.extend(
        /** @lends LineageLayoutView */
        {
            _viewName: 'LineageLayoutView',

            template: LineageLayoutViewtmpl,
41
            className: "resizeGraph",
42 43 44 45 46 47

            /** Layout sub regions */
            regions: {},

            /** ui selector cache */
            ui: {
48
                graph: ".graph",
49
                checkHideProcess: "[data-id='checkHideProcess']",
50 51
                checkDeletedEntity: "[data-id='checkDeletedEntity']",
                selectDepth: 'select[data-id="selectDepth"]',
52 53 54 55
                filterToggler: '[data-id="filter-toggler"]',
                settingToggler: '[data-id="setting-toggler"]',
                searchToggler: '[data-id="search-toggler"]',
                boxClose: '[data-id="box-close"]',
56
                lineageFullscreenToggler: '[data-id="fullScreen-toggler"]',
57 58 59
                filterBox: '.filter-box',
                searchBox: '.search-box',
                settingBox: '.setting-box',
60
                lineageTypeSearch: '[data-id="typeSearch"]',
61
                lineageDetailClose: '[data-id="close"]',
62
                searchNode: '[data-id="searchNode"]',
63 64 65
                nodeEntityList: '[data-id="entityList"]',
                showOnlyHoverPath: '[data-id="showOnlyHoverPath"]',
                showTooltip: '[data-id="showTooltip"]'
66
            },
67 68 69 70 71 72
            templateHelpers: function() {
                return {
                    width: "100%",
                    height: "100%"
                };
            },
73 74 75
            /** ui events hash */
            events: function() {
                var events = {};
76 77
                events["click " + this.ui.checkHideProcess] = 'onCheckUnwantedEntity';
                events["click " + this.ui.checkDeletedEntity] = 'onCheckUnwantedEntity';
78
                events['change ' + this.ui.selectDepth] = 'onSelectDepthChange';
79 80 81
                events["click " + this.ui.filterToggler] = 'onClickFilterToggler';
                events["click " + this.ui.boxClose] = 'toggleBoxPanel';
                events["click " + this.ui.settingToggler] = 'onClickSettingToggler';
82
                events["click " + this.ui.lineageFullscreenToggler] = 'onClickLineageFullscreenToggler';
83
                events["click " + this.ui.searchToggler] = 'onClickSearchToggler';
84 85 86
                events["click " + this.ui.lineageDetailClose] = function() {
                    this.toggleLineageInfomationSlider({ close: true });
                };
87 88 89 90 91 92 93 94
                return events;
            },

            /**
             * intialize a new LineageLayoutView Layout
             * @constructs
             */
            initialize: function(options) {
95
                _.extend(this, _.pick(options, 'processCheck', 'guid', 'entityDefCollection', 'actionCallBack', 'fetchCollection'));
96
                this.collection = new VLineageList();
97
                this.lineageData = null;
98
                this.typeMap = {};
99
                this.apiGuid = {};
100
                this.asyncFetchCounter = 0;
101
                this.edgeCall;
102 103
                this.filterObj = {
                    isProcessHideCheck: false,
104
                    isDeletedEntityHideCheck: false,
105 106
                    depthCount: ''
                };
107 108 109
                this.searchNodeObj = {
                    selectedNode: ''
                }
110
            },
111 112 113

            initializeGraph: function() {
                this.g = {};
114
                this.g = new dagreD3.graphlib.Graph()
115 116 117 118 119 120 121 122 123 124
                    .setGraph({
                        nodesep: 50,
                        ranksep: 90,
                        rankdir: "LR",
                        marginx: 20,
                        marginy: 20,
                        transition: function transition(selection) {
                            return selection.transition().duration(500);
                        }
                    })
125 126 127 128
                    .setDefaultEdgeLabel(function() {
                        return {};
                    });
            },
129 130 131 132 133 134 135 136 137 138 139 140 141
            onRender: function() {
                var that = this;
                this.fetchGraphData();
                if (platform.name === "IE") {
                    this.$('svg').css('opacity', '0');
                }
                if (this.layoutRendered) {
                    this.layoutRendered();
                }
                if (this.processCheck) {
                    this.hideCheckForProcess();
                }
                this.initializeGraph();
142 143 144 145 146 147
                this.ui.selectDepth.select2({
                    data: _.sortBy([3, 6, 9, 12, 15, 18, 21]),
                    tags: true,
                    dropdownCssClass: "number-input",
                    multiple: false
                });
148 149 150
            },
            onShow: function() {
                this.$('.fontLoader').show();
151 152 153 154 155 156 157 158 159
                this.$el.resizable({
                    handles: ' s',
                    minHeight: 375,
                    stop: function(event, ui) {
                        ui.element.height(($(this).height()));
                    },
                });
            },
            onClickLineageFullscreenToggler: function(e) {
160
                var icon = $(e.currentTarget).find('i'),
161 162 163
                    panel = $(e.target).parents('.tab-pane').first();
                icon.toggleClass('fa-expand fa-compress');
                panel.toggleClass('fullscreen-mode');
164
            },
165
            onCheckUnwantedEntity: function(e) {
166
                var data = $.extend(true, {}, this.lineageData);
167
                //this.fromToNodeData = {};
168
                this.initializeGraph();
169 170 171 172 173
                if ($(e.target).data("id") === "checkHideProcess") {
                    this.filterObj.isProcessHideCheck = e.target.checked;
                } else {
                    this.filterObj.isDeletedEntityHideCheck = e.target.checked;
                }
174
                this.generateData({ "relationshipMap": this.relationshipMap, "guidEntityMap": this.guidEntityMap });
175
            },
176 177 178 179
            toggleBoxPanel: function(el) {
                this.$el.find('.show-box-panel').removeClass('show-box-panel');
                if (el && el.addClass) {
                    el.addClass('show-box-panel');
180
                }
181
            },
182 183 184 185 186 187 188 189 190
            onClickFilterToggler: function() {
                this.toggleBoxPanel(this.ui.filterBox);
            },
            onClickSettingToggler: function() {
                this.toggleBoxPanel(this.ui.settingBox);
            },
            onClickSearchToggler: function() {
                this.toggleBoxPanel(this.ui.searchBox);
            },
191 192 193 194 195 196 197 198 199
            onSelectDepthChange: function(e, options) {
                this.initializeGraph();
                this.filterObj.depthCount = e.currentTarget.value;
                this.fetchGraphData({ queryParam: { 'depth': this.filterObj.depthCount } });
            },

            fetchGraphData: function(options) {
                var that = this,
                    queryParam = options && options.queryParam || {};
200
                this.fromToNodeData = {};
201 202
                this.$('.fontLoader').show();
                this.$('svg>g').hide();
203
                this.collection.getLineage(this.guid, {
204
                    skipDefaultError: true,
205
                    queryParam: queryParam,
206 207
                    success: function(data) {
                        if (data.relations.length) {
208 209 210 211 212 213 214
                            that.lineageData = $.extend(true, {}, data);
                            that.relationshipMap = that.crateLineageRelationshipHashMap(data);
                            that.guidEntityMap = $.extend(true, {}, data.guidEntityMap);
                            if (that.lineageData) {
                                that.renderLineageTypeSearch();
                            }
                            that.generateData({ "relationshipMap": that.relationshipMap, "guidEntityMap": that.guidEntityMap });
215 216
                        } else {
                            that.noLineage();
217
                            that.hideCheckForProcess();
218 219
                        }
                    },
220
                    cust_error: function(model, response) {
221
                        that.lineageData = [];
222
                        that.noLineage();
223 224 225 226
                    },
                    complete: function() {
                        that.$('.fontLoader').hide();
                        that.$('svg>g').show();
227
                    }
228
                })
229
            },
230
            noLineage: function() {
231
                this.$('.fontLoader').hide();
232
                this.$('.depth-container').hide();
233
                this.$('svg').html('<text x="50%" y="50%" alignment-baseline="middle" text-anchor="middle">No lineage data found</text>');
234 235 236
                if (this.actionCallBack) {
                    this.actionCallBack();
                }
237
            },
238 239 240
            hideCheckForProcess: function() {
                this.$('.hideProcessContainer').hide();
            },
241 242 243 244 245 246
            isProcess: function(node) {
                var typeName = node.typeName,
                    superTypes = node.superTypes,
                    entityDef = node.entityDef;
                if (typeName == "Process") {
                    return true;
247
                }
248 249 250 251 252
                return _.contains(superTypes, "Process");
            },
            isDeleted: function(node) {
                if (_.isUndefined(node)) {
                    return
253
                }
254 255 256 257 258 259 260 261
                return Enums.entityStateReadOnly[node.status];
            },
            isNodeToBeUpdated: function(node) {
                var isProcessHideCheck = this.filterObj.isProcessHideCheck,
                    isDeletedEntityHideCheck = this.filterObj.isDeletedEntityHideCheck
                var returnObj = {
                    isProcess: (isProcessHideCheck && node.isProcess),
                    isDeleted: (isDeletedEntityHideCheck && node.isDeleted)
262

263 264 265 266 267 268 269 270 271 272 273 274
                };
                returnObj["update"] = returnObj.isProcess || returnObj.isDeleted;
                return returnObj;
            },
            getNestedSuperTypes: function(options) {
                var entityDef = options.entityDef;
                return Utils.getNestedSuperTypes({ data: entityDef.toJSON(), collection: this.entityDefCollection })
            },
            getEntityDef: function(typeName) {
                var entityDef = null;
                if (typeName) {
                    entityDef = this.entityDefCollection.fullCollection.find({ name: typeName });
275
                }
276 277 278 279 280 281 282 283 284 285 286 287
                return entityDef;
            },
            getServiceType: function(options) {
                if (!options) {
                    return;
                }
                var typeName = options.typeName,
                    entityDef = options.entityDef,
                    serviceType = null;
                if (typeName) {
                    if (entityDef) {
                        serviceType = entityDef.get("serviceType") || null;
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
                return serviceType;
            },
            crateLineageRelationshipHashMap: function(data) {
                var that = this,
                    relations = data && data.relations,
                    guidEntityMap = data && data.guidEntityMap,
                    makeNodeData = function(relationObj) {
                        var obj = $.extend(true, {
                            shape: "img",
                            label: relationObj.displayText.trunc(18),
                            toolTipLabel: relationObj.displayText,
                            id: relationObj.guid,
                            isLineage: true,
                            entityDef: this.getEntityDef(relationObj.typeName)
                        }, relationObj);
                        obj["serviceType"] = this.getServiceType({ typeName: relationObj.typeName, entityDef: obj.entityDef });
                        obj["superTypes"] = this.getNestedSuperTypes({ entityDef: obj.entityDef });
                        obj['isProcess'] = this.isProcess(obj);
                        obj['isDeleted'] = this.isDeleted(obj);
                        return obj;
                    }.bind(this),
                    newHashMap = {};
                _.each(relations, function(obj) {
                    if (!that.fromToNodeData[obj.fromEntityId]) {
                        that.fromToNodeData[obj.fromEntityId] = makeNodeData(guidEntityMap[obj.fromEntityId]);
                    }
                    if (!that.fromToNodeData[obj.toEntityId]) {
                        that.fromToNodeData[obj.toEntityId] = makeNodeData(guidEntityMap[obj.toEntityId]);
318
                    }
319 320
                    if (newHashMap[obj.fromEntityId]) {
                        newHashMap[obj.fromEntityId].push(obj.toEntityId);
321
                    } else {
322
                        newHashMap[obj.fromEntityId] = [obj.toEntityId];
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
                });
                return newHashMap;
            },
            generateData: function(options) {
                var that = this,
                    relationshipMap = options && $.extend(true, {}, options.relationshipMap) || {},
                    guidEntityMap = options && options.guidEntityMap || {},
                    styleObj = {
                        fill: 'none',
                        stroke: '#ffb203',
                        width: 3
                    },
                    getStyleObjStr = function(styleObj) {
                        return 'fill:' + styleObj.fill + ';stroke:' + styleObj.stroke + ';stroke-width:' + styleObj.width;
                    },
                    filterRelationshipMap = relationshipMap,
                    isHideFilterOn = this.filterObj.isProcessHideCheck || this.filterObj.isDeletedEntityHideCheck,
                    getNewToNodeRelationship = function(toNodeGuid) {
                        if (toNodeGuid && relationshipMap[toNodeGuid]) {
                            var newRelationship = [];
                            _.each(relationshipMap[toNodeGuid], function(guid) {
                                var nodeToBeUpdated = that.isNodeToBeUpdated(that.fromToNodeData[guid]);
                                if (nodeToBeUpdated.update) {
                                    var newRelation = getNewToNodeRelationship(guid);
                                    if (newRelation) {
                                        newRelationship = newRelationship.concat(newRelation);
350
                                    }
351 352
                                } else {
                                    newRelationship.push(guid);
353
                                }
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
                            });
                            return newRelationship;
                        } else {
                            return null;
                        }
                    },
                    getToNodeRelation = function(toNodes, fromNodeToBeUpdated) {
                        var toNodeRelationship = [];
                        _.each(toNodes, function(toNodeGuid) {
                            var toNodeToBeUpdated = that.isNodeToBeUpdated(that.fromToNodeData[toNodeGuid]);
                            if (toNodeToBeUpdated.update) {
                                // To node need to updated
                                if (pendingFromRelationship[toNodeGuid]) {
                                    toNodeRelationship = toNodeRelationship.concat(pendingFromRelationship[toNodeGuid]);
                                } else {
                                    var newToNodeRelationship = getNewToNodeRelationship(toNodeGuid);
                                    if (newToNodeRelationship) {
                                        toNodeRelationship = toNodeRelationship.concat(newToNodeRelationship);
                                    }
373
                                }
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
                            } else {
                                //when bothe node not to be updated.
                                toNodeRelationship.push(toNodeGuid);
                            }
                        });
                        return toNodeRelationship;
                    },
                    pendingFromRelationship = {};
                if (isHideFilterOn) {
                    filterRelationshipMap = {};
                    _.each(relationshipMap, function(toNodes, fromNodeGuid) {
                        var fromNodeToBeUpdated = that.isNodeToBeUpdated(that.fromToNodeData[fromNodeGuid]),
                            toNodeList = getToNodeRelation(toNodes, fromNodeToBeUpdated);
                        if (fromNodeToBeUpdated.update) {
                            if (pendingFromRelationship[fromNodeGuid]) {
                                pendingFromRelationship[fromNodeGuid] = pendingFromRelationship[fromNodeGuid].concat(toNodeList);
                            } else {
                                pendingFromRelationship[fromNodeGuid] = toNodeList;
                            }
393
                        } else {
394 395 396 397 398
                            if (filterRelationshipMap[fromNodeGuid]) {
                                filterRelationshipMap[fromNodeGuid] = filterRelationshipMap[fromNodeGuid].concat(toNodeList);
                            } else {
                                filterRelationshipMap[fromNodeGuid] = toNodeList;
                            }
399
                        }
400
                    })
401 402
                }

403 404 405
                _.each(filterRelationshipMap, function(toNodesList, fromNodeGuid) {
                    if (!that.g._nodes[fromNodeGuid]) {
                        that.g.setNode(fromNodeGuid, that.fromToNodeData[fromNodeGuid]);
406
                    }
407 408 409 410 411 412 413 414 415 416 417 418 419
                    _.each(toNodesList, function(toNodeGuid) {
                        if (!that.g._nodes[toNodeGuid]) {
                            that.g.setNode(toNodeGuid, that.fromToNodeData[toNodeGuid]);
                        }
                        that.g.setEdge(fromNodeGuid, toNodeGuid, {
                            "arrowhead": 'arrowPoint',
                            "lineInterpolate": 'basis',
                            "style": getStyleObjStr(styleObj),
                            'styleObj': styleObj
                        });
                    })
                })

420
                //if no relations found
421
                if (_.isEmpty(filterRelationshipMap)) {
422 423
                    this.$('svg').html('<text x="50%" y="50%" alignment-baseline="middle" text-anchor="middle">No relations to display</text>');
                }
424

425 426 427
                if (this.fromToNodeData[this.guid]) {
                    this.fromToNodeData[this.guid]['isLineage'] = false;
                    this.findImpactNodeAndUpdateData({ "relationshipMap": filterRelationshipMap, "guid": this.guid, "getStyleObjStr": getStyleObjStr });
428
                }
429 430
                if (this.asyncFetchCounter == 0) {
                    this.createGraph();
431
                }
432
            },
433
            findImpactNodeAndUpdateData: function(options) {
434
                var that = this,
435 436 437 438 439 440 441 442 443
                    relationshipMap = options.relationshipMap,
                    fromNodeGuid = options.guid,
                    getStyleObjStr = options.getStyleObjStr,
                    toNodeList = relationshipMap[fromNodeGuid];
                if (toNodeList && toNodeList.length) {
                    if (!relationshipMap[fromNodeGuid]["traversed"]) {
                        relationshipMap[fromNodeGuid]["traversed"] = true;
                        _.each(toNodeList, function(toNodeGuid) {
                            that.fromToNodeData[toNodeGuid]['isLineage'] = false;
444 445 446
                            var styleObj = {
                                fill: 'none',
                                stroke: '#fb4200',
447
                                width: 3
448
                            }
449 450 451 452 453 454 455 456 457 458 459 460 461
                            that.g.setEdge(fromNodeGuid, toNodeGuid, {
                                "arrowhead": 'arrowPoint',
                                "lineInterpolate": 'basis',
                                "style": getStyleObjStr(styleObj),
                                'styleObj': styleObj
                            });
                            that.findImpactNodeAndUpdateData({
                                "relationshipMap": relationshipMap,
                                "guid": toNodeGuid,
                                "getStyleObjStr": getStyleObjStr
                            });
                        });
                    }
462 463
                }
            },
464 465 466 467 468 469 470 471
            toggleInformationSlider: function(options) {
                if (options.open && !this.$('.lineage-edge-details').hasClass("open")) {
                    this.$('.lineage-edge-details').addClass('open');
                } else if (options.close && this.$('.lineage-edge-details').hasClass("open")) {
                    d3.selectAll('circle').attr("stroke", "none");
                    this.$('.lineage-edge-details').removeClass('open');
                }
            },
472 473
            centerNode: function(nodeID) {
                var zoom = function() {
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
                    svgGroup.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
                };
                var selectedNode = this.$('svg').find("g.nodes").find('>g#' + nodeID);

                if (selectedNode.length > 0) {
                    selectedNode = selectedNode;
                    var matrix = selectedNode.attr('transform').replace(/[^0-9\-.,]/g, '').split(','),
                        x = matrix[0],
                        y = matrix[1];
                } else {
                    selectedNode = this.$('svg').find("g.nodes").find('g').eq(1);
                    var x = this.g.graph().width / 2,
                        y = this.g.graph().height / 2;

                }
                var viewerWidth = this.$('svg').width(),
490 491 492 493 494 495 496 497 498 499 500 501 502 503
                    viewerHeight = this.$('svg').height(),
                    gBBox = d3.select('g').node().getBBox(),
                    zoomListener = d3.behavior.zoom().scaleExtent([0.01, 50]).on("zoom", zoom),
                    scale = 1.2,
                    xa = -((x * scale) - (viewerWidth / 2)),
                    ya = -((y * scale) - (viewerHeight / 2));

                this.zoom.translate([xa, ya]);
                d3.select('g').transition()
                    .duration(350)
                    .attr("transform", "translate(" + xa + "," + ya + ")scale(" + scale + ")");
                zoomListener.scale(scale);
                zoomListener.translate([xa, ya]);
                this.zoom.scale(scale);
504 505 506 507 508 509 510
            },
            zoomed: function(that) {
                this.$('svg').find('>g').attr("transform",
                    "translate(" + this.zoom.translate() + ")" +
                    "scale(" + this.zoom.scale() + ")"
                );
            },
511 512 513 514 515 516 517 518 519 520 521 522
            interpolateZoom: function(translate, scale, that, zoom) {
                return d3.transition().duration(350).tween("zoom", function() {
                    var iTranslate = d3.interpolate(zoom.translate(), translate),
                        iScale = d3.interpolate(zoom.scale(), scale);
                    return function(t) {
                        zoom
                            .scale(iScale(t))
                            .translate(iTranslate(t));
                        that.zoomed();
                    };
                });
            },
523
            createGraph: function() {
524 525 526
                var that = this,
                    width = this.$('svg').width(),
                    height = this.$('svg').height();
527 528 529 530 531 532 533
                this.g.nodes().forEach(function(v) {
                    var node = that.g.node(v);
                    // Round the corners of the nodes
                    if (node) {
                        node.rx = node.ry = 5;
                    }
                });
534 535 536 537 538 539 540
                // Create the renderer
                var render = new dagreD3.render();
                // Add our custom arrow (a hollow-point)
                render.arrows().arrowPoint = function normal(parent, id, edge, type) {
                    var marker = parent.append("marker")
                        .attr("id", id)
                        .attr("viewBox", "0 0 10 10")
541
                        .attr("refX", 8)
542 543
                        .attr("refY", 5)
                        .attr("markerUnits", "strokeWidth")
544 545
                        .attr("markerWidth", 4)
                        .attr("markerHeight", 4)
546
                        .attr("orient", "auto");
547

548 549
                    var path = marker.append("path")
                        .attr("d", "M 0 0 L 10 5 L 0 10 z")
550
                        .style("fill", edge.styleObj.stroke);
551 552 553 554
                    dagreD3.util.applyStyle(path, edge[type + "Style"]);
                };
                render.shapes().img = function circle(parent, bbox, node) {
                    //var r = Math.max(bbox.width, bbox.height) / 2,
555 556 557 558 559
                    if (node.id == that.guid) {
                        var currentNode = true
                    }
                    var shapeSvg = parent.append('circle')
                        .attr('fill', 'url(#img_' + node.id + ')')
560
                        .attr('r', '24px')
561
                        .attr('data-stroke', node.id)
562
                        .attr("class", "nodeImage " + (currentNode ? "currentNode" : (node.isProcess ? "process" : "node")));
563 564 565 566 567 568 569 570 571 572

                    parent.insert("defs")
                        .append("pattern")
                        .attr("x", "0%")
                        .attr("y", "0%")
                        .attr("patternUnits", "objectBoundingBox")
                        .attr("id", "img_" + node.id)
                        .attr("width", "100%")
                        .attr("height", "100%")
                        .append('image')
573 574
                        .attr("xlink:href", function(d) {
                            if (node) {
575
                                return Utils.getEntityIconPath({ entityData: node });
576
                            }
577
                        })
578 579 580 581 582 583 584
                        .attr("x", currentNode ? "3" : "6")
                        .attr("y", currentNode ? "3" : "4")
                        .attr("width", "40")
                        .attr("height", "40")
                        .on("error", function() {
                            this.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', Utils.getEntityIconPath({ entityData: node, errorUrl: this.href.baseVal }));
                        });
585

586
                    node.intersect = function(point) {
587
                        return dagreD3.intersect.circle(node, currentNode ? 24 : 21, point);
588
                    };
589 590 591
                    return shapeSvg;
                };
                // Set up an SVG group so that we can translate the final graph.
592 593 594
                if (this.$("svg").find('.output').length) {
                    this.$("svg").find('.output').parent('g').remove();
                }
595 596 597
                var svg = this.svg = d3.select(this.$("svg")[0])
                    .attr("viewBox", "0 0 " + width + " " + height)
                    .attr("enable-background", "new 0 0 " + width + " " + height),
598
                    svgGroup = svg.append("g");
599
                var zoom = this.zoom = d3.behavior.zoom()
600 601
                    .center([width / 2, height / 2])
                    .scaleExtent([0.01, 50])
602
                    .on("zoom", that.zoomed.bind(this));
603

604 605 606
                function zoomClick() {
                    var clicked = d3.event.target,
                        direction = 1,
607
                        factor = 0.5,
608
                        target_zoom = 1,
609
                        center = [width / 2, height / 2],
610 611 612 613
                        translate = zoom.translate(),
                        translate0 = [],
                        l = [],
                        view = { x: translate[0], y: translate[1], k: zoom.scale() };
614

615 616 617
                    d3.event.preventDefault();
                    direction = (this.id === 'zoom_in') ? 1 : -1;
                    target_zoom = zoom.scale() * (1 + factor * direction);
618

619 620 621
                    translate0 = [(center[0] - view.x) / view.k, (center[1] - view.y) / view.k];
                    view.k = target_zoom;
                    l = [translate0[0] * view.k + view.x, translate0[1] * view.k + view.y];
622

623 624
                    view.x += center[0] - l[0];
                    view.y += center[1] - l[1];
625

626
                    that.interpolateZoom([view.x, view.y], view.k, that, zoom);
627
                }
628
                d3.selectAll(this.$('.lineageZoomButton')).on('click', zoomClick);
629 630
                var tooltip = d3Tip()
                    .attr('class', 'd3-tip')
631
                    .offset([10, 0])
632 633
                    .html(function(d) {
                        var value = that.g.node(d);
634 635 636 637 638
                        var htmlStr = "";
                        if (value.id !== that.guid) {
                            htmlStr = "<h5 style='text-align: center;'>" + (value.isLineage ? "Lineage" : "Impact") + "</h5>";
                        }
                        htmlStr += "<h5 class='text-center'><span style='color:#359f89'>" + value.toolTipLabel + "</span></h5> ";
639 640 641
                        if (value.typeName) {
                            htmlStr += "<h5 class='text-center'><span>(" + value.typeName + ")</span></h5> ";
                        }
642 643 644
                        if (value.queryText) {
                            htmlStr += "<h5>Query: <span style='color:#359f89'>" + value.queryText + "</span></h5> ";
                        }
645
                        return "<div class='tip-inner-scroll'>" + htmlStr + "</div>";
646
                    });
647

648 649
                svg.call(zoom)
                    .call(tooltip);
650 651 652
                if (platform.name !== "IE") {
                    this.$('.fontLoader').hide();
                }
653 654
                render(svgGroup, this.g);
                svg.on("dblclick.zoom", null)
655
                // .on("wheel.zoom", null);
656
                //change text postion 
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

                function isConnected(a, b, o) {
                    //console.log(a, b, o);
                    if (a === o || (b && b.length && b.indexOf(o) != -1)) {
                        return true;
                    }
                }

                function fade(opacity, d, nodesToHighlight) {
                    var node = svg.selectAll('.node');
                    var path = svg.selectAll('.edgePath');
                    node.classed("hover-active", function(selectedNode, i, nodes) {
                        if (isConnected(d, nodesToHighlight, selectedNode)) {
                            return true;
                        } else {
                            return false;
                        }
                    });
                    path.classed('hover-active-node', function(c) {
                        var _thisOpacity = c.v === d || c.w === d ? 1 : 0;
                        if (_thisOpacity) {
                            return true;
                        } else {
                            return false;
                        }

                    });

                }
                //Highlight on click
687
                svgGroup.selectAll("g.nodes g.label")
688
                    .attr("transform", "translate(2,-35)");
689
                var waitForDoubleClick = null;
690 691
                svgGroup.selectAll("g.nodes g.node")
                    .on('mouseenter', function(d) {
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
                        that.activeNode = true;
                        var matrix = this.getScreenCTM()
                            .translate(+this.getAttribute("cx"), +this.getAttribute("cy"));
                        that.$('svg').find('.node').removeClass('active');
                        $(this).addClass('active');

                        // Fix
                        var width = $('body').width();
                        var currentELWidth = $(this).offset();
                        var direction = 'e';
                        if (((width - currentELWidth.left) < 330)) {
                            direction = (((width - currentELWidth.left) < 330) && ((currentELWidth.top) < 400)) ? 'sw' : 'w';
                            if (((width - currentELWidth.left) < 330) && ((currentELWidth.top) > 600)) {
                                direction = 'nw';
                            }
                        } else if (((currentELWidth.top) > 600)) {
                            direction = (((width - currentELWidth.left) < 330) && ((currentELWidth.top) > 600)) ? 'nw' : 'n';
                            if ((currentELWidth.left) < 50) {
                                direction = 'ne'
                            }
                        } else if ((currentELWidth.top) < 400) {
                            direction = ((currentELWidth.left) < 50) ? 'se' : 's';
                        }
715 716 717 718 719 720 721 722 723 724 725 726
                        if (that.ui.showTooltip.prop('checked')) {
                            tooltip.direction(direction).show(d);
                        }

                        if (!that.ui.showOnlyHoverPath.prop('checked')) {
                            return;
                        }
                        that.$('svg').addClass('hover');
                        var nextNode = that.g.successors(d),
                            previousNode = that.g.predecessors(d),
                            nodesToHighlight = nextNode.concat(previousNode);
                        fade(0.3, d, nodesToHighlight);
727
                    })
728
                    .on('mouseleave', function(d) {
729 730 731 732 733
                        that.activeNode = false;
                        var nodeEL = this;
                        setTimeout(function(argument) {
                            if (!(that.activeTip || that.activeNode)) {
                                $(nodeEL).removeClass('active');
734 735 736
                                if (that.ui.showTooltip.prop('checked')) {
                                    tooltip.hide(d);
                                }
737
                            }
738 739 740 741 742 743 744 745
                        }, 400);
                        if (!that.ui.showOnlyHoverPath.prop('checked')) {
                            return;
                        }
                        that.$('svg').removeClass('hover');
                        fade(1, d);
                    })
                    .on('click', function(d) {
746
                        if (d3.event.defaultPrevented) return; // ignore drag
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
                        d3.event.preventDefault();

                        if (waitForDoubleClick != null) {
                            clearTimeout(waitForDoubleClick)
                            waitForDoubleClick = null;
                            tooltip.hide(d);
                            Utils.setUrl({
                                url: '#!/detailPage/' + d + '?tabActive=lineage',
                                mergeBrowserUrl: false,
                                trigger: true
                            });
                        } else {
                            var currentEvent = d3.event
                            waitForDoubleClick = setTimeout(function() {
                                tooltip.hide(d);
                                that.toggleLineageInfomationSlider({ open: true, obj: d });
                                svgGroup.selectAll('[data-stroke]').attr('stroke', 'none');
                                svgGroup.selectAll('[data-stroke]').attr('stroke', function(c) {
                                    if (c == d) {
                                        return "#316132";
                                    } else {
                                        return 'none';
                                    }
                                })
                                that.updateRelationshipDetails({ obj: d });
                                waitForDoubleClick = null;
                            }, 150)
                        }
775
                    });
776

777 778 779 780 781 782 783 784
                svgGroup.selectAll("g.edgePath path.path").on('click', function(d) {
                    var data = { obj: _.find(that.lineageData.relations, { "fromEntityId": d.v, "toEntityId": d.w }) },
                        relationshipId = data.obj.relationshipId;
                    require(['views/graph/PropagationPropertyModal'], function(PropagationPropertyModal) {
                        var view = new PropagationPropertyModal({
                            edgeInfo: data,
                            relationshipId: relationshipId,
                            lineageData: that.lineageData,
785 786
                            apiGuid: that.apiGuid,
                            detailPageFetchCollection: that.fetchCollection
787 788 789
                        });
                    });
                })
790 791 792 793 794 795 796 797 798
                $('body').on('mouseover', '.d3-tip', function(el) {
                    that.activeTip = true;
                });
                $('body').on('mouseleave', '.d3-tip', function(el) {
                    that.activeTip = false;
                    that.$('svg').find('.node').removeClass('active');
                    tooltip.hide();
                });

799
                // Center the graph
800
                this.centerNode(that.guid);
801
                zoom.event(svg);
802
                //svg.attr('height', this.g.graph().height * initialScale + 40);
803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
                if (platform.name === "IE") {
                    this.IEGraphRenderDone = 0;
                    this.$('svg .edgePath').each(function(argument) {
                        var childNode = $(this).find('marker');
                        $(this).find('marker').remove();
                        var eleRef = this;
                        ++that.IEGraphRenderDone;
                        setTimeout(function(argument) {
                            $(eleRef).find('defs').append(childNode);
                            --that.IEGraphRenderDone;
                            if (that.IEGraphRenderDone === 0) {
                                this.$('.fontLoader').hide();
                                this.$('svg').fadeTo(1000, 1)
                            }
                        }, 1000);
                    });
                }
820
            },
821 822 823 824 825 826 827 828 829 830 831 832
            renderLineageTypeSearch: function() {
                var that = this;
                var lineageData = $.extend(true, {}, this.lineageData);
                var data = [];

                var typeStr = '<option></option>';
                if (!_.isEmpty(lineageData)) {
                    _.each(lineageData.guidEntityMap, function(obj, index) {
                        typeStr += '<option value="' + obj.guid + '">' + obj.attributes.name + '</option>';
                    });
                }
                that.ui.lineageTypeSearch.html(typeStr);
833
                this.initilizelineageTypeSearch()
834
            },
835
            initilizelineageTypeSearch: function() {
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
                var that = this;
                that.ui.lineageTypeSearch.select2({
                    closeOnSelect: true,
                    placeholder: 'Select Node'
                }).on('change.select2', function(e) {
                    e.stopPropagation();
                    e.stopImmediatePropagation();
                    d3.selectAll(".serach-rect").remove();
                    var selectedNode = $('[data-id="typeSearch"]').val();
                    that.searchNodeObj.selectedNode = $('[data-id="typeSearch"]').val();
                    that.centerNode(selectedNode);

                    that.svg.selectAll('.nodes g.label').attr('stroke', function(c, d) {
                        if (c == selectedNode) {
                            return "#316132";
                        } else {
                            return 'none';
                        }
                    });
                    // Using jquery for selector because d3 select is not working for few process entities.
                    d3.select($(".node#" + selectedNode)[0]).insert("rect", "circle")
                        .attr("class", "serach-rect")
                        .attr("x", -50)
                        .attr("y", -27.5)
                        .attr("width", 100)
                        .attr("height", 55);
                    d3.selectAll(".nodes circle").classed("wobble", function(d, i, nodes) {
                        if (d == selectedNode) {
                            return true;
                        } else {
                            return false;
                        }
                    });

                });
                if (that.searchNodeObj.selectedNode) {
                    that.ui.lineageTypeSearch.val(that.searchNodeObj.selectedNode);
                    that.ui.lineageTypeSearch.trigger("change.select2");
                }
            },
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
            toggleLineageInfomationSlider: function(options) {
                if (options.open && !this.$('.lineage-details').hasClass("open")) {
                    this.$('.lineage-details').addClass('open');
                } else if (options.close && this.$('.lineage-details').hasClass("open")) {
                    d3.selectAll('circle').attr("stroke", "none");
                    this.$('.lineage-details').removeClass('open');
                }
            },
            updateRelationshipDetails: function(options) {
                var that = this;
                var lineageData;
                for (var x in that.lineageData.guidEntityMap) {
                    if (x == options.obj) {
                        lineageData = that.lineageData.guidEntityMap[x]
                    }
                }
                var data = lineageData,
                    typeName = data.typeName || options.obj.name,
                    searchString = options.searchString,
                    listString = "";
                this.$("[data-id='typeName']").text(typeName);
                var getElement = function(options) {
                    var showCofig = [
                        "meaningNames",
                        "meanings",
                        "classificationNames",
                        {
                            "attributes": [
                                "description",
                                "name",
                                "qualifiedName"
                            ]
                        }
                    ];
                    var tbody = '';
                    for (var x = 0; x < showCofig.length; x++) {
                        if (typeof showCofig[x] === "object") {
                            _.each(showCofig[x].attributes, function(element, index, list) {
                                var dataToShow = data.attributes[element] ? data.attributes[element] : "N/A";
                                tbody += '<tr><td class="html-cell renderable">' + element + '</td><td  class="html-cell renderable">' + dataToShow + '</td></tr>';
                            })
                        } else {
                            var dataToShow = data[showCofig[x]] ? data[showCofig[x]] : "N/A";
                            dataToShow = dataToShow && dataToShow.length > 0 ? dataToShow : "N/A";
                            tbody += '<tr><td class="html-cell renderable">' + showCofig[x] + '</td><td class="html-cell renderable">' + dataToShow + '</td></tr>';
                        }
                    }
                    var thead = '<thead><tr><th class="renderable">Type</th><th class="renderable">Details</th></thead>';
                    var table = '<table style="word-wrap: break-word;" class="table table-hover ">' + thead + '<tbody>' + tbody + '</body></table>';
                    return table;

                }
                listString += getElement(data);
                this.ui.nodeEntityList.html(listString);
930 931 932
            }
        });
    return LineageLayoutView;
933
});