-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
574 lines (533 loc) · 20.9 KB
/
index.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
<html>
<head>
<title>Rack</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<link href="//unpkg.com/sanitize.css" rel="stylesheet" />
<link href="//fonts.googleapis.com/css?family=Raleway" rel="stylesheet" />
<link href="//use.fontawesome.com/releases/v5.0.9/css/solid.css" rel="stylesheet" />
<style type="text/css">
body { background-color: #f2f2f2; overflow: hidden; }
body, input, textarea, button, select { font-family: 'Raleway', sans-serif; }
body > div { position: absolute; }
.graph { top: 50px; right: 0; bottom: 0; left: 0; overflow: hidden; }
.topbar { top: 0; right: 0; left: 0; height: 50px; background-color: #fff; box-shadow: 0px 5px 8px -4px #ccc; }
.properties { top: 0; right: -30px; bottom: 0; width: 330px; padding: 70px 0 0 40px; overflow: auto; background-color: #fff; box-shadow: -5px 0px 8px -4px #ccc; transition: right .4s cubic-bezier(0.175, 0.885, 0.320, 1.275); }
.properties.hidden { right: -335px; }
.topbar { display: none; } .properties { padding-top: 40px; } /* Disabled the top bar for now because it isn't in use anyway */
.properties > * { display: block; position: relative; padding: 0; margin: 0; }
.properties > .soul { width: 80%; padding-left: 3px; margin-bottom: 10px; font-size: 1.3em; }
.properties button.delete { position: absolute; right: 45px; bottom: 10px; width: 1em; height: 2em; font-size: 1em; border: none; background: none; opacity: .5; cursor: pointer; text-indent: -999999px; overflow: hidden; transition: .2s opacity; }
.properties button.delete:hover { opacity: 1; }
.properties button.delete:before { display: block; position: absolute; content: "\f2ed"; font-family: 'Font Awesome 5 Free'; font-weight: 900; text-indent: 0; }
.properties ul { list-style: none; }
.properties li > * { display: block; position: relative; float: left; }
.properties input { width: calc((300px - (40px * 2)) / 2); padding: 3px; border: 1px solid #fff; }
.properties input:focus, .properties input:hover { border-color: #666; }
.properties input:not(:focus) { cursor: pointer; }
.properties input[readonly] { border-color: #fff; cursor: default; }
.properties a.link-to-node { text-decoration: none; color: #000; }
.properties input[name="key"]:placeholder-shown ~ a.link-to-node { display: none; }
</style>
<script src="//cdn.jsdelivr.net/npm/gun/gun.js"></script>
<script src="//unpkg.com/force-graph"></script>
<script>
// Create a hack to get all existing items from localStorage:
Gun.getAll = function()
{
// Mostly copied over from localStorage code
try{store = Gun.window.localStorage}catch(e){};
if(!store)
{
store = {setItem: function(k,v){this[k]=v}, removeItem: function(k){delete this[k]}, getItem: function(k){return this[k]}};
}
let prefix = 'gun/';
let gap = Gun.obj.ify(store.getItem('gap/' + prefix)) || {};
let disk = Gun.obj.ify(store.getItem(prefix));
return disk;
};
</script>
<script>
document.addEventListener('DOMContentLoaded', function(event)
{
// Initialize objects:
const forceGraph = ForceGraph()(document.getElementsByClassName('graph')[0]);
window.gunDB = Gun({ localStorage: true }); // Currently attached to window, to easily access from browser console
var state = 'default';
var graphData = {
nodes: [],
links: []
};
let highlightNodes = [],
highlightNode = null,
openedNode = null,
highlightLink = null;
var gunKeys = [],
gunSouls = [],
gunRefs = { exist: {}, setup: {} };
const attributesListItemHTML = document.createElement('li');
let attributesListItemChildrenHTML = [document.createElement('input'), document.createElement('input')];
attributesListItemChildrenHTML[0].type = attributesListItemChildrenHTML[1].type = 'input';
attributesListItemChildrenHTML[0].placeholder = attributesListItemChildrenHTML[0].name = 'key';
attributesListItemChildrenHTML[1].placeholder = attributesListItemChildrenHTML[1].name = 'value';
attributesListItemHTML.appendChild(attributesListItemChildrenHTML[0]);
attributesListItemHTML.appendChild(attributesListItemChildrenHTML[1]);
let attributesListItemNodeLink = document.createElement('a');
attributesListItemNodeLink.innerHTML = '◇';
attributesListItemNodeLink.href = '#';
attributesListItemNodeLink.className = 'link-to-node';
attributesListItemHTML.appendChild(attributesListItemNodeLink);
let linkFromNode = '',
linkAttribute = '';
let newNodeButtonAt = -1,
newNodeAt = -1;
// Configure the ForceGraph:
forceGraph.d3Force('link').distance(link => 50);
forceGraph
.nodeId('#')
.nodeLabel('#')
.nodeRelSize(19)
.linkSource('source')
.linkTarget('target')
.linkDirectionalParticles(1)
.onLinkHover(link =>
{
highlightLink = link;
highlightNodes = link ? [link.source, link.target] : [];
})
.linkCanvasObjectMode(() => 'after')
.linkCanvasObject((link, ctx, globalScale) =>
{
if(link == highlightLink)
{
const start = link.source;
const end = link.target;
// calculate label positioning
const textPos = Object.assign(...['x', 'y'].map(c => (
{
[c]: link.source[c] + (link.target[c] - link.source[c]) / 2 // calc middle point
})));
ctx.font = '10pt Raleway';
// draw text label
ctx.save();
ctx.translate(textPos.x, textPos.y);
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = '#666666';
ctx.fillText(link.label, 0, 0);
ctx.restore();
}
})
.nodeCanvasObject((node, ctx, globalScale) =>
{
if(node == graphData.nodes[newNodeButtonAt])
{
let circleSize = 1;
ctx.beginPath();
ctx.arc(node.fx, node.fy, 12 * circleSize, 0, 2 * Math.PI, false);
ctx.fillStyle = 'rgba(0, 186, 197, 1)';
ctx.fill();
ctx.beginPath();
ctx.arc(node.fx, node.fy, 10 * circleSize, 0, 2 * Math.PI, false);
ctx.fillStyle = 'rgba(0, 102, 107, 1)';
ctx.fill();
ctx.fillStyle = 'rgba(0, 186, 197, 1)';
ctx.font = '900 9pt "Font Awesome 5 Free"';
ctx.fillText('\uF055', node.x, node.y);
}
else if(node == graphData.nodes[newNodeAt])
{
ctx.fillStyle = 'rgba(0, 102, 107, 1)';
ctx.font = '900 12pt "Font Awesome 5 Free"';
ctx.fillText('\uF477', node.x, node.y);
}
else
{
ctx.font = '10pt Raleway';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = 'rgba(0, 102, 107, 1)';
if(highlightNodes.indexOf(node) >= 0 || highlightNode == node || openedNode == node)
{
ctx.fillStyle = 'rgba(0, 186, 197, 1)';
}
ctx.fillText(node.label, node.x, node.y);
}
})
.onNodeHover(node =>
{
document.getElementsByClassName('graph')[0].style.cursor = node ? 'pointer' : null;
highlightNode = node;
})
.onNodeClick(node =>
{
if(newNodeButtonAt >= 0)
{
if(node == graphData.nodes[newNodeButtonAt])
{
newNodeAt = newNodeButtonAt;
newNodeButtonAt = -1;
highlightNode = node;
let newSoul = Gun.state.lex() + Gun.text.random(7);
let soulElement = document.querySelector('.properties > .soul');
soulElement.removeAttribute('readonly');
soulElement.setAttribute('value', newSoul);
soulElement.value = newSoul;
soulElement.focus();
soulElement.select();
}
}
if(state == 'link')
{
// Remove potential existing link from graphData:
let existingLinkAt = -1,
listItem = document.querySelector('.properties li[data-soul="' + linkFromNode + '"][data-attr="' + linkAttribute + '"]');
existingLinkAt = graphData.links.findIndex(link => (link.source['#'] == linkFromNode && link.label == linkAttribute));
if(existingLinkAt >= 0)
{
graphData.links.splice(existingLinkAt, 1);
}
// Create new link in gunDB:
gunDB.get(linkFromNode).get(linkAttribute).put(gunDB.get(node['#']));
// Set value in value:
listItem.querySelector('input[name="value"]').value = node['#'];
// Update link button icon:
listItem.querySelector('.link-to-node').innerHTML = '⎆';
if(!listItem.classList.contains('ref'))
{
listItem.classList.add('ref');
}
state = 'default';
}
else if(node == openedNode)
{
openedNode = null;
}
else if(newNodeAt >= 0)
{
openedNode = node;
document.querySelector('.properties ul').innerHTML = '';
let newListItem = attributesListItemHTML.cloneNode(true);
newListItem.dataset.soul = node['#'];
newListItem.querySelector('input[name="value"]').setAttribute('readonly', true);
document.querySelector('.properties ul').appendChild(newListItem);
}
else
{
openedNode = node;
document.querySelector('.properties > .soul').setAttribute('value', node['#']);
document.querySelector('.properties > .soul').value = node['#'];
document.querySelector('.properties ul').innerHTML = '';
gunDB.get(node['#']).once(function(data)
{
Object.keys(data).forEach(function(attrKey)
{
if(data[attrKey] !== null && attrKey != '_')
{
let newListItem = attributesListItemHTML.cloneNode(true);
newListItem.dataset.soul = node['#'];
newListItem.dataset.attr = attrKey;
newListItem.querySelector('input[name="key"]').setAttribute('value', attrKey);
if(typeof data[attrKey] !== 'object')
{
newListItem.querySelector('input[name="value"]').setAttribute('value', data[attrKey]);
}
else
{
newListItem.querySelector('input[name="value"]').setAttribute('value', data[attrKey]['#']);
newListItem.classList.add('ref');
newListItem.querySelector('.link-to-node').href = '#' + data[attrKey]['#'];
newListItem.querySelector('.link-to-node').innerHTML = '⎆';
}
document.querySelector('.properties ul').appendChild(newListItem);
}
});
let newListItem = attributesListItemHTML.cloneNode(true);
newListItem.dataset.soul = node['#'];
newListItem.querySelector('input[name="value"]').setAttribute('readonly', true);
document.querySelector('.properties ul').appendChild(newListItem);
});
}
// Update the forceGraph:
forceGraph.graphData(graphData);
document.querySelector('.properties').classList.remove('hidden');
})
.onBackgroundClick((event) =>
{
openedNode = null;
document.querySelector('.properties').classList.add('hidden');
let clickPosition = forceGraph.screen2GraphCoords(event.clientX - event.target.getBoundingClientRect().left, event.clientY - event.target.getBoundingClientRect().top);
if(newNodeButtonAt >= 0)
{
graphData.nodes[newNodeButtonAt].fx = clickPosition.x;
graphData.nodes[newNodeButtonAt].fy = clickPosition.y;
}
else
{
newNodeButtonAt = graphData.nodes.push({ '#': '', 'label': '', 'fx': clickPosition.x, 'fy': clickPosition.y }) - 1;
}
forceGraph.graphData(graphData);
});
document.getElementsByClassName('properties')[0].addEventListener('focusin', (event) =>
{
if(event.target.parentElement.classList.contains('ref'))
{
event.target.parentElement.dataset.ref = event.target.value;
event.target.value = '';
}
});
document.getElementsByClassName('properties')[0].addEventListener('focusout', (event) =>
{
if(event.target.name == 'key') // if input is for a `key`
{
if(!('attr' in event.target.parentElement.dataset))
{
if(event.target.value.length > 0)
{
gunDB.get(event.target.parentElement.dataset.soul).get(event.target.value).put('');
event.target.parentElement.dataset.attr = event.target.value;
event.target.parentElement.querySelector('input[name="value"]').removeAttribute('readonly');
// Add new line to list of properties:
let newListItem = attributesListItemHTML.cloneNode(true);
newListItem.dataset.soul = event.target.parentElement.dataset.soul;
newListItem.querySelector('input[name="value"]').setAttribute('readonly', true);
document.querySelector('.properties ul').appendChild(newListItem);
}
}
else if(event.target.value == event.target.parentElement.dataset.attr) // if new value is the same as the old value...
{
// Nothing changed, so do nothing ;)
}
else if(event.target.value.length > 0)
{
gunDB.get(event.target.parentElement.dataset.soul).get(event.target.value).put(event.target.parentElement.querySelector('input[name="value"]').value);
gunDB.get(event.target.parentElement.dataset.soul).get(event.target.parentElement.dataset.attr).put(null);
event.target.parentElement.dataset.attr = event.target.value;
}
else // if key is empty, remove attribute
{
gunDB.get(event.target.parentElement.dataset.soul).get(event.target.parentElement.dataset.attr).put(null);
// Remove line from .properties:
event.target.parentElement.parentNode.removeChild(event.target.parentElement);
}
}
else if(event.target.name == 'value') // if input is for a `value`
{
let writeValue = true;
if('ref' in event.target.parentElement.dataset)
{
if(event.target.value.length <= 0)
{
event.target.value = event.target.parentElement.dataset.ref;
writeValue = false;
}
delete event.target.parentElement.dataset.ref;
// Update links in graphData:
let existingLinkAt = -1;
existingLinkAt = graphData.links.findIndex(link => (link.source['#'] == event.target.parentElement.dataset.soul && link.label == event.target.parentElement.dataset.attr));
if(existingLinkAt >= 0)
{
graphData.links.splice(existingLinkAt, 1); // Link is removed from graph links array here, but graph is update when node change is triggered in GUN
}
// Update icon:
event.target.parentElement.querySelector('.link-to-node').innerHTML = '◇';
}
if(writeValue)
{
gunDB.get(event.target.parentElement.dataset.soul).get(event.target.parentElement.dataset.attr).put(event.target.value);
}
}
else if(event.target.name == 'soul')
{
event.target.setAttribute('readonly', true);
event.target.blur();
//event.target.deselect();
if(event.target.value.length > 0)
{
// TODO: Check for collision with already existing node what accidental same name?
gunDB.get(event.target.value).put({ 'null': null });
document.querySelector('.properties li').dataset.soul = event.target.value;
}
}
});
document.getElementsByClassName('properties')[0].addEventListener('keyup', (event) =>
{
//console.log(event.target.name);
});
document.getElementsByClassName('properties')[0].addEventListener('click', (event) =>
{
if(event.target.classList.contains('link-to-node'))
{
event.preventDefault();
state = 'link';
linkFromNode = event.target.parentElement.dataset.soul;
linkAttribute = event.target.parentElement.dataset.attr;
}
else if(event.target.classList.contains('delete'))
{
// Tombstone node in gunDB:
let nodeSoul = event.target.parentElement.querySelector('ul li').dataset.soul;
gunDB.get(nodeSoul).once(function(data)
{
Object.keys(data).forEach(function(attrKey)
{
gunDB.get(nodeSoul).get(attrKey).put(null);
});
gunDB.get(nodeSoul).get('VOID').put(1);
});
// Close properties element:
document.querySelector('.properties').classList.add('hidden');
}
});
// Prepare listener function:
function onNodeChange(data, nodeKey)
{
let i = -1;
if(newNodeAt >= 0)
{
i = newNodeAt;
newNodeAt = -1;
graphData.nodes[i]['#'] = nodeKey;
graphData.nodes[i].label = nodeKey.substring(0, 5) + (nodeKey.length > 5 ? '\u2026' : '');
graphData.nodes[i].x = graphData.nodes[i].fx;
graphData.nodes[i].y = graphData.nodes[i].fy;
graphData.nodes[i].fx = graphData.nodes[i].fy = null;
}
else
{
i = graphData.nodes.findIndex((node) => node['#'] == nodeKey);
}
if(i < 0 && !data['VOID']) // Node not yet added to graphData
{
i = graphData.nodes.push({ '#': nodeKey, 'label': nodeKey.substring(0, 5) + (nodeKey.length > 5 ? '\u2026' : '') }) - 1;
}
else if(i >= 0 && data['VOID']) // Node in graphData, but now tombstoned
{
// Remove node from graphData:
graphData.nodes.splice(i, 1);
// Remove links from/to node from graphData:
for(let j=graphData.links.length-1; j>=0; j--)
{
if(graphData.links[j].source['#'] == nodeKey || graphData.links[j].target['#'] == nodeKey)
{
console.log('Removing link ' + graphData.links[j].label);
graphData.links.splice(j, 1);
}
}
}
if(data['VOID'])
{
return;
}
// TODO: Check if newNode shizzle is >-1, then use to set position and currently opened node...
// Go over all attributes:
Object.keys(data).forEach(function(attrKey)
{
// Add link if target node exists:
if(data[attrKey] !== null && typeof data[attrKey] === 'object')
{
if(data[attrKey]['#'] && data[attrKey]['#'] != nodeKey)
{
if(gunRefs.exist[nodeKey])
{
if(gunRefs.exist[nodeKey][data[attrKey]['#']])
{
return;
}
}
if(gunSouls.indexOf(data[attrKey]['#']) >= 0)
{
graphData.links.push({ 'source': nodeKey, 'target': data[attrKey]['#'], label: attrKey });
if(!gunRefs.exist[nodeKey])
{
gunRefs.exist[nodeKey] = {};
}
gunRefs.exist[nodeKey][data[attrKey]['#']] = { label: attrKey };
}
else
{
// If target nodes does not exist, add it to this array to handle later on:
if(!gunRefs.setup[data[attrKey]['#']])
{
gunRefs.setup[data[attrKey]['#']] = {};
}
gunRefs.setup[data[attrKey]['#']][nodeKey] = { label: attrKey };
}
}
}
});
// Go over all links stashed in the gunRefs.setup to add them now that all nodes are added:
if(gunRefs.setup[nodeKey])
{
let sourceNodes = Object.keys(gunRefs.setup[nodeKey]);
while(sourceNodes.length > 0) // Assume all nodes in the array still exist
{
let sourceNode = gunRefs.setup[nodeKey][sourceNodes[0]]; // Currently handling this node...
if(gunSouls.indexOf(sourceNodes[0]) >= 0)
{
graphData.links.push({ 'source': sourceNodes[0], 'target': nodeKey, label: sourceNode.label });
if(!gunRefs.exist[sourceNode])
{
gunRefs.exist[sourceNode] = {};
}
gunRefs.exist[sourceNode][sourceNodes[0]] = { label: sourceNode.label };
}
delete gunRefs.setup[nodeKey][sourceNodes[0]];
sourceNodes.splice(0, 1);
}
delete gunRefs.setup[nodeKey];
}
forceGraph.graphData(graphData);
}
// Walk through all nodes found in graph:
function processGraph(graph)
{
graph = graph || gunDB._.graph;
gunKeys = Object.keys(graph);
gunKeys.forEach(function(nodeKey)
{
// Keep track of already processed nodes/souls:
if(gunSouls.indexOf(graph[nodeKey]['_']['#']) < 0 && !graph[nodeKey]['VOID']) // May be a bit hacky; to check for tombstoned nodes already...
{
// Attach listener to node:
gunDB.get(nodeKey).on(onNodeChange);
gunSouls.push(graph[nodeKey]['_']['#']);
}
});
}
// Use our hack to get existing nodes from localStorage:
processGraph(Gun.getAll());
// Another hack?: register listener for any new node:
gunDB._.root.on('put', function(at)
{
Object.keys(at.put).forEach(function(putKey)
{
if(gunSouls.indexOf(putKey) < 0)
{
gunDB.get(putKey).on(onNodeChange);
gunSouls.push(putKey);
}
});
});
let checkForChanges = setInterval(function()
{
let currentGunKeys = Object.keys(gunDB._.graph);
if(gunKeys.join(',') != currentGunKeys.join(','))
{
processGraph();
gunKeys = currentGunKeys;
}
}, 5000);
});
</script>
</head>
<body>
<div class="graph"></div>
<div class="properties hidden">
<button class="delete">Remove</button>
<input type="text" name="soul" value="" class="soul" readonly />
<ul></ul>
</div>
<div class="topbar"></div>
</body>
</html>