[TASK] Rewrite forcegraph with d3 v4

This commit is contained in:
Martin Geno 2017-02-23 22:32:25 +01:00 committed by Xaver Maierhofer
parent d51c0fdb9d
commit 98f175d6a5
No known key found for this signature in database
GPG Key ID: 7FDCE23FD2EC9FE8
7 changed files with 459 additions and 735 deletions

View File

@ -8,6 +8,7 @@ A web-app to visualize nodes and links on a map for Freifunk open mesh network.
#### Main differences to https://github.com/ffnord/meshviewer
_Some similar features might have been implemented/merged_
- Forcegraph rewrite with d3.js v4
- Map layer modes (Allow to set a default layer based on time combined with a stylesheet)
- Automatic updates for selected node or list (incl. image stats cache-breaker)
- Node filter

21
app.js
View File

@ -14,7 +14,23 @@ require.config({
'leaflet.label': '../node_modules/leaflet-label/dist/leaflet.label',
'chroma-js': '../node_modules/chroma-js/chroma.min',
'moment': '../node_modules/moment/moment',
'd3': '../node_modules/d3/d3.min',
// d3 modules indirect dependencies
// by d3-zoom: d3-drag
'd3-ease': '../node_modules/d3-ease/build/d3-ease',
'd3-transition': '../node_modules/d3-transition/build/d3-transition',
'd3-color': '../node_modules/d3-color/build/d3-color',
'd3-interpolate': '../node_modules/d3-interpolate/build/d3-interpolate',
// by d3-force
'd3-collection': '../node_modules/d3-collection/build/d3-collection',
'd3-dispatch': '../node_modules/d3-dispatch/build/d3-dispatch',
'd3-quadtree': '../node_modules/d3-quadtree/build/d3-quadtree',
'd3-timer': '../node_modules/d3-timer/build/d3-timer',
// by d3-drag: d3-selection
// d3 modules dependencies
'd3-selection': '../node_modules/d3-selection/build/d3-selection',
'd3-force': '../node_modules/d3-force/build/d3-force',
'd3-zoom': '../node_modules/d3-zoom/build/d3-zoom',
'd3-drag': '../node_modules/d3-drag/build/d3-drag',
'virtual-dom': '../node_modules/virtual-dom/dist/virtual-dom',
'rbush': '../node_modules/rbush/rbush',
'helper': 'utils/helper',
@ -22,6 +38,9 @@ require.config({
},
shim: {
'leaflet.label': ['leaflet'],
'd3-drag': ['d3-selection'],
'd3-force': ['d3-collection', 'd3-dispatch', 'd3-quadtree', 'd3-timer'],
'd3-zoom': ['d3-drag', 'd3-ease', 'd3-transition', 'd3-color', 'd3-interpolate'],
'tablesort': {
exports: 'Tablesort'
}

View File

@ -1,762 +1,247 @@
define(['d3', 'helper'], function (d3, helper) {
'use strict';
define(['d3-selection', 'd3-force', 'd3-zoom', 'd3-drag', 'utils/math', 'forcegraph/draw'],
function (d3Selection, d3Force, d3Zoom, d3Drag, math, draw) {
'use strict';
var margin = 200;
var NODE_RADIUS = 15;
var LINE_RADIUS = 12;
return function (config, linkScale, sidebar, router) {
var self = this;
var el;
var canvas;
var ctx;
var force;
var forceLink;
return function (config, linkScale, sidebar, router) {
var self = this;
var canvas;
var ctx;
var screenRect;
var nodesDict;
var linksDict;
var zoomBehavior;
var force;
var el;
var font;
var doAnimation = false;
var intNodes = [];
var intLinks = [];
var highlight;
var highlightedNodes = [];
var highlightedLinks = [];
var nodes = [];
var uplinkNodes = [];
var nonUplinkNodes = [];
var unseenNodes = [];
var unknownNodes = [];
var savedPanZoom;
var transform = d3Zoom.zoomIdentity;
var intNodes = [];
var dictNodes = {};
var intLinks = [];
var draggedNode;
var NODE_RADIUS_DRAG = 10;
var NODE_RADIUS_SELECT = 15;
var LINK_RADIUS_SELECT = 12;
var LINK_DISTANCE = 70;
var ZOOM_MIN = 1 / 8;
var ZOOM_MAX = 3;
function graphDiameter(n) {
return Math.sqrt(n.length / Math.PI) * LINK_DISTANCE * 1.41;
}
var FORCE_ALPHA = 0.3;
function savePositions() {
var save = intNodes.map(function (d) {
return { id: d.o.id, x: d.x, y: d.y };
});
draw.setTransform(transform);
localStorage.setItem('graph/nodeposition', JSON.stringify(save));
}
function nodeName(d) {
if (d.o.node && d.o.node.nodeinfo) {
return d.o.node.nodeinfo.hostname;
}
return d.o.id;
}
function dragstart() {
var e = translateXY(d3.mouse(el));
var n = intNodes.filter(function (d) {
return distancePoint(e, d) < NODE_RADIUS;
});
if (n.length === 0) {
return;
function resizeCanvas() {
canvas.width = el.offsetWidth;
canvas.height = el.offsetHeight;
draw.setMaxArea(canvas.width, canvas.height);
}
draggedNode = n[0];
d3.event.sourceEvent.stopPropagation();
d3.event.sourceEvent.preventDefault();
draggedNode.fixed |= 2;
draggedNode.px = draggedNode.x;
draggedNode.py = draggedNode.y;
}
function dragmove() {
if (draggedNode) {
var e = translateXY(d3.mouse(el));
draggedNode.px = e.x;
draggedNode.py = e.y;
force.resume();
function moveTo(x, y) {
transform.x = (canvas.width + sidebar()) / 2 - x * transform.k;
transform.y = canvas.height / 2 - y * transform.k;
}
}
function dragend() {
if (draggedNode) {
d3.event.sourceEvent.stopPropagation();
d3.event.sourceEvent.preventDefault();
draggedNode.fixed &= ~2;
draggedNode = undefined;
}
}
var draggableNode = d3.behavior.drag()
.on('dragstart', dragstart)
.on('drag', dragmove)
.on('dragend', dragend);
function animatePanzoom(translate, scale) {
var translateP = zoomBehavior.translate();
var scaleP = zoomBehavior.scale();
if (!doAnimation) {
zoomBehavior.translate(translate);
zoomBehavior.scale(scale);
panzoom();
} else {
var start = { x: translateP[0], y: translateP[1], scale: scaleP };
var end = { x: translate[0], y: translate[1], scale: scale };
var interpolate = d3.interpolateObject(start, end);
var duration = 500;
var ease = d3.ease('cubic-in-out');
d3.timer(function (t) {
if (t >= duration) {
return true;
}
var v = interpolate(ease(t / duration));
zoomBehavior.translate([v.x, v.y]);
zoomBehavior.scale(v.scale);
panzoom();
return false;
});
}
}
function onPanZoom() {
savedPanZoom = {
translate: zoomBehavior.translate(),
scale: zoomBehavior.scale()
};
panzoom();
}
function panzoom() {
var translate = zoomBehavior.translate();
var scale = zoomBehavior.scale();
panzoomReal(translate, scale);
}
function panzoomReal(translate, scale) {
screenRect = {
left: -translate[0] / scale, top: -translate[1] / scale,
right: (canvas.width - translate[0]) / scale,
bottom: (canvas.height - translate[1]) / scale
};
requestAnimationFrame(redraw);
}
function getSize() {
var sidebarWidth = sidebar();
var width = el.offsetWidth - sidebarWidth;
var height = el.offsetHeight;
return [width, height];
}
function panzoomTo(a, b) {
var sidebarWidth = sidebar();
var size = getSize();
var targetWidth = Math.max(1, b[0] - a[0]);
var targetHeight = Math.max(1, b[1] - a[1]);
var scaleX = size[0] / targetWidth;
var scaleY = size[1] / targetHeight;
var scaleMax = zoomBehavior.scaleExtent()[1];
var scale = 0.5 * Math.min(scaleMax, Math.min(scaleX, scaleY));
var centroid = [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2];
var x = -centroid[0] * scale + size[0] / 2;
var y = -centroid[1] * scale + size[1] / 2;
var translate = [x + sidebarWidth, y];
animatePanzoom(translate, scale);
}
function updateHighlight(nopanzoom) {
highlightedNodes = [];
highlightedLinks = [];
if (highlight !== undefined) {
if (highlight.type === 'node') {
var n = nodesDict[highlight.o.nodeinfo.node_id];
if (n) {
highlightedNodes = [n];
if (!nopanzoom) {
panzoomTo([n.x, n.y], [n.x, n.y]);
}
}
function onClick() {
if (d3Selection.event.defaultPrevented) {
return;
} else if (highlight.type === 'link') {
var l = linksDict[highlight.o.id];
}
if (l) {
highlightedLinks = [l];
if (!nopanzoom) {
var x = d3.extent([l.source, l.target], function (d) {
return d.x;
});
var y = d3.extent([l.source, l.target], function (d) {
return d.y;
});
panzoomTo([x[0], y[0]], [x[1], y[1]]);
}
}
var e = transform.invert([d3Selection.event.clientX, d3Selection.event.clientY]);
var n = force.find(e[0], e[1], NODE_RADIUS_SELECT);
if (n !== undefined) {
router.node(n.o.node)();
return;
}
e = { x: e[0], y: e[1] };
var closedLink;
var radius = LINK_RADIUS_SELECT;
intLinks
.forEach(function (d) {
var distance = math.distanceLink(e, d.source, d.target);
if (distance < radius) {
closedLink = d;
radius = distance;
}
});
if (closedLink !== undefined) {
router.link(closedLink.o)();
}
}
if (!nopanzoom) {
if (!savedPanZoom) {
panzoomTo([0, 0], force.size());
} else {
animatePanzoom(savedPanZoom.translate, savedPanZoom.scale);
}
}
}
function drawLabel(d) {
var neighbours = d.neighbours.filter(function (n) {
return n.link.o.type !== 'fastd' && n.link.o.type !== 'L2TP';
});
var sum = neighbours.reduce(function (a, b) {
return [a[0] + b.node.x, a[1] + b.node.y];
}, [0, 0]);
var sumCos = sum[0] - d.x * neighbours.length;
var sumSin = sum[1] - d.y * neighbours.length;
var angle = Math.PI / 2;
if (neighbours.length > 0) {
angle = Math.PI + Math.atan2(sumSin, sumCos);
}
var cos = Math.cos(angle);
var sin = Math.sin(angle);
var width = d.labelWidth;
var height = d.labelHeight;
var x = d.x + d.labelA * Math.pow(Math.abs(cos), 2 / 5) * Math.sign(cos) - width / 2;
var y = d.y + d.labelB * Math.pow(Math.abs(sin), 2 / 5) * Math.sign(sin) - height / 2;
ctx.drawImage(d.label, x, y, width, height);
}
function visibleLinks(d) {
return (d.source.x > screenRect.left && d.source.x < screenRect.right &&
d.source.y > screenRect.top && d.source.y < screenRect.bottom) ||
(d.target.x > screenRect.left && d.target.x < screenRect.right &&
d.target.y > screenRect.top && d.target.y < screenRect.bottom);
}
function visibleNodes(d) {
return d.x + margin > screenRect.left && d.x - margin < screenRect.right &&
d.y + margin > screenRect.top && d.y - margin < screenRect.bottom;
}
function drawNode(color, radius, scale, r) {
var node = document.createElement('canvas');
node.height = node.width = scale * radius * 8 * r;
var nctx = node.getContext('2d');
nctx.scale(scale * r, scale * r);
nctx.save();
nctx.translate(-node.width / scale, -node.height / scale);
nctx.lineWidth = radius;
nctx.beginPath();
nctx.moveTo(radius, 0);
nctx.arc(0, 0, radius, 0, 2 * Math.PI);
nctx.restore();
nctx.translate(node.width / 2 / scale / r, node.height / 2 / scale / r);
nctx.beginPath();
nctx.moveTo(radius, 0);
nctx.arc(0, 0, radius, 0, 2 * Math.PI);
nctx.strokeStyle = color;
nctx.lineWidth = radius;
nctx.stroke();
return node;
}
function redraw() {
var r = window.devicePixelRatio;
var translate = zoomBehavior.translate();
var scale = zoomBehavior.scale();
var links = intLinks.filter(visibleLinks);
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.restore();
ctx.save();
ctx.translate(translate[0], translate[1]);
ctx.scale(scale, scale);
var clientColor = 'rgba(230, 50, 75, 1.0)';
var unknownColor = '#D10E2A';
var nonUplinkColor = '#F2E3C6';
var uplinkColor = '#5BAAEB';
var unseenColor = '#FFA726';
var highlightColor = 'rgba(252, 227, 198, 0.15)';
var nodeRadius = 6;
var cableColor = '#50B0F0';
// -- draw links --
ctx.save();
links.forEach(function (d) {
var dx = d.target.x - d.source.x;
var dy = d.target.y - d.source.y;
var a = Math.sqrt(dx * dx + dy * dy);
dx /= a;
dy /= a;
ctx.beginPath();
ctx.moveTo(d.source.x + dx * nodeRadius, d.source.y + dy * nodeRadius);
ctx.lineTo(d.target.x - dx * nodeRadius, d.target.y - dy * nodeRadius);
ctx.strokeStyle = d.o.type === 'Kabel' ? cableColor : d.color;
ctx.globalAlpha = d.o.type === 'fastd' || d.o.type === 'L2TP' ? 0.2 : 0.8;
ctx.lineWidth = d.o.type === 'fastd' || d.o.type === 'L2TP' ? 1.5 : 2.5;
ctx.stroke();
});
ctx.restore();
// -- draw unknown nodes --
ctx.beginPath();
unknownNodes.filter(visibleNodes).forEach(function (d) {
ctx.moveTo(d.x + nodeRadius, d.y);
ctx.arc(d.x, d.y, nodeRadius, 0, 2 * Math.PI);
});
ctx.strokeStyle = unknownColor;
ctx.lineWidth = nodeRadius;
ctx.stroke();
// -- draw nodes --
ctx.save();
ctx.scale(1 / scale / r, 1 / scale / r);
var nonUplinkNode = drawNode(nonUplinkColor, nodeRadius, scale, r);
nonUplinkNodes.filter(visibleNodes).forEach(function (d) {
ctx.drawImage(nonUplinkNode, scale * r * d.x - nonUplinkNode.width / 2, scale * r * d.y - nonUplinkNode.height / 2);
});
var uplinkNode = drawNode(uplinkColor, nodeRadius, scale, r);
uplinkNodes.filter(visibleNodes).forEach(function (d) {
ctx.drawImage(uplinkNode, scale * r * d.x - uplinkNode.width / 2, scale * r * d.y - uplinkNode.height / 2);
});
var unseenNode = drawNode(unseenColor, nodeRadius, scale, r);
unseenNodes.filter(visibleNodes).forEach(function (d) {
ctx.drawImage(unseenNode, scale * r * d.x - unseenNode.width / 2, scale * r * d.y - unseenNode.height / 2);
});
ctx.restore();
// -- draw clients --
ctx.save();
ctx.beginPath();
if (scale > 0.9) {
var startDistance = 16;
nodes.filter(visibleNodes).forEach(function (d) {
helper.positionClients(ctx, d, Math.PI, d.o.node.statistics.clients, startDistance);
});
}
ctx.fillStyle = clientColor;
ctx.fill();
ctx.restore();
// -- draw node highlights --
if (highlightedNodes.length) {
function redraw() {
ctx.save();
ctx.globalCompositeOperation = 'lighten';
ctx.fillStyle = highlightColor;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.translate(transform.x, transform.y);
ctx.scale(transform.k, transform.k);
ctx.beginPath();
highlightedNodes.forEach(function (d) {
ctx.moveTo(d.x + 5 * nodeRadius, d.y);
ctx.arc(d.x, d.y, 5 * nodeRadius, 0, 2 * Math.PI);
});
ctx.fill();
intLinks.forEach(draw.drawLink);
intNodes.forEach(draw.drawNode);
ctx.restore();
}
// -- draw link highlights --
if (highlightedLinks.length) {
ctx.save();
ctx.lineWidth = 2 * 5 * nodeRadius;
ctx.globalCompositeOperation = 'lighten';
ctx.strokeStyle = highlightColor;
ctx.lineCap = 'round';
el = document.createElement('div');
el.classList.add('graph');
ctx.beginPath();
highlightedLinks.forEach(function (d) {
ctx.moveTo(d.source.x, d.source.y);
ctx.lineTo(d.target.x, d.target.y);
});
ctx.stroke();
ctx.restore();
}
// -- draw labels --
if (scale > 0.9) {
intNodes.filter(visibleNodes).forEach(drawLabel, scale);
}
ctx.restore();
}
function tickEvent() {
redraw();
}
function resizeCanvas() {
var r = window.devicePixelRatio;
canvas.width = el.offsetWidth * r;
canvas.height = el.offsetHeight * r;
canvas.style.width = el.offsetWidth + 'px';
canvas.style.height = el.offsetHeight + 'px';
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.scale(r, r);
requestAnimationFrame(redraw);
}
function distance(a, b) {
return Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2);
}
function distancePoint(a, b) {
return Math.sqrt(distance(a, b));
}
function distanceLink(p, a, b) {
/* http://stackoverflow.com/questions/849211 */
var l2 = distance(a, b);
if (l2 === 0) {
return distance(p, a);
}
var t = ((p.x - a.x) * (b.x - a.x) + (p.y - a.y) * (b.y - a.y)) / l2;
if (t < 0) {
return distance(p, a);
}
if (t > 1) {
return distance(p, b);
}
return Math.sqrt(distance(p, {
x: a.x + t * (b.x - a.x),
y: a.y + t * (b.y - a.y)
}));
}
function translateXY(d) {
var translate = zoomBehavior.translate();
var scale = zoomBehavior.scale();
return {
x: (d[0] - translate[0]) / scale,
y: (d[1] - translate[1]) / scale
};
}
function onClick() {
if (d3.event.defaultPrevented) {
return;
}
var e = translateXY(d3.mouse(el));
var n = intNodes.filter(function (d) {
return distancePoint(e, d) < NODE_RADIUS;
});
if (n.length > 0) {
router.node(n[0].o.node)();
return;
}
var links = intLinks.filter(function (d) {
return d.o.type !== 'fastd' && d.o.type !== 'L2TP';
}).filter(function (d) {
return distanceLink(e, d.source, d.target) < LINE_RADIUS;
});
if (links.length > 0) {
router.link(links[0].o)();
}
}
function zoom(z, scale) {
var size = getSize();
var newSize = [size[0] / scale, size[1] / scale];
var sidebarWidth = sidebar();
var delta = [size[0] - newSize[0], size[1] - newSize[1]];
var translate = z.translate();
var translateNew = [sidebarWidth + (translate[0] - sidebarWidth - delta[0] / 2) * scale, (translate[1] - delta[1] / 2) * scale];
animatePanzoom(translateNew, z.scale() * scale);
}
function keyboardZoom(z) {
return function () {
var e = d3.event;
if (e.altKey || e.ctrlKey || e.metaKey) {
return;
}
if (e.keyCode === 43) {
zoom(z, 1.41);
}
if (e.keyCode === 45) {
zoom(z, 1 / 1.41);
}
};
}
el = document.createElement('div');
el.classList.add('graph');
font = window.getComputedStyle(el).fontSize + ' ' + window.getComputedStyle(el).fontFamily;
zoomBehavior = d3.behavior.zoom()
.scaleExtent([1 / 3, 3])
.on('zoom', onPanZoom)
.translate([sidebar(), 0]);
canvas = d3.select(el)
.attr('tabindex', 1)
.on('keypress', keyboardZoom(zoomBehavior))
.call(zoomBehavior)
.append('canvas')
.on('click', onClick)
.call(draggableNode)
.node();
ctx = canvas.getContext('2d');
force = d3.layout.force()
.charge(-250)
.gravity(0.1)
.linkDistance(function (d) {
if (d.o.type === 'fastd' || d.o.type === 'L2TP') {
return 0;
}
return LINK_DISTANCE;
})
.linkStrength(function (d) {
if (d.o.type === 'fastd' || d.o.type === 'L2TP') {
return 0.02;
}
return Math.max(0.5, 1 / d.o.tq);
})
.on('tick', tickEvent)
.on('end', savePositions);
window.addEventListener('resize', resizeCanvas);
panzoom();
self.setData = function setData(data) {
var oldNodes = {};
intNodes.forEach(function (d) {
oldNodes[d.o.id] = d;
});
intNodes = data.graph.nodes.map(function (d) {
var e;
if (d.id in oldNodes) {
e = oldNodes[d.id];
} else {
e = {};
}
e.o = d;
return e;
});
var newNodesDict = {};
intNodes.forEach(function (d) {
newNodesDict[d.o.id] = d;
});
var oldLinks = {};
intLinks.forEach(function (d) {
oldLinks[d.o.id] = d;
});
intLinks = data.graph.links.map(function (d) {
var e;
if (d.id in oldLinks) {
e = oldLinks[d.id];
} else {
e = {};
}
e.o = d;
e.source = newNodesDict[d.source.id];
e.target = newNodesDict[d.target.id];
e.color = linkScale(d.tq).hex();
return e;
});
linksDict = {};
nodesDict = {};
intNodes.forEach(function (d) {
d.neighbours = {};
if (d.o.node) {
nodesDict[d.o.node.nodeinfo.node_id] = d;
}
var name = nodeName(d);
var offset = 5;
var lineWidth = 3;
var buffer = document.createElement('canvas');
var r = window.devicePixelRatio;
var bctx = buffer.getContext('2d');
bctx.font = font;
var width = bctx.measureText(name).width;
var scale = zoomBehavior.scaleExtent()[1] * r;
buffer.width = (width + 2 * lineWidth) * scale;
buffer.height = (16 + 2 * lineWidth) * scale;
bctx.font = font;
bctx.scale(scale, scale);
bctx.textBaseline = 'middle';
bctx.textAlign = 'center';
bctx.fillStyle = 'rgba(242, 227, 198, 1.0)';
bctx.fillText(name, buffer.width / (2 * scale), buffer.height / (2 * scale));
d.label = buffer;
d.labelWidth = buffer.width / scale;
d.labelHeight = buffer.height / scale;
d.labelA = offset + buffer.width / (2 * scale);
d.labelB = offset + buffer.height / (2 * scale);
});
intNodes.forEach(function (d) {
d.neighbours = Object.keys(d.neighbours).map(function (k) {
return d.neighbours[k];
});
});
nodes = intNodes.filter(function (d) {
return !d.o.unseen && d.o.node;
});
uplinkNodes = nodes.filter(function (d) {
return d.o.node.flags.uplink;
});
nonUplinkNodes = nodes.filter(function (d) {
return !d.o.node.flags.uplink;
});
unseenNodes = intNodes.filter(function (d) {
return d.o.unseen && d.o.node;
});
unknownNodes = intNodes.filter(function (d) {
return !d.o.node;
});
var save = JSON.parse(localStorage.getItem('graph/nodeposition'));
if (save) {
var nodePositions = {};
save.forEach(function (d) {
nodePositions[d.id] = d;
});
intNodes.forEach(function (d) {
if (nodePositions[d.o.id] && (d.x === undefined || d.y === undefined)) {
d.x = nodePositions[d.o.id].x;
d.y = nodePositions[d.o.id].y;
forceLink = d3Force.forceLink()
.distance(function (d) {
if (d.o.type === 'fastd' || d.o.type === 'L2TP') {
return 0;
}
return 75;
})
.strength(function (d) {
if (d.o.type === 'fastd' || d.o.type === 'L2TP') {
return 0.02;
}
return Math.max(0.5, 1 / d.o.tq);
});
}
var diameter = graphDiameter(intNodes);
var zoom = d3Zoom.zoom()
.scaleExtent([ZOOM_MIN, ZOOM_MAX])
.on('zoom', function () {
transform = d3Selection.event.transform;
draw.setTransform(transform);
redraw();
});
force.nodes(intNodes)
.links(intLinks)
.size([diameter, diameter]);
force = d3Force.forceSimulation()
.force('link', forceLink)
.force('charge', d3Force.forceManyBody())
.force('x', d3Force.forceX().strength(0.02))
.force('y', d3Force.forceY().strength(0.02))
.force('collide', d3Force.forceCollide())
.on('tick', redraw);
updateHighlight(true);
var drag = d3Drag.drag()
.subject(function () {
var e = transform.invert([d3Selection.event.x, d3Selection.event.y]);
var n = force.find(e[0], e[1], NODE_RADIUS_DRAG);
force.start();
resizeCanvas();
if (n !== undefined) {
n.x = d3Selection.event.x;
n.y = d3Selection.event.y;
return n;
}
return undefined;
})
.on('start', function () {
if (!d3Selection.event.active) {
force.alphaTarget(FORCE_ALPHA).restart();
}
d3Selection.event.subject.fx = transform.invertX(d3Selection.event.subject.x);
d3Selection.event.subject.fy = transform.invertY(d3Selection.event.subject.y);
})
.on('drag', function () {
d3Selection.event.subject.fx = transform.invertX(d3Selection.event.x);
d3Selection.event.subject.fy = transform.invertY(d3Selection.event.y);
})
.on('end', function () {
if (!d3Selection.event.active) {
force.alphaTarget(0);
}
d3Selection.event.subject.fx = null;
d3Selection.event.subject.fy = null;
});
canvas = d3Selection.select(el)
.append('canvas')
.on('click', onClick)
.call(drag)
.call(zoom)
.node();
ctx = canvas.getContext('2d');
draw.setCTX(ctx);
window.addEventListener('resize', function () {
resizeCanvas();
redraw();
});
self.setData = function setData(data) {
intNodes = data.graph.nodes.map(function (d) {
var e;
if (d.id in dictNodes) {
e = dictNodes[d.id];
} else {
e = {};
dictNodes[d.id] = e;
}
e.o = d;
return e;
});
intLinks = data.graph.links.map(function (d) {
var e = {};
e.o = d;
e.source = dictNodes[d.source.id];
e.target = dictNodes[d.target.id];
e.color = linkScale(d.tq).hex();
return e;
});
force.nodes(intNodes);
forceLink.links(intLinks);
force.alpha(1).restart();
resizeCanvas();
};
self.resetView = function resetView() {
draw.setHighlight(null);
transform.k = (ZOOM_MIN + 1) / 2;
moveTo(0, 0);
redraw();
};
self.gotoNode = function gotoNode(d) {
draw.setHighlight({ type: 'node', o: d });
for (var i = 0; i < intNodes.length; i++) {
var n = intNodes[i];
if (n.o.node !== d) {
continue;
}
transform.k = (ZOOM_MAX + 1) / 2;
moveTo(n.x, n.y);
break;
}
redraw();
};
self.gotoLink = function gotoLink(d) {
draw.setHighlight({ type: 'link', o: d });
for (var i = 0; i < intLinks.length; i++) {
var l = intLinks[i];
if (l.o !== d) {
continue;
}
moveTo((l.source.x + l.target.x) / 2, (l.source.y + l.target.y) / 2);
break;
}
redraw();
};
self.destroy = function destroy() {
force.stop();
canvas.remove();
force = null;
if (el.parentNode) {
el.parentNode.removeChild(el);
}
};
self.render = function render(d) {
d.appendChild(el);
resizeCanvas();
};
return self;
};
self.resetView = function resetView() {
highlight = undefined;
updateHighlight();
doAnimation = true;
};
self.gotoNode = function gotoNode(d) {
highlight = { type: 'node', o: d };
updateHighlight();
doAnimation = true;
};
self.gotoLink = function gotoLink(d) {
highlight = { type: 'link', o: d };
updateHighlight();
doAnimation = true;
};
self.destroy = function destroy() {
force.stop();
canvas.remove();
force = null;
if (el.parentNode) {
el.parentNode.removeChild(el);
}
};
self.render = function render(d) {
d.appendChild(el);
resizeCanvas();
updateHighlight();
};
return self;
};
});
});

120
lib/forcegraph/draw.js Normal file
View File

@ -0,0 +1,120 @@
define(['helper'], function (helper) {
var self = {};
var ctx;
var width;
var height;
var transform;
var highlight;
var nodeColor = '#fff';
var clientColor = '#e6324b';
var cableColor = '#50b0f0';
var highlightColor = 'rgba(255, 255, 255, 0.2)';
var labelColor = '#fff';
var NODE_RADIUS = 15;
var LINE_RADIUS = 12;
function drawDetailNode(d) {
if (transform.k > 1) {
ctx.beginPath();
helper.positionClients(ctx, d, Math.PI, d.o.node.statistics.clients, 15);
ctx.fillStyle = clientColor;
ctx.fill();
ctx.beginPath();
var name = d.o.node_id;
if (d.o.node && d.o.node.nodeinfo) {
name = d.o.node.nodeinfo.hostname;
}
ctx.textAlign = 'center';
ctx.fillStyle = labelColor;
ctx.fillText(name, d.x, d.y + 20);
}
}
function drawHighlightNode(d) {
if (highlight && highlight.type === 'node' && d.o.node === highlight.o) {
ctx.arc(d.x, d.y, NODE_RADIUS * 1.5, 0, 2 * Math.PI);
ctx.fillStyle = highlightColor;
ctx.fill();
ctx.beginPath();
}
}
function drawHighlightLink(d, to) {
if (highlight && highlight.type === 'link' && d.o === highlight.o) {
ctx.lineTo(to[0], to[1]);
ctx.strokeStyle = highlightColor;
ctx.lineWidth = LINE_RADIUS * 2;
ctx.lineCap = 'round';
ctx.stroke();
to = [d.source.x, d.source.y];
}
return to;
}
self.drawNode = function drawNode(d) {
if (d.x < transform.invertX(0) || d.y < transform.invertY(0) || transform.invertX(width) < d.x || transform.invertY(height) < d.y) {
return;
}
ctx.beginPath();
drawHighlightNode(d);
ctx.moveTo(d.x + 3, d.y);
ctx.arc(d.x, d.y, 8, 0, 2 * Math.PI);
ctx.fillStyle = nodeColor;
ctx.fill();
drawDetailNode(d);
};
self.drawLink = function drawLink(d) {
var zero = transform.invert([0, 0]);
var area = transform.invert([width, height]);
if (d.source.x < zero[0] && d.target.x < zero[0] || d.source.y < zero[1] && d.target.y < zero[1] ||
d.source.x > area[0] && d.target.x > area[0] || d.source.y > area[1] && d.target.y > area[1]) {
return;
}
ctx.beginPath();
ctx.moveTo(d.source.x, d.source.y);
var to = [d.target.x, d.target.y];
to = drawHighlightLink(d, to);
ctx.lineTo(to[0], to[1]);
ctx.strokeStyle = d.o.type === 'Kabel' ? cableColor : d.color;
if (d.o.type === 'fastd' || d.o.type === 'L2TP') {
ctx.globalAlpha = 0.2;
ctx.lineWidth = 1.5;
} else {
ctx.globalAlpha = 0.8;
ctx.lineWidth = 2.5;
}
ctx.stroke();
};
self.setCTX = function setCTX(newValue) {
ctx = newValue;
};
self.setHighlight = function setHighlight(newValue) {
highlight = newValue;
};
self.setTransform = function setTransform(newValue) {
transform = newValue;
};
self.setMaxArea = function setMaxArea(newWidth, newHeight) {
width = newWidth;
height = newHeight;
};
return self;
});

29
lib/utils/math.js Normal file
View File

@ -0,0 +1,29 @@
define(function () {
return {
distance: function distance(a, b) {
return Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2);
},
distancePoint: function distancePoint(a, b) {
return Math.sqrt(distance(a, b));
},
distanceLink: function distanceLink(p, a, b) {
/* http://stackoverflow.com/questions/849211 */
var l2 = distance(a, b);
if (l2 === 0) {
return distance(p, a);
}
var t = ((p.x - a.x) * (b.x - a.x) + (p.y - a.y) * (b.y - a.y)) / l2;
if (t < 0) {
return distance(p, a);
} else if (t > 1) {
return distance(p, b);
}
return distancePoint(p, {
x: a.x + t * (b.x - a.x),
y: a.y + t * (b.y - a.y)
});
}
};
});

View File

@ -44,7 +44,10 @@
"dependencies": {
"almond": "^0.3.3",
"chroma-js": "^1.2.1",
"d3": "3.5",
"d3-drag": "^1.0.3",
"d3-force": "^1.0.5",
"d3-selection": "^1.0.4",
"d3-zoom": "^1.1.2",
"leaflet": "https://github.com/davojta/Leaflet.git#stable_0_7_7_1_release",
"leaflet-label": "^0.2.1-0",
"moment": "^2.17.1",

View File

@ -683,9 +683,76 @@ currently-unhandled@^0.4.1:
dependencies:
array-find-index "^1.0.1"
d3@3.5:
version "3.5.17"
resolved "https://registry.yarnpkg.com/d3/-/d3-3.5.17.tgz#bc46748004378b21a360c9fc7cf5231790762fb8"
d3-collection@1:
version "1.0.2"
resolved "https://registry.yarnpkg.com/d3-collection/-/d3-collection-1.0.2.tgz#df5acb5400443e9eabe9c1379896c67e52426b39"
d3-color@1:
version "1.0.2"
resolved "https://registry.yarnpkg.com/d3-color/-/d3-color-1.0.2.tgz#83cb4b3a9474e40795f009d97e97a15649830bbc"
d3-dispatch@1:
version "1.0.2"
resolved "https://registry.yarnpkg.com/d3-dispatch/-/d3-dispatch-1.0.2.tgz#5b511e79a46a1f89492841c0a8f656687d5daa0a"
d3-drag@1, d3-drag@^1.0.3:
version "1.0.3"
resolved "https://registry.yarnpkg.com/d3-drag/-/d3-drag-1.0.3.tgz#a016d21c696d130ba758babf1cd9e5f049169d0b"
dependencies:
d3-dispatch "1"
d3-selection "1"
d3-ease@1:
version "1.0.2"
resolved "https://registry.yarnpkg.com/d3-ease/-/d3-ease-1.0.2.tgz#b486f8f3ca308ca7be38197d65622b6e30983377"
d3-force@^1.0.5:
version "1.0.5"
resolved "https://registry.yarnpkg.com/d3-force/-/d3-force-1.0.5.tgz#be8f65ac70688b8d26a9d9bc1e4699c1525f46b1"
dependencies:
d3-collection "1"
d3-dispatch "1"
d3-quadtree "1"
d3-timer "1"
d3-interpolate@1:
version "1.1.3"
resolved "https://registry.yarnpkg.com/d3-interpolate/-/d3-interpolate-1.1.3.tgz#e119c91b6be4941e581675ca3e1279bb92bd2c9b"
dependencies:
d3-color "1"
d3-quadtree@1:
version "1.0.2"
resolved "https://registry.yarnpkg.com/d3-quadtree/-/d3-quadtree-1.0.2.tgz#e7e873af06aaa427eaa4af094cc4cbfb350b9e38"
d3-selection@1, d3-selection@^1.0.4:
version "1.0.4"
resolved "https://registry.yarnpkg.com/d3-selection/-/d3-selection-1.0.4.tgz#b862c7ae22436efe8459b7659ccdae84f09b43a3"
d3-timer@1:
version "1.0.4"
resolved "https://registry.yarnpkg.com/d3-timer/-/d3-timer-1.0.4.tgz#adaf7f60c7b54c99b2ffabd28c15a0c108a75321"
d3-transition@1:
version "1.0.3"
resolved "https://registry.yarnpkg.com/d3-transition/-/d3-transition-1.0.3.tgz#91dc986bddb30973639320a85db72ce4ab1a27bb"
dependencies:
d3-color "1"
d3-dispatch "1"
d3-ease "1"
d3-interpolate "1"
d3-selection "1"
d3-timer "1"
d3-zoom@^1.1.2:
version "1.1.2"
resolved "https://registry.yarnpkg.com/d3-zoom/-/d3-zoom-1.1.2.tgz#a8944947e92a12bc5d5a3fb4dccf1a40e7de5fb3"
dependencies:
d3-dispatch "1"
d3-drag "1"
d3-interpolate "1"
d3-selection "1"
d3-transition "1"
d@^0.1.1, d@~0.1.1:
version "0.1.1"