-
Notifications
You must be signed in to change notification settings - Fork 0
/
almende-vis.html
592 lines (485 loc) · 26.1 KB
/
almende-vis.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
<!--TODO:
1. show/hide on hover. The must be a hover option to
make object visible/hidden. Hidden objects disappear when we
recede the mouse too far away.
2. List of words for search.
-->
<body onLoad="
Summary.innerHTML = 'Loading realtime client API<BR>' ; gapi.load('client,drive-realtime', () => {
Summary.innerHTML += 'Loading Drive_v2 API<br>' ; gapi.client.load('drive', 'v2').then(() =>
controller = new Controller(onFileLoaded))})"
style="background-color:lightgrey;
-webkit-touch-callout: none; /* iOS Safari */ -webkit-user-select: none; /* Chrome/Safari/Opera */ -khtml-user-select: none; /* Konqueror */ -moz-user-select: none; /* Firefox */ -ms-user-select: none; /* Internet Explorer/Edge */ user-select: none; /* Non-prefixed version, currently not supported by any browser */">
<script type="text/javascript" src="https://apis.google.com/js/api.js"></script>
<script type="text/javascript" src="realtime-client-utils.js"></script>
<script type="text/javascript" src="controller.js"></script>
<script src="libs/vis.js"></script>
<!--
<script src="http://almende.github.io/vis/dist/vis.js"></script>
-->
<div id="network_div" style=""></div>
<div style="float: left; width:50; height: 100; font-size: xx-small; white-space:nowrap"><span id="Summary">I know this works in Chrome<br></span>
<ul id="word_list" class="controls"></ul></div>
<table cellspacing="0" cellpadding="0" id="authorizeButton" style="display:none"><tr>
<td align="center" width="300" height="40" bgcolor="#000091" style="-webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; color: #ffffff; display: block;">
<a href="javascript:" style="font-size:16px; font-weight: bold; font-family: Helvetica, Arial, sans-serif; text-decoration: none; line-height:40px; width:100%; display:inline-block"><span style="color: #FFFFFF">You must authorize</span></a>
</td>
</tr> </table>
<table onmouseenter="classVisible('aboutbar', 'block')" onmouseleave="classVisible('aboutbar', 'none')" style="float: right; font-size:small">
<tr id=resetButton style="display:none"><td><a href="javascript:nodes.clear(); edges.clear();reset()" title="Clean up the display. You can achieve the same with F5-page refresh but this button is faster and unloads the server.">Reset</a> </td></tr>
<tr><td><a class="aboutbar" href="javascript:window.open('about.html' + location.hash)">About</a></td></tr>
<tr><td><a class="aboutbar" href="javascript:window.open('options.html' + location.hash)">Options</a></td></tr>
<tr><td><a class="aboutbar" href="http://almende.github.io/vis/examples/network/21_data_manipulation.html">Almende</a></td></tr>
<tr><td><button class="aboutbar" onclick="controller.loader.selectOrCreateNew()">Anothr file</button></td></tr>
<tr><td><button class="aboutbar" onclick="controller.loader.GooglePick()">Ggl picker</button></td></tr>
<script>
function html(parent, document) { var document = document || window.document
return function (type, attributes, text) { var el = document.createElement(type);
if (attributes) for (var a in attributes) el.setAttribute(a, attributes[a])
if (text) el.appendChild(document.createTextNode(text)); parent.appendChild(el); return el
}}
</script>
<tr><td><button class="aboutbar" onclick="
function jsonAMap(map) { return map.items().reduce((seed, [k,v]) => {seed[k] =
(v.type == 'List' ? v.asArray() : (v.type == 'Map' ? jsonAMap(v) : v)); return seed}, new Object())}
var stringified = JSON.stringify(jsonAMap(window.controller.model.getRoot()))
var parsed = JSON.parse(stringified)
var doc = window.open('', '_blank').document ; var inBody = html(doc.body, doc)
var ta = inBody('textarea', {style:'width:100%; height:95vh'}) ; ta.value = stringified
var div = inBody('div'); var inDiv = html(div, doc)
var origin = window.location.href.split('#')[0]; var copies = []
function divView1() { div.innerHTML = ''
inDiv('button', {}, 'Copy into').onclick = function() { div.innerHTML = 'Loading drive API'
newFileName = newFileName.value ; var parsed = JSON.parse(ta.value)
div.innerHTML = 'Creating the file'
createNewFile(newFileName, file => { div.innerHTML = 'Openting the new document for writing'
function modelInitializer(model) { var root = model.getRoot()
for (k in parsed) {var v = parsed[k] ; var kind = (Array.isArray(v) ? 'List' : 'Map')
//console.log(['root set ' , k , kind , v])
root.set(k, (model['create' + kind])(v))
} ; copies.push(file); divView1()
} ; controller.loader.loadFile(file.id, model => setTimeout(() => {
div.innerHTML = 'Importing the data'; modelInitializer(model)}, 0), () => {})
})
} ; var newFileName = inDiv('input', {value: 'new file name'}) ; inDiv('b', {}, ' to create a copy of the file ')
copies.forEach(c => inDiv('a', {href:origin + '#fileId=' + c.id}, c.title))
listFiles(resp => { resp = resp.items
var filtered = resp.filter(file => file.id == rtclient.params.fileId)
.forEach(file => newFileName.value = file.title) ; var knownNames = new Set(resp.map(file => file.title))
for (i = 1; ; i++) {var newName = newFileName.value + '-copy_' + i
if (!knownNames.has(newName)) { newFileName.value = newName; break}}
})
} ; divView1()
">Export</button></td></tr>
<tr><td><a class="aboutbar" id="histButton">Hist trend</a></td></tr>
</table>
<style>.aboutbar{display:none}</style>
<!-- Undo and redo buttons. -->
<table onmouseenter="redoButton.style.display = 'block'" onmouseleave="redoButton.style.display = 'none'" style="float: right">
<tr><td><button id="undoButton" disabled>Undo</button></td></tr>
<tr><td><button id="redoButton" style="display:none" disabled>Redo</button></td></tr>
</table >
<table onmouseenter="classVisible('connbar', 'block')" onmouseleave="classVisible('connbar', 'none')" style="float: right">
<tr><td><button id="connect_button" onclick="connButtonClicked([])" disabled>strong Conn</button></td></tr>
<tr><td><button class="connbar" id="circle_button" onclick="circleButtonClicked([])" disabled>circle Conn</button></td></tr>
<tr><td><button class="connbar" id="breakNodes_button" onclick="breakNodesClicked()" disabled title="Breaks connections between selected nodes">break</button></td></tr>
<tr><td><button class="connbar" id="delete_button" onclick="deleteButtonClicked()" disabled>Del Sel</button></td></tr>
<tr><td><button class="connbar" id="flip_button" onclick="flipButtonClicked()" disabled>Flip Sel</button></td></tr>
</table>
<style>.connbar{display:none}</style>
<table onmouseenter="classVisible('addbar', 'block')" onmouseleave="classVisible('addbar', 'none')" style="float: right">
<tr><td><input id="input1" onkeydown="if (event.keyCode == 13) addnodeButtonClicked()"/></td></tr>
<tr><td><button class="addbar" id="add_button" onclick="addnodeButtonClicked()" style="display:none">add node</button></td></tr>
<tr><td><button class="addbar1" id="rename_button" onclick="renameButtonClicked()" style="display:none">Rename</button></td></tr>
</table>
<table style="float: right">
<tr><td><b id="saving1" style="display:none">Saving... </b></td></tr >
</table>
<script>
NodeList.prototype.forEach = Array.prototype.forEach // enable forEach in NodeList, http://stackoverflow.com/a/27649511/6267925
function classVisible(cls, visibility) { document.querySelectorAll("." + cls).forEach(c => c.style.display = visibility) }
word_list.addEventListener("click", function(e) {
if(e.target && e.target.nodeName == "LI") { ; var text = e.target.textContent
selectNode(text) ; network.focusOnNode(text, {
scale: 1, offset: {x:0,y:0}, animation: {duration: 2500, easingFunction: 'easeInOutQuad'}
}) ; window.scrollTo(0,0) // browser jump. Useful for long lists
}
});
word_list.ondblclick = function(e) { input1.value = e.target.textContent}
function selectNode(id) {
var selected = (shiftPressed) ? network.getSelection().nodes : []
selected.push(id) ; console.log("select node " + id + " caused partial expand"); partialExpand(id, topLocation())
network.selectNodes(selected) // select in graph
onselect(network.getSelection())
}
function getLI(word) {
var list = word_list.querySelectorAll('li');
for (var k in list) { li = list[k]
if (li.textContent == word) return li
}
}
function insertFirst(li) {
if (word_list.firstChild) word_list.insertBefore(li, word_list.firstChild);
else word_list.appendChild(li);
}
function updateListSelection(justSelected) {
justSelected.map(getLI).forEach ( li => {word_list.removeChild(li) ; insertFirst(li)})
}
</script>
<span id="ConnectMode_span" style="display:none; z-index:-1000">connect mode</span>
<style type="text/css">
body {font-family:verdana}
.network-manipulationLabel {display: none}
a, span, table, button, input, .controls { position: relative; left: 0; top: 0; margin: 0; padding: 0;}
#network_div { position: absolute; left: 0; top: 0; margin: 0; padding: 0; width: 100%; height: 100%; }
</style>
<script>
var errorsOccured = false
window.onerror = function(errorMsg, url, lineNumber, colNo, e) {
if (!errorsOccured)
alert("Error " + errorMsg + " in " + url + ", line " + lineNumber + ". Watch the developer console.");
errorsOccured = true
};
var shiftPressed = undefined ;
function installKeyListener() {["keydown", "keyup"].forEach(evt =>
window.addEventListener(evt, function(event) { shiftPressed = event.shiftKey
// Bind to both command (for Mac) and control (for Win/Linux)
if (event.keyCode == 17) {
var down = event.type == 'keydown' ; var newDisplay = down ? 'block' : 'none'
if (ConnectMode_span.style.display != newDisplay) {
ConnectMode_span.style.display = newDisplay
if ((network.getSelection().edges.length == 1)) {
console.log('edit mode ' + network.getSelection().edges[0])
//edit edge mode
if (down) {
ConnectMode_span.editorData = null
network._createEditEdgeToolbar.call(network)
} else {
network._createManipulatorBar.call(network)
recoverEditEdge()
var newEdge = ConnectMode_span.editorData
if (newEdge != null) { controller.compound(function() {
controller.removeEdge(newEdge.id)
controller.connect(newEdge.from, newEdge.to)
})}
}
} else {
// new connection mode
console.log('new conn mode')
network[down ? '_createAddEdgeToolbar' : '_createManipulatorBar']
.call(network)
/*if (network.manipulationDOM[element])
network.manipulationDOM[element].onclick()
else
console.log('element ' + element + " undefined")*/
}
}
} else if (ConnectMode_span.style.display != 'none') {
//console.log('another key pressed!') // need to stop conn mode immediately (it has side effects)
network._createManipulatorBar.call(network)
ConnectMode_span.style.display = 'none'
}
}, true)
)}
var options = {
dataManipulation: {enabled: true, initiallyVisible:false},
onConnect: function (edge, callback) {
console.log('on connect ' + str(edge, true))
controller.connect(edge.from, edge.to)
callback([]); // cancel update. Do it with model update
},
onEditEdge: function (edge, callback) {
callback(ConnectMode_span.editorData = edge); // track changes
},
/*nodes: { // having only text obfuscates its location on the edges
shape: "text",
color: {
border: 'orange',
background: 'white',
}
}*/
};
function control(func) {
controller[func](input1.value)
}
function deleteButtonClicked() {
// fired when user (rather than graph) initiates removal
// Do the same as when graph initiates removal
options.onDelete(network.getSelection() , function() {})
}
//fired when graph (rather than user) initiates removal.
// Promote the command to the model. Actualy graph will be
// pruned on model update event.
options.onDelete = function(deleted, cb) {
controller.compound(function() {
deleted.edges.forEach (edge => controller.removeEdge(edge) )
deleted.nodes.forEach (node => controller.deleteNode(node) )
return cb([]) // cancel delete -- do in on model update
})
}
function onselect(selected) {
var nodes = selected.nodes
console.log("selected.nodes: " + nodes.join(',') + ", network.sel.nodes: " + network.getSelection().nodes.join(','))
delete_button.disabled = nodes.length + selected.edges.length == 0
connect_button.disabled = circle_button.disabled =
breakNodes_button.disabled = (nodes.length < 2)
rename_button.className = (nodes.length == 0) ? 'addbar1' : 'addbar'
rename_button.innerHTML = (nodes.length < 2) ? 'Rename' : "Merge " + nodes.length + " words"
flip_button.disabled = (nodes.length != 2)
// select item in the list
updateListSelection(nodes)
}
function flipButtonClicked() {
var selected = network.getSelection().nodes
var name1 = selected[0] ; var name2 = selected[1]
//nodes.update({id: selected[0], label:validName})
var temp = "flipping_temp 1bf4e67deadad20cc14d"
with (controller) { compound(function() {
mergeRename([name1], temp) ; mergeRename([name2], name1) ; mergeRename([temp], name2)
})}
}
function enlistTheWord(word) {
var li = document.createElement("LI");
li.appendChild(document.createTextNode(word));
insertFirst(li)
}
function expandFirst() {
var fi = word_list.firstChild ; if (fi) {
partialExpand(fi.textContent, {x:0, y:0})
fi.click()
}
}
function topLocation() {
if (!word_list.firstChild) return {x:0, y:0}
var firstNode = network.nodes[word_list.firstChild.textContent]
return firstNode == null ? {x:0, y:0} : firstNode
}
function str(obj, displayValues) { // debug function
if (!obj) return undefined
var result = Object.keys(obj)
if (displayValues) result = result.map(function(item) {return item + " => " + obj[item]})
return result.join(',')
}
function makeProxy(id, location) {
if (nodes.get(id) == null) {
var nn = {id: id, label: id, x: location.x, y: location.y, allowedToMoveX: true, allowedToMoveY: true, title:id}
if (controller.connectionSet(id).size != 1) nn.shape = 'dot'
nodes.add(nn)
}
}
function visEdge(a,b) {return network.edges[edgeId(a, b)]}
/*depth == 0: stop descending and pop up a proxy for any unavailable connection */
function partialExpand(id, location, depth) { depth = depth || parseInt(controller.getConfig('hoverExpandDepth')) + 1
function log(msg) {
console.log(new Array(depth ).join(" ") + msg)
}
// Nodes.get(id) returns the object added by nodes.add(node) whereas network.nodes[id] is related
// graph node. It has no 'shape' or 'title' but contains right current coordinages.
var existent = nodes.get(id) ;
if (existent != null && existent.shape == "dot") { location = network.nodes[id] ;
nodes.remove(id); existent = null}
if (existent == null) {
function join(buddy) { if (!visEdge(id, buddy)) {
visConnect(buddy, id, location) ; // both connections are necessary when
visConnect(id, buddy, location) // establishing connections on expand
}}
var conns = controller.connectionSet(id)
if (depth == 1) {
makeProxy(id, location)
conns.forEach(function (buddy) {var node = nodes.get(buddy); if (node != null) join(buddy)})
} else {
nodes.add({id: id, label:id, x: location.x, y: location.y, allowedToMoveX: true, allowedToMoveY: true})
conns.forEach(function (buddy) { partialExpand(buddy, network.nodes[id], depth-1) ; join(buddy)})
}
}
//updateListSelection([id]) // not effective because all expanded will move to the front of list
}
function visConnect(nodeA, nodeB, location) {
if (validEdgeDir(nodeA, nodeB)) {
if (location) ; else location = topLocation()
makeProxy(nodeA, location) ; makeProxy(nodeB, location)
edges.add({id: edgeId(nodeA, nodeB), from: nodeA, to: nodeB})
}
// this is needed due to bug 623, https://github.com/almende/vis/issues/623
// Basically, edge edit unselects edges but it is reported as
// selected in network.getSelection() and, thus, we enter
// edit edge mode instead of draw new edge on cotrol pres and crush
//network.selectNodes([])
// a better workaround. It unselects edges, leaving nodes selected
if (this.network) network.selectNodes(network.getSelection().nodes)
}
function split(comma_separated) {return comma_separated.length == 0 ? [] : comma_separated.split(controller.separator)}
function addnodeButtonClicked() {
var connectTo = network.getSelection().nodes
var newWords = split(input1.value).map(function(word) {return word.trim()})
controller.compound(function() {
newWords.forEach ( nw => { nw = nw.trim()
if (controller.graph.get(nw) == null) willingToSelect = controller.createNode(willingToSelect = nw, connectTo)
else controller.connectAll(nw, connectTo)
connectTo.push(nw) // connect all new words together to the initially selected ones
})
})
//input1.value = ""
}
function circleButtonClicked(plusAdded) {
var ids = network.getSelection().nodes.concat(plusAdded)
controller.compound(function() {
for (var i = 1 ; i != ids.length ; i++)
controller.connect(ids[i-1], ids[i])
if (ids.length > 2) controller.connect(ids[ids.length-1], ids[0])
})
}
function cartesianForEach(col1, col2, pairfunc) {col1.forEach(i => col2.forEach(j => pairfunc(i,j))) }
function connButtonClicked(plusAdded) {
var ids = network.getSelection().nodes.concat(plusAdded)
controller.compound( () => cartesianForEach(ids, ids, (i,j) => controller.connect(i,j)) )
}
function renameButtonClicked() {
//controller.renameNode(selected[0], willingToSelect = input1.value)
var victims = network.getSelection().nodes
var target = willingToSelect = input1.value.trim()
controller.mergeRename(victims, target)
onselect(network.getSelection())
}
function breakNodesClicked() {
var nodes = network.getSelection().nodes ; var victimEdges = []
cartesianForEach(nodes, nodes, (i,j) => { var eid = edgeId(i,j)
if (edges.get(eid) != null && validEdgeDir(i,j)) victimEdges.push(eid)
}) ; options.onDelete({edges:victimEdges, nodes:[]}, function() {})
}
// can be called due to delete-cancel of when user confirmes the edit
// can be called due to delete-cancel of when user confirmes the edit
// NewEdge.id has wrong from/to after edit. Remove and
// recreate it.
function recoverEditEdge() {
ConnectMode_span.style.display = 'none'
var newEdge = ConnectMode_span.editorData
if (newEdge == null) return // no edit was actually started -- nothing to roll back
edges.remove(newEdge.id)
var originalConnection = (newEdge.id)
visConnect(originalConnection[0], originalConnection[1])
}
// called by controller.js
function onMapValueChanged(evt) {
if (evt.newValue == null) {
Summary.update(-1, -split(evt.oldValue).length) ; console.log("remote event: deleted " + evt.property)
nodes.remove(evt.property)
word_list.removeChild(getLI(evt.property))
if (nodes.length == 0) expandFirst()
}
else if (evt.oldValue == null) {
Summary.update(+1, split(evt.newValue).length) ; console.log("remote event: created " + evt.property)
var selected = topLocation()
nodes.add({id: evt.property, label:evt.property, x: selected.x, y: selected.y, allowedToMoveX: true, allowedToMoveY: true})
enlistTheWord(evt.property)
if (willingToSelect == evt.property) selectNode(willingToSelect)
}
else {
var listWas = split(evt.oldValue) ; var newList = split(evt.newValue) ; var src = evt.property
let added = newList.filter(n => listWas.indexOf(n) == -1) ; let removed = listWas.filter(w => newList.indexOf(w) == -1)
Summary.update(0, added.length - removed.length) ; added.forEach(n => visConnect(src, n)) ; removed.forEach(w => edges.remove(edgeId(src, w)) );
}
}
function validEdgeDir(a, b) { return a < b }
function edgeId(a,b) {
return (validEdgeDir(a,b) ? [a,b] : [b,a]).join(controller.separator)
}
function isPartial() {return controller.getConfig('almende-mode') == 'partial'}
window.onbeforeunload = function (e) {if (saving1.style.display != 'none') return "There are some data unsaved. Are you sure that you want to terminate?"}
function reset() {
nodes = new vis.DataSet();
edges = new vis.DataSet();
network = new vis.Network(network_div, {nodes: nodes, edges: edges}, options);
network.editMode = true // https://github.com/almende/vis/issues/605#issue-55793606
network._createManipulatorBar()
network.on('select', onselect)
network.keycharm.bind("esc", function(evt) {
if (ConnectMode_span.style.display == 'block') recoverEditEdge()})
// make distance eucledian https://github.com/almende/vis/issues/729
network._nodeInActiveArea = function(node) {
function squared(x) { return Math.pow(node[x] - network.areaCenter[x],2)}
return Math.pow(squared('x') + squared('y'), 1/2) < this.constants.clustering.activeAreaBoxSize/2/this.scale
}
}
function onFileLoaded(doc) {
installKeyListener()
document.body.style.backgroundColor = 'white'
doc.addEventListener(gapi.drive.realtime.EventType.DOCUMENT_SAVE_STATE_CHANGED, function(e) {
//document.body.style.backgroundColor = (saving = e.isSaving) ? 'ligthyellow' : 'white'
saving1.style.display = (e.isSaving) ? 'inline' : 'none'
input1.style.color = (e.isSaving) ? 'red' : 'black'
});
controller.graph.addEventListener(gapi.drive.realtime.EventType.VALUE_CHANGED, onMapValueChanged);
undoButton.onclick = function(e) { controller.model.undo(); };
redoButton.onclick = function(e) { controller.model.redo(); };
// Add event handler for UndoRedoStateChanged events.
var onUndoRedoStateChanged = function(e) {
undoButton.disabled = !e.canUndo;
redoButton.disabled = !e.canRedo;
}; document.querySelectorAll("button").forEach(b => b.addEventListener("click", () => input1.focus()))
controller.model.addEventListener(gapi.drive.realtime.EventType.UNDO_REDO_STATE_CHANGED, onUndoRedoStateChanged);
if (location.search.indexOf("mode=") != -1)
controller.setConfig('almende-mode', location.search.replace("?mode=", ""))
options.clustering = controller.getConfig('almende-mode') == 'cluster'
Summary.nodes = Summary.edges = 0 ; let format = x => x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, " ");
Summary.update=function(nodeDiff, edgeDiff) {Summary.nodes += nodeDiff ; Summary.edges += edgeDiff
this.innerHTML = "<a href='https://developers.google.com/google-apps/realtime/size' target='_blank' title='Should not exceed 10 MB'>"
+ format(controller.model.bytesUsed) + " bytes</a> for " + format(Summary.nodes) + " words with " +format(Summary.edges/2) + " transitions"
} // div by 2 cos graph stores edges in both directions whereas we display only one
var knots = controller.graph.keys() ; knots.forEach(n => {enlistTheWord(n) ; Summary.edges += controller.connectionSet(n).size})
Summary.update(knots.length, 0)
if (!isPartial()) knots.forEach ( node => {//cy.startBatch() try {
nodes.add({id: node, label:node})
controller.connectionSet(node).forEach(assoc => visConnect(node, assoc))
}) ; else resetButton.style.display = 'block'
reset()
}
function makeDiv(populate) { let dialog = document.createElement("div");
style(dialog, "position: fixed; left: 0px; top: 0px; width:100%; height:100%; z-index: 1000; background-color:white") // defined in realtime-client
function escFunc(e) {if (e.keyCode == 27) close()} ; window.addEventListener('keydown', escFunc)
function close() {dialog.remove(); window.removeEventListener('keydown', escFunc) ; (destructor || function(){})()}
function textNode(tag) {return text => make(tag, {}, text)}
var make = html(dialog)
var destructor = populate(make, textNode, close) ; document.body.appendChild(dialog)
}
function historicTrends(diff, scale, avgSize) {var [diff, scale] = [diff, scale].map(a => a || false) ; var avgSize = avgSize || 1
function visit(tree1, tree2, f) {return typeof tree1 == "number" ? f(tree1, tree2) : tree1.map((el, i) => visit(el, tree2[i], f))};
var redVis = (collection, seed) => collection.reduce((acc, el) =>
visit(acc, el, (a,b) => a+b), seed);
let data = [...controller.trends.asArray(), [Date.now(), [Summary.nodes, Summary.edges/2]]] ; let labels = [ "Date", "nodes", "edges"]
if (diff) {
let avgIntervalTime = (data.pop()[0] - data[0][0])/data.length // used to display density (histogram) rather than counts per interval
data = data.slice(1).map(([t2, [w,e]],i) => {var [t1,[ww, ee]] = data[i]
let dt = (t2 - t1)/avgIntervalTime// dt should be used if intervars have variable width.
return [t2, [(w - ww)/dt, (e - ee)/dt]]})
}
const addRatio = ratioHandler => data.map(([ms, [w,e]]) => [ms, [w,e, ratioHandler(e/w)]])
data = addRatio(r => Math.abs(r) == Infinity ? NaN : r); labels = [...labels, "e/w"]
if (scale) { let totals = redVis(addRatio(r =>
isNaN(r) || Math.abs(r) == Infinity ? 0 : r).map(([,e])=>e), [0,0,0])
for (seriesIndex of [1,2]) { let s = totals[0]/totals[seriesIndex]
data = data.map(([ms, sample]) => {sample[seriesIndex]*=s; return [ms, sample]})
labels[seriesIndex+1] += "*" + s.toFixed(2)
}
}
data = data.map(([ms, data]) => [new Date(ms), ...data])
makeDiv((make, textNode, close) => {
textNode("b")("Usage: Zoom: click-drag, Pan: shift-click-drag, Restore zoom level: double-click or ");
textNode('button')("Close").onclick=close ; var buttons = [['Diff',diff], ['Scale', scale]]
.map(([title, initVal]) => {textNode("b")(" "+title+":"); var b = make('input', {type:"checkbox"});
b.checked = initVal ; return [b, initVal]})
make('button', {}, 'Export').onclick = () => open('').document.write(JSON.stringify(data))
var timer = setInterval(e => { if (buttons.filter(([b,iv])=> b.checked != iv).length > 0)
{clearTimeout(timer) ; close() ; historicTrends(...buttons.map(([b,]) => b.checked))}}, 2000)
make('div', {id:"div_g", style:"width:100%"}) ; return () => clearTimeout(timer)
})
var script = document.createElement('script'); script.src = 'http://dygraphs.com/dygraph-combined.js';
script.onload = function () {
Dygraph.addEvent(document, "mousewheel", function() { lastClickedGraph = null; });
Dygraph.addEvent(document, "click", function() { lastClickedGraph = null; });
new Dygraph(document.getElementById("div_g"),
...[data, {showRoller: true, labels: labels}]);
}; document.head.appendChild(script);
}
</script>
</body>