d3.js is cool. So is node.js. Hence, doing something with both technologies is almost a logical consequence.
Start the Demo at least in two browser instances/devices (tested with Firefox, Chrome, IE9+, iPad, iPhone). Then click to create and to burst bubbles. Drag the bubbles around and try the action buttons to force larger changes to the d3.js scene.
This demo maintains a pool of “circles” on the server and implements the distributed MVC pattern. The Model is kept on the server. Each instance of the browser keeps a copy of the View and the Controller. Furthermore, a lightweight version of the model is used for data presentation and is processed by the d3 engine. The node.js based server is responsible for synchronization of all models via push messages. All user interaction triggers a change on the server model first. This holds true even for the initiating client. An example scenario follows:
- user clicks on a bubble
- the event handler reads the „id“ of the SVG-circle element and calls the server side function remove(id)
- the server updates the model
- the server calls the removeData(id) function for each connected client (including the initiating one)
- the data structure in the client is updated (in this example the object with the specified id is removed)
- d3.js scene is updated
The static files (index.html, CSS, templates and Javascript files) are served using express.js. The socket.io library is used as a convenience layer on top of websockets and provides a reliable permanent server/client connection.
Remarks regarding performance issues:
- the good news: node.js and websockets are blazingly fast, playing with the demo for some minutes in three browser instances generates a CPU usage time for the node.js process of about 5 seconds, i.e. there is plenty of room for more serious stuff
- advice: use SVG opacity styles instead of HTML opacity styles whenever possible, this reduces the SVG render time and enables larger SVG scenes (10 fold improvement in Firefox)
The source code for the server application is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 |
// utility library, see: http://underscorejs.org/ var _ = require('underscore'); // initialize web server framework var express = require('express'); var app = express(); var http = require('http'); http.globalAgent.maxSockets = 500; var server = http.createServer(app); var logFile = require('fs').createWriteStream('./circle.log', {flags: 'a'}); app.use(express.logger({stream: logFile})); app.use(express.compress()); app.use(express.static(__dirname + '/public')); // websocket var io = require('socket.io').listen(server, {log: false}); //the circle model var model = require('./model').model; model.populate(); // listen on connection event using namespace 'circle' io.of('/circle').on('connection', function (socket) { var address = socket.handshake.address; logFile.write("New connection from " + address.address + '\n'); logFile.write('send circle data: ' + model.getSize() + ' entries' + '\n'); // any connecting client gets the complete model data socket.emit('update', {ts: Date.now(), circles: model.getData()}); var behaviour = { 'add': add, 'remove': remove, 'resize': resize, 'moveStart': moveStart, 'move': move, 'moveEnd': moveEnd }; // map events to functions _.map(behaviour, function(func, eventName) { socket.on(eventName, _.bind(func, socket)); }); }); function add(attr) { logFile.write('add circle: x=' + attr.x + ', y=' + attr.y + '\n'); var entry = model.add(attr); io.of('/circle').emit('add', {ts: Date.now(), entry: entry}); } function remove(id) { logFile.write('remove circle: id=' + id + '\n'); id = model.remove(id); if (id != -1) io.of('/circle').emit('remove', {ts: Date.now(), id: id}); } function resize(info) { var entry = model.resize(info.id, info.delta); if (entry) io.of('/circle').emit('resize', {ts: Date.now(), entry: entry}); } function moveStart(id) { logFile.write('moveStart circle: id=' + id + '\n'); //socket.broadcast.emit('circles moveStart', {ts: Date.now(), id: id}); io.of('/circle').emit('moveStart', {ts: Date.now(), id: id}); } function moveEnd(entry) { logFile.write('moveEnd circle: id=' + entry.id + ', x=' + entry.x + ', y=' + entry.y + '\n'); model.move(entry); io.of('/circle').emit('moveEnd', {ts: Date.now(), entry: entry}); } function move(entry) { io.of('/circle').emit('move', {ts: Date.now(), entry: entry}); } //the job controller var jobs = require('./jobs').jobs; // prevent "flooding" the websocket connection with jobs update events jobs.onChange = _.throttle(function () { io.of('/jobs').emit('update', jobs.getData()); }, 333); //listen on connection event using namespace 'jobs' io.of('/jobs').on('connection', function (socket) { logFile.write('send job list\n'); // any connecting client gets the complete job data socket.emit('update', jobs.getData()); var behaviour = { 'shuffle': shuffle, 'stream': stream, 'reset': reset }; // map events to functions _.map(behaviour, function(func, eventName) { socket.on(eventName, _.bind(func, socket)); }); }); function shuffle() { jobs.start('shuffle', function (job) { model.shuffle(); io.of('/circle').emit('update', {ts: Date.now(), circles: model.getData()}); setTimeout(function () { job.complete(); logFile.write('shuffle completed' + '\n'); }, 1000); }); logFile.write('shuffle started' + '\n'); } function stream() { var count = 100; function streamEvent (job) { io.of('/circle').emit('add', {ts: Date.now(), entry: model.add(0, 0)}); io.of('/circle').emit('remove', {ts: Date.now(), id: model.removeRandom()}); if (--count) { setTimeout(function(){streamEvent(job);}, 150); job.running(100 - count); } else { job.complete(); logFile.write('stream completed' + '\n'); } } jobs.start('stream', streamEvent); logFile.write('stream started' + '\n'); } function reset() { jobs.start('reset', function (job) { model.populate(); io.of('/circle').emit('update', {ts: Date.now(), circles: model.getData()}); setTimeout(function () { job.complete(); }, 600); logFile.write('reset' + '\n'); }); } // start the server server.listen(7777, function () { logFile.write('circle demo started on port ' + server.address().port + '\n'); }); |
The server model:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 |
var _ = require('underscore'); // the circle model exports.model = { INIT_CIRCLES: 20, SIZE: 450, COLORS: ["red","orange","blue","green"], nextId: 1, data: [], random: function(pool) { if (_.isFinite(pool)) { return (Math.random()*pool)|0; } if (_.isArray(pool)) { return pool[Math.random()*pool.length|0]; } return Math.random(); }, getData: function() { return this.data; }, getSize: function() { return this.data.length; }, getColorStatistics: function() { var colors = _.object(this.COLORS, [0, 0, 0, 0]); for (var i=0; i< this.data.length; i++) { colors[this.data[i].color] += 1; } return colors; }, add: function(attr) { var entry = { id: this.nextId++, x: attr.x || this.SIZE - 30 - this.random(this.SIZE - 60), y: attr.y || this.SIZE - 30 - this.random(this.SIZE - 60), r: 30 + this.random(35), color: this.random(this.COLORS), opacity: (30 + this.random(50))/100 }; this.data.push(entry); return entry; }, resize: function(id, delta) { var factor = (delta > 0) ? 1.03 : 1/1.03; for (var i=0; i< this.data.length; i++) { var d = this.data[i]; if (d.id == id) { var old = d.r; d.r *= factor; d.r = Math.min(150, Math.max(20, d.r)); if (d.r == old) return null; else return d; } } }, move: function(entry) { for (var i=0; i< this.data.length; i++) { var d = this.data[i]; if (d.id == entry.id) { d.x = entry.x; d.y = entry.y; // move to end, emulates highest z-index this.data.splice(i, 1); this.data.push(d); return; } } }, remove: function(id) { for (var i=0; i< this.data.length; i++) { if (this.data[i].id == id) { this.data.splice(i, 1); return id; } } return -1; }, removeRandom: function() { if (this.data.length) { var i = this.random(this.data.length); var id = this.data[i].id; this.data.splice(i, 1); return id; } return -1; }, populate: function() { this.data = []; for (var i=0; i< this.INIT_CIRCLES; i++) { this.add({x: 0, y: 0}); } }, shuffle: function() { for (var i=0; i< this.data.length; i++) { this.data[i].x = this.SIZE - 30 - this.random(this.SIZE - 60); this.data[i].y = this.SIZE - 30 - this.random(this.SIZE - 60); } } }; //TODO: normalize size and position data, get rid of pixel related information |
The client code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 |
var CircleController = can.Control({ isMobile: navigator.userAgent.match(/Mobile/i), init: function () { var me = this; this.eventCount = 0; // an array of circle objects this.data = []; var fragment = can.view('/templates/circle.ejs'); this.element.html(fragment); this.setupDrawingArea(); this.setupWebsocket(); var throttleResize = _.throttle(function (info) { me.socket.emit('resize', info); }, 25); this.element.bind('mousewheel', function(event, delta, deltaX, deltaY) { if (event.target.nodeName == 'circle') throttleResize({id: event.target.getAttribute('id'), delta: delta}); event.preventDefault(); }); }, setupDrawingArea: function () { var me = this; // setup drawing area this.element.css("width", "450px").css("height", "450px"); this.scene = d3.select(this.element.find("svg")[0]) .attr("width", 500).attr("height", 500) .on("click", function() { var target = d3.event.target; if (target.nodeName == 'circle') { var id = d3.select(target).attr("id"); me.socket.emit('remove', id); } else { var pos = d3.mouse(this); me.socket.emit('add', {x: pos[0]|0, y: pos[1]|0}); } }); }, enter: function () { this.dragging = false; var me = this; function dragStart() { me.dragging = true; var circle = d3.select(this); var id = circle.attr("id"); me.socket.emit('moveStart', id); }; function dragMove() { var circle = d3.select(this); var ev = d3.event; circle.attr("cx", ev.dx + parseInt(circle.attr("cx"))); circle.attr("cy", ev.dy + parseInt(circle.attr("cy"))); var id = circle.attr("id"); var x = circle.attr('cx'); var y = circle.attr('cy'); me.socket.emit('move', {id: id, x: x, y: y}); }; function dragEnd() { me.dragging = false; var circle = d3.select(this); var id = circle.attr("id"); var x = Math.min(450, Math.max(0, circle.attr('cx'))); var y = Math.min(450, Math.max(0, circle.attr('cy'))); me.socket.emit('moveEnd', {id: id, x: x, y: y}); }; // macro function function P(propName) { return function(d) { return d[propName]; }; } // the key function binds the data entries to the DOM elements using the id var circles = this.scene.selectAll("circle.default").data(this.data, P("id")); circles.enter() // the enter set, a set of new data entries without DOM equivalent .append("circle") .call(d3.behavior.drag() .on('dragstart', dragStart) .on('drag', dragMove) .on('dragend', dragEnd)) .attr("id", P("id")) .attr("class", "default") .attr("r", 1) .attr("cx", P("x")) .attr("cy", P("y")) .style("fill", function(d) { return me.isMobile ? d.color : "url(#gradient_" + d.color + ")"; }) .style("fill-opacity", P("opacity")) .transition().duration(500) .attr("r", P("r")); }, exit: function () { // macro function function P(propName) { return function(d) { return d[propName]; }; } var circles = this.scene.selectAll("circle.default").data(this.data, P("id")); circles.exit() // the exit set, a set of superfluous DOM nodes without data equivalent .attr("class", null) .style("stroke-opacity", 0) .transition() .attr("r", function(d) { return 1.8*d.r; }) .style("fill-opacity", 0.05) .each("end", function () { d3.select(this).remove(); }); }, update: function (dur) { // macro function function P(propName) { return function(d) { return d[propName]; }; } var circles = this.scene.selectAll("circle.default").data(this.data, P("id")); circles // the update set, all DOM nodes with a data binding .transition().duration(dur) .attr("r", P("r")) .attr("cx", P("x")) .attr("cy", P("y")); }, // // the payload called as event from server // setData: function (ts, circles) { this.data = JSON.parse(JSON.stringify(circles)); this.exit(); this.enter(); this.update(800); this.log(ts, this.data.length + " circles updated"); }, addData: function (ts, entry) { this.data.push(JSON.parse(JSON.stringify(entry))); this.enter(); this.log(ts, "circle added, id=" + entry.id); }, toForeground: function (d3Node) { var node = d3Node[0][0]; if (!node) return; node.parentNode.appendChild(node); }, moveStart: function (ts, id) { if (this.dragging) return; var circle = this.scene.select('circle[id="' + id + '"]'); circle.style("stroke", "white"); this.toForeground(circle); }, moveEnd: function (ts, entry) { this.log(ts, "circle moved, id=" + entry.id); for (var i=0; i < this.data.length; i++) { if (this.data[i].id == entry.id) { this.data[i].x = entry.x; this.data[i].y = entry.y; break; } } var circle = this.scene.select('circle[id="' + entry.id + '"]'); circle.style("stroke", null); this.toForeground(circle); this.update(300); }, move: function (ts, entry) { if (this.dragging) return; this.log(ts, "circle moving, id=" + entry.id); var circle = this.scene.select('circle[id="' + entry.id+ '"]'); circle.attr("cx", entry.x).attr("cy", entry.y); }, resize: function (ts, entry) { this.log(ts, "circle resize, id=" + entry.id); for (var i=0; i < this.data.length; i++) { if (this.data[i].id == entry.id) { this.data[i].r = entry.r; break; } } var circle = this.scene.select('circle[id="' + entry.id+ '"]'); circle.attr("r", entry.r); }, removeData: function (ts, id) { for (var i=0; i < this.data.length; i++) { if (this.data[i].id == id) { this.data.splice(i, 1); break; } } this.exit(); this.log(ts, "circle removed, id=" + id); }, format: d3.time.format("%X"), log: function (ts, msg) { var fragment = this.eventCount + " circle events, " + msg + ' @' + this.format(new Date(ts)) + ' +' + ts%1000 + 'ms'; $('#log').html(fragment); }, setupWebsocket: function () { var me = this; // map events to functions var behaviour = { 'update': function (data) { me.eventCount++; me.setData(data.ts, data.circles); }, 'add': function (data) { me.eventCount++; me.addData(data.ts, data.entry); }, 'resize': function (data) { me.eventCount++; me.resize(data.ts, data.entry); }, 'remove': function (data) { me.eventCount++; me.removeData(data.ts, data.id); }, 'moveStart': function (data) { me.eventCount++; me.moveStart(data.ts, data.id); }, 'move': function (data) { me.eventCount++; me.move(data.ts, data.entry); }, 'moveEnd': function (data) { me.eventCount++; me.moveEnd(data.ts, data.entry); } }; // connect with websocket server using namespace: '/circle' this.socket = io.connect('/circle'); _.map(behaviour, function(func, eventName) { me.socket.on(eventName, func); }); } }); |