RelationshipLayoutView.js 25.7 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 24
/**
 * 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/RelationshipLayoutView_tmpl',
    'collection/VLineageList',
    'models/VEntity',
    'utils/Utils',
25
    'utils/CommonViewFunction',
26 27 28 29
    'd3-tip',
    'utils/Enums',
    'utils/UrlLinks',
    'platform'
30
], function(require, Backbone, RelationshipLayoutViewtmpl, VLineageList, VEntity, Utils, CommonViewFunction, d3Tip, Enums, UrlLinks, platform) {
31 32 33 34 35 36 37 38
    'use strict';

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

            template: RelationshipLayoutViewtmpl,
39
            className: "resizeGraph",
40 41 42 43 44 45
            /** Layout sub regions */
            regions: {},

            /** ui selector cache */
            ui: {
                relationshipDetailClose: '[data-id="close"]',
46 47 48 49 50 51
                searchNode: '[data-id="searchNode"]',
                relationshipViewToggle: 'input[name="relationshipViewToggle"]',
                relationshipDetailTable: "[data-id='relationshipDetailTable']",
                relationshipSVG: "[data-id='relationshipSVG']",
                relationshipDetailValue: "[data-id='relationshipDetailValue']",
                zoomControl: "[data-id='zoomControl']",
52 53
                boxClose: '[data-id="box-close"]',
                noValueToggle: "[data-id='noValueToggle']"
54 55 56 57 58 59 60 61 62
            },

            /** ui events hash */
            events: function() {
                var events = {};
                events["click " + this.ui.relationshipDetailClose] = function() {
                    this.toggleInformationSlider({ close: true });
                };
                events["keyup " + this.ui.searchNode] = 'searchNode';
63 64 65 66
                events["click " + this.ui.boxClose] = 'toggleBoxPanel';
                events["change " + this.ui.relationshipViewToggle] = function(e) {
                    this.relationshipViewToggle(e.currentTarget.checked)
                };
67 68 69 70 71 72
                events["click " + this.ui.noValueToggle] = function(e) {
                    Utils.togglePropertyRelationshipTableEmptyValues({
                        "inputType": this.ui.noValueToggle,
                        "tableEl": this.ui.relationshipDetailValue
                    });
                };
73 74 75 76 77 78 79 80
                return events;
            },

            /**
             * intialize a new RelationshipLayoutView Layout
             * @constructs
             */
            initialize: function(options) {
81
                _.extend(this, _.pick(options, 'entity', 'entityName', 'guid', 'actionCallBack', 'attributeDefs'));
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
                this.graphData = this.createData(this.entity);
            },
            createData: function(entity) {
                var that = this,
                    links = [],
                    nodes = {};
                if (entity && entity.relationshipAttributes) {
                    _.each(entity.relationshipAttributes, function(obj, key) {
                        if (!_.isEmpty(obj)) {
                            links.push({
                                "source": nodes[that.entity.typeName] ||
                                    (nodes[that.entity.typeName] = _.extend({ "name": that.entity.typeName }, { value: entity })),
                                "target": nodes[key] ||
                                    (nodes[key] = _.extend({
                                        "name": key
                                    }, { value: obj })),
                                "value": obj
                            })
                        }
                    });
                }
                return { nodes: nodes, links: links };
            },
105
            onRender: function() {
106
                this.ui.zoomControl.hide();
107 108
                this.$el.addClass('auto-height');
            },
109 110 111 112 113 114
            onShow: function(argument) {
                if (this.graphData && _.isEmpty(this.graphData.links)) {
                    this.noRelationship();
                } else {
                    this.createGraph(this.graphData);
                }
115
                this.createTable();
116 117 118 119 120 121 122 123 124 125 126 127
            },
            noRelationship: function() {
                this.$('svg').html('<text x="50%" y="50%" alignment-baseline="middle" text-anchor="middle">No relationship data found</text>');
            },
            toggleInformationSlider: function(options) {
                if (options.open && !this.$('.relationship-details').hasClass("open")) {
                    this.$('.relationship-details').addClass('open');
                } else if (options.close && this.$('.relationship-details').hasClass("open")) {
                    d3.selectAll('circle').attr("stroke", "none");
                    this.$('.relationship-details').removeClass('open');
                }
            },
128 129 130 131 132 133 134 135 136 137
            toggleBoxPanel: function(options) {
                var el = options && options.el,
                    nodeDetailToggler = options && options.nodeDetailToggler,
                    currentTarget = options.currentTarget;
                this.$el.find('.show-box-panel').removeClass('show-box-panel');
                if (el && el.addClass) {
                    el.addClass('show-box-panel');
                }
                this.$('circle.node-detail-highlight').removeClass("node-detail-highlight");
            },
138 139 140 141 142 143 144 145
            searchNode: function(e) {
                var $el = $(e.currentTarget);
                this.updateRelationshipDetails(_.extend({}, $el.data(), { searchString: $el.val() }))
            },
            updateRelationshipDetails: function(options) {
                var data = options.obj.value,
                    typeName = data.typeName || options.obj.name,
                    searchString = options.searchString,
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
                    listString = "",
                    getEntityTypelist = function(options) {
                        var activeEntityColor = "#4a90e2",
                            deletedEntityColor = "#BB5838",
                            entityTypeHtml = '',
                            getdefault = function(obj) {
                                var options = obj.options,
                                    status = (Enums.entityStateReadOnly[options.entityStatus || options.status] ? " deleted-relation" : ''),
                                    guid = options.guid,
                                    entityColor = obj.color,
                                    name = obj.name,
                                    typeName = options.typeName;

                                return "<li class=" + status + ">" +
                                    "<a style='color:" + entityColor + "' href=#!/detailPage/" + guid + "?tabActive=relationship>" + name + " (" + typeName + ")</a>" +
                                    "</li>";
                            },
                            getWithButton = function(obj) {
                                var options = obj.options,
                                    status = (Enums.entityStateReadOnly[options.entityStatus || options.status] ? " deleted-relation" : ''),
                                    guid = options.guid,
                                    entityColor = obj.color,
                                    name = obj.name,
                                    typeName = options.typeName,
                                    relationship = obj.relationship || false,
                                    entity = obj.entity || false,
                                    icon = '<i class="fa fa-trash"></i>',
                                    title = "Deleted";
                                if (relationship) {
                                    icon = '<i class="fa fa-long-arrow-right"></i>';
                                    status = (Enums.entityStateReadOnly[options.relationshipStatus || options.status] ? "deleted-relation" : '');
                                    title = "Relationship Deleted";
                                }
                                return "<li class=" + status + ">" +
                                    "<a style='color:" + entityColor + "' href=#!/detailPage/" + options.guid + "?tabActive=relationship>" + _.escape(name) + " (" + options.typeName + ")</a>" +
                                    '<button type="button" title="' + title + '" class="btn btn-sm deleteBtn deletedTableBtn btn-action ">' + icon + '</button>' +
                                    "</li>";
                            };

                        var name = options.entityName ? options.entityName : Utils.getName(options, "displayText");
                        if (options.entityStatus == "ACTIVE") {
                            if (options.relationshipStatus == "ACTIVE") {
                                entityTypeHtml = getdefault({
                                    "color": activeEntityColor,
                                    "options": options,
                                    "name": _.escape(name)
                                });
                            } else if (options.relationshipStatus == "DELETED") {
                                entityTypeHtml = getWithButton({
                                    "color": activeEntityColor,
                                    "options": options,
                                    "name": _.escape(name),
                                    "relationship": true
                                })
                            }
                        } else if (options.entityStatus == "DELETED") {
                            entityTypeHtml = getWithButton({
                                "color": deletedEntityColor,
                                "options": options,
                                "name": _.escape(name),
                                "entity": true
                            })
                        } else {

                            entityTypeHtml = getdefault({
                                "color": activeEntityColor,
                                "options": options,
                                "name": _.escape(name)
                            });
                        }
                        return entityTypeHtml;
                    };
218
                this.ui.searchNode.hide();
219 220 221
                this.$("[data-id='typeName']").text(typeName);
                var getElement = function(options) {
                    var name = options.entityName ? options.entityName : Utils.getName(options, "displayText");
222 223
                    var entityTypeButton = getEntityTypelist(options);
                    return entityTypeButton;
224 225
                }
                if (_.isArray(data)) {
226 227 228
                    if (data.length > 1) {
                        this.ui.searchNode.show();
                    }
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
                    _.each(_.sortBy(data, "displayText"), function(val) {
                        var name = Utils.getName(val, "displayText"),
                            valObj = _.extend({}, val, { entityName: name });
                        if (searchString) {
                            if (name.search(new RegExp(searchString, "i")) != -1) {
                                listString += getElement(valObj);
                            } else {
                                return;
                            }
                        } else {
                            listString += getElement(valObj);
                        }
                    });
                } else {
                    listString += getElement(data);
                }
                this.$("[data-id='entityList']").html(listString);
            },
            createGraph: function(data) {
                var that = this,
                    width = this.$('svg').width(),
                    height = this.$('svg').height();

                var scale = 1.0,
253 254
                    activeEntityColor = "#00b98b",
                    deletedEntityColor = "#BB5838",
255 256
                    defaultEntityColor = "#e0e0e0",
                    selectedNodeColor = "#4a90e2";
257 258 259 260 261 262

                var force = d3.layout.force()
                    .nodes(d3.values(data.nodes))
                    .links(data.links)
                    .size([width, height])
                    .linkDistance(200)
263
                    .gravity(0.5)
264
                    .friction(0.1)
265
                    .charge(function(d) {
266
                        var charge = -2000;
267 268 269 270 271 272 273 274 275 276 277 278
                        if (d.index === 0) charge = 100
                        return charge;
                    })
                    .on("tick", tick)
                    .start();

                var zoom = d3.behavior.zoom()
                    .scale(scale)
                    .scaleExtent([1, 5])
                    .on("zoom", zoomed);

                function zoomed() {
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
                    container.attr("transform",
                        "translate(" + zoom.translate() + ")" +
                        "scale(" + zoom.scale() + ")"
                    );
                }

                function interpolateZoom(translate, scale) {
                    var self = this;
                    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));
                            zoomed();
                        };
                    });
                }

                function zoomClick() {
                    var clicked = d3.event.target,
                        direction = 1,
                        factor = 0.5,
                        target_zoom = 1,
                        center = [width / 2, height / 2],
                        extent = zoom.scaleExtent(),
                        translate = zoom.translate(),
                        translate0 = [],
                        l = [],
                        view = { x: translate[0], y: translate[1], k: zoom.scale() };

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

                    if (target_zoom < extent[0] || target_zoom > extent[1]) { return false; }

                    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];

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

                    interpolateZoom([view.x, view.y], view.k);
325 326
                }

327 328


329
                d3.selectAll(this.$('.lineageZoomButton')).on('click', zoomClick);
330

331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
                var svg = d3.select(this.$("svg")[0])
                    .attr("viewBox", "0 0 " + width + " " + height)
                    .attr("enable-background", "new 0 0 " + width + " " + height)
                    .call(zoom)
                    .on("dblclick.zoom", null),
                    drag = force.drag()
                    .on("dragstart", dragstart);

                var container = svg.append("g")
                    .attr("id", "container")
                    .attr("transform", "translate(0,0)scale(1,1)");


                // build the arrow.
                container.append("svg:defs").selectAll("marker")
346
                    .data(["deletedLink", "activeLink"]) // Different link/path types can be defined here
347 348 349 350 351 352 353 354 355 356
                    .enter().append("svg:marker") // This section adds in the arrows
                    .attr("id", String)
                    .attr("viewBox", "0 -5 10 10")
                    .attr("refX", 10)
                    .attr("refY", -0.5)
                    .attr("markerWidth", 6)
                    .attr("markerHeight", 6)
                    .attr("orient", "auto")
                    .append("svg:path")
                    .attr("d", "M0,-5L10,0L0,5")
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
                    .attr("fill", function(d) {
                        return d == "deletedLink" ? deletedEntityColor : activeEntityColor;
                    });

                function getPathColor(options) {
                    return isAllEntityRelationDeleted(options) ? deletedEntityColor : activeEntityColor
                }

                function isAllEntityRelationDeleted(options) {
                    var data = options.data,
                        type = options.type;
                    var d = $.extend(true, {}, data);
                    if (d && !_.isArray(d.value)) {
                        d.value = [d.value];
                    }

                    return (_.findIndex(d.value, function(val) {
                        if (type == "node") {
                            return (val.entityStatus || val.status) == "ACTIVE"
                        } else {
                            return val.relationshipStatus == "ACTIVE"
                        }
                    }) == -1);
                }
381 382 383 384 385 386 387

                // add the links and the arrows
                var path = container.append("svg:g").selectAll("path")
                    .data(force.links())
                    .enter().append("svg:path")
                    //    .attr("class", function(d) { return "link " + d.type; })
                    .attr("class", "relatioship-link")
388 389 390 391
                    .attr("stroke", function(d) { return getPathColor({ data: d, type: 'path' }) })
                    .attr("marker-end", function(d) {
                        return "url(#" + (isAllEntityRelationDeleted({ data: d }) ? "deletedLink" : "activeLink") + ")";
                    });
392 393 394 395 396 397

                // define the nodes
                var node = container.selectAll(".node")
                    .data(force.nodes())
                    .enter().append("g")
                    .attr("class", "node")
398 399 400 401 402 403 404 405 406 407
                    .on('touchstart', function(d) {
                        if (d && d.value && d.value.guid != that.guid) {
                            d3.event.stopPropagation();
                        }
                    })
                    .on('mousedown', function(d) {
                        if (d && d.value && d.value.guid != that.guid) {
                            d3.event.stopPropagation();
                        }
                    })
408 409
                    .on('click', function(d) {
                        if (d3.event.defaultPrevented) return; // ignore drag
410 411 412 413
                        if (d && d.value && d.value.guid == that.guid) {
                            that.ui.boxClose.trigger('click');
                            return;
                        }
414
                        that.toggleBoxPanel({ el: that.$('.relationship-node-details') });
415
                        that.ui.searchNode.data({ obj: d });
416
                        $(this).find('circle').addClass("node-detail-highlight");
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
                        that.updateRelationshipDetails({ obj: d });

                    }).call(force.drag);

                // add the nodes
                var circleContainer = node.append("g");
                circleContainer.on("dblclick", function(d) {
                    if ((_.isArray(d.value) && d.value.length == 1) || d.value.guid) {
                        var guid = _.isArray(d.value) ? _.first(d.value).guid : d.value.guid;
                        Utils.setUrl({
                            url: '#!/detailPage/' + guid,
                            mergeBrowserUrl: false,
                            urlParams: { tabActive: 'relationship' },
                            trigger: true
                        });
                    }
                })
434

435

436 437 438 439 440 441 442 443 444
                circleContainer.append("circle")
                    .attr("cx", 0)
                    .attr("cy", 0)
                    .attr("r", function(d) {
                        d.radius = 25;
                        return d.radius;
                    })
                    .attr("fill", function(d) {
                        if (d && d.value && d.value.guid == that.guid) {
445 446 447
                            if (isAllEntityRelationDeleted({ data: d, type: 'node' })) {
                                return deletedEntityColor;
                            } else {
448
                                return selectedNodeColor;
449 450 451
                            }
                        } else if (isAllEntityRelationDeleted({ data: d, type: 'node' })) {
                            return deletedEntityColor;
452
                        } else {
453
                            return activeEntityColor;
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
                        }
                    })
                    .attr("typename", function(d) {
                        return d.name;
                    })
                circleContainer.append("text")
                    .attr('x', 0)
                    .attr('y', 0)
                    .attr('dy', (25 - 17))
                    .attr("text-anchor", "middle")
                    .style("font-family", "FontAwesome")
                    .style('font-size', function(d) { return '25px'; })
                    .text(function(d) {
                        var iconObj = Enums.graphIcon[d.name];
                        if (iconObj && iconObj.textContent) {
                            return iconObj.textContent;
                        } else {
                            if (d && _.isArray(d.value) && d.value.length > 1) {
                                return '\uf0c5';
                            } else {
                                return '\uf016';
                            }
                        }
                    })
                    .attr("fill", function(d) {
479
                        return "#fff";
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
                    });
                var countBox = circleContainer.append('g')
                countBox.append("circle")
                    .attr("cx", 18)
                    .attr("cy", -20)
                    .attr("r", function(d) {
                        if (_.isArray(d.value) && d.value.length > 1) {
                            return 10;
                        }
                    });

                countBox.append("text")
                    .attr('dx', 18)
                    .attr('dy', -16)
                    .attr("text-anchor", "middle")
495
                    .attr("fill", defaultEntityColor)
496
                    .text(function(d) {
497
                        if (_.isArray(d.value) && d.value.length > 1) {
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
                            return d.value.length;
                        }
                    });


                // add the text 
                node.append("text")
                    .attr("x", -15)
                    .attr("y", "35")
                    .text(function(d) { return d.name; });

                // add the curvy lines
                function tick() {
                    path.attr("d", function(d) {
                        var diffX = d.target.x - d.source.x,
                            diffY = d.target.y - d.source.y,

                            // Length of path from center of source node to center of target node
                            pathLength = Math.sqrt((diffX * diffX) + (diffY * diffY)),

                            // x and y distances from center to outside edge of target node
                            offsetX = (diffX * d.target.radius) / pathLength,
                            offsetY = (diffY * d.target.radius) / pathLength;

                        return "M" + d.source.x + "," + d.source.y + "A" + pathLength + "," + pathLength + " 0 0,1 " + (d.target.x - offsetX) + "," + (d.target.y - offsetY)
                    });

                    node.attr("transform", function(d) {
526 527 528 529
                        if (d && d.value && d.value.guid == that.guid) {
                            d.x = (width / 2)
                            d.y = (height / 2)
                        }
530 531 532 533 534 535 536
                        return "translate(" + d.x + "," + d.y + ")";
                    });
                }

                function dragstart(d) {
                    d3.select(this).classed("fixed", d.fixed = true);
                }
537 538 539
            },
            createTable: function() {
                this.entityModel = new VEntity({});
540
                var table = CommonViewFunction.propertyTable({ scope: this, valueObject: this.entity.relationshipAttributes, attributeDefs: this.attributeDefs });
541
                this.ui.relationshipDetailValue.html(table);
542 543 544 545
                Utils.togglePropertyRelationshipTableEmptyValues({
                    "inputType": this.ui.noValueToggle,
                    "tableEl": this.ui.relationshipDetailValue
                });
546 547
            },
            relationshipViewToggle: function(checked) {
548 549 550
                this.ui.relationshipDetailTable.toggleClass('visible invisible');
                this.ui.relationshipSVG.toggleClass('visible invisible');

551 552 553 554 555 556 557
                if (checked) {
                    this.ui.zoomControl.hide();
                    this.$el.addClass('auto-height');
                } else {
                    this.ui.zoomControl.show();
                    this.$el.removeClass('auto-height');
                }
558

559
            }
560 561 562
        });
    return RelationshipLayoutView;
});