-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpanel.htm
678 lines (564 loc) · 19 KB
/
panel.htm
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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Flow Workspace</title>
<link href="/iotstyle.css" rel="stylesheet" type="text/css">
<script src="micro.js"></script>
<script src="microsvg.js"></script>
<script src="panel.js"></script>
<style>
/* body with streched main */
body.sitelayout {
width: 100vw;
height: 100vh;
grid-template-rows: header max-content navbar max-content main 1fr;
}
#panel {
--con-color: #080808;
fill: none;
background-color: silver;
background-image: linear-gradient(to top, rgba(0, 0, 0, .2) 1px, transparent 1px),
linear-gradient(to left, rgba(0, 0, 0, .2) 1px, transparent 1px);
background-size: 12px 12px;
}
#panel #templates {
display: none;
}
#links>line,
#links>path {
stroke: var(--con-color);
stroke-width: 3;
stroke-linecap: round;
marker-end: url(#arrow);
}
#links>marker path {
fill: var(--con-color);
}
.node {
font-size: 12px;
font-family: sans-serif;
fill: #000000;
fill-opacity: 1;
stroke: none;
font-style: normal;
font-weight: normal;
cursor: move;
}
.node rect {
fill: #d4dced;
stroke-width: 0;
}
/* connector pins */
.node circle {
fill: var(--con-color);
stroke-width: 2;
stroke: #d4dced;
r: 6;
&[draggable] {
cursor: crosshair;
}
.node .config {
cursor: pointer;
}
.dragCircle {
fill: none;
stroke: none;
}
#Grid {
fill: #e0e0e0;
stroke: none
}
</style>
</head>
<body class="sitelayout" style="max-width:100%;--layout-gap: 0;--content-back:none">
<header>
<h1>Flow Workspace</h1>
</header>
<div class="navbar">
<a class="button" href="/">Home</a>
<a class="button" href="/board.htm">Board</a>
<a class="button" href="/microide.htm">IDE</a>
<a class="button" href="/log.htm">Log</a>
<span class="gap"></span>
<button id="addButton">+</button>
<button id="unlock">unlock</button>
<button id="auto">auto</button>
<button id="sysButton">sys</button>
</div>
<main style="user-select: none;overflow:scroll">
<svg id="panel">
<defs>
<marker id="arrow" markerWidth="6" markerHeight="6" refX="14" refY="8" orient="auto" viewBox="0 0 16 16">
<path d="M0,0 L0,16 L16,8 z" style="fill:var(--con-color)" />
</marker>
</defs>
<rect height="100%" width="100%"></rect>
<g id="templates">
<g draggable="true" class="node">
<title></title>
<rect width="64" height="64" rx="8"></rect>
<use class="icon" x="16" y="8" width="32" height="32" color="#203050" href="" />
<use class="config" x="48" y="4" width="12" height="12" color="#203050" href="/icons.svg#config" />
<text class="id" x="32" y="56" text-anchor="middle">subtitle</text>
<circle pin="in" cx="3" cy="32"></circle>
<circle pin="out" draggable="true" cx="61" cy="32"></circle>
</g>
</g>
<g id="viewport">
<g id="nodes"></g>
<g id="links"></g>
</g>
</svg>
</main>
<script>
// GRID dimension and size
const PANEL_GRIDSIZE = 72; // px
const NODE_SIZE = 64; // px
const PANEL_WIDTH = 16;
const PANEL_HEIGHT = 12;
const XPref = 64; // x-prefering curve for Edges
const ITERATE = 200;
// https://cs.brown.edu/people/rtamassi/gdhandbook/chapters/force-directed.pdf
class LAYOUT {
XY = "uXY"; // key in localstorage for placements
nodes = {};
edges = [];
// add a new node
addNode(id, t, s) {
var n = this.nodes[id] ?? (this.nodes[id] = {});
n.id = id;
n.icon = uElements.defs[t]?.icon || t;
n.conf = s;
n._x = 0;
n._y = 0;
n._fx = 0;
n._fy = 0;
}
// add a new edge
addEdge(srcPath, tarPath) {
this.edges.push({
src: srcPath,
srcPin: "out",
tar: tarPath,
tarPin: "in"
});
}
// analyse connections, find unconnected Nodes.
analyseChains() {
// reset in/out counters to 0
for (const n of Object.values(this.nodes)) {
n._out = n._in = 0;
}
// remove edge going into the nirvana
this.edges = this.edges.filter(l => {
const fits = (this.nodes[l.src] && this.nodes[l.tar]);
if (!fits) {
console.log("undeliverable action:", l.src, l.tar);
}
return (fits);
});
this.edges.forEach(l => {
this.nodes[l.src]._out++;
this.nodes[l.tar]._in++;
});
}
placeSingleNodes() {
let px = 1;
for (const n of Object.values(this.nodes)) {
if (n._out == 0 && n._in == 0) {
n._x = px++;
n._y = 0;
n._fixed = true;
}
}
} // placeSingleNodes()
loadPlacements() {
// read position from localstorage
const locs = JSON.parse(window.localStorage.getItem(this.XY) || "{}");
let px = 1;
for (const [id, n] of Object.entries(this.nodes)) {
if ((!n._fixed) && (locs[id])) {
n._x = locs[id]._x;
n._y = locs[id]._y;
n._fixed = true;
}
}
} // loadPlacements()
}
const layout = new LAYOUT();
function constrain(val, min, max) {
if (val < min) {
val = min;
} else if (val > max) {
val = max;
}
return (val);
} // constrain()
document.getElementById('unlock').addEventListener("click", evt => {
calcReset(true);
});
document.getElementById('auto').addEventListener("click", evt => {
for (let n = 0; n < ITERATE; n++) moveNodes();
drawNodes();
drawEdges();
});
document.getElementById('addButton').addEventListener("click", async evt => {
// load dialogs on demand.
await loadPlugins();
DialogClass.openModalForm('addElement', {});
});
var params = getHashParams({ sys: false });
window.addEventListener("hashchange", function() {
window.location.reload();
});
document.getElementById('sysButton').addEventListener('click', function(evt) {
params.sys = !toBool(params.sys);
window.location.hash = 'sys=' + params.sys;
});
async function loadPlugins() {
var ret;
if (!document.querySelector('dialog#addElement')) {
// lazy load dialogs.
ret = fetchText("./board-new.htm")
.then(txt => {
document.body.appendChild(document.createRange().createContextualFragment(txt));
});
}
return (ret);
} // loadPlugins()
// Element definitions and config+state of running elements
const uElements = {
defs: {},
impl: [],
env: {},
config: {},
state: {}
};
var panelObj = document.getElementById('panel');
var linksObj = document.getElementById('links');
var viewObj = document.getElementById('viewport');
panelObj.style.width = PANEL_GRIDSIZE * PANEL_WIDTH + "px";
panelObj.style.height = PANEL_GRIDSIZE * PANEL_HEIGHT + "px";
var DragNode; // node element where dragging started.
var DragObj = null; // SVGObject that will be dragged
var DragMode = null;
var DragOffset = null;
// nodes are all existing elements from the device configuration
// extended by _x, _y
var nodes = {};
var edges = [];
/*
HomeDing config data model ->
create nodes = {id, xPos, _y, onXXX, obj }
create edges = {src, srcPin, tar, tarPin, obj}
*/
// create all nodes and edges from the HomeDing config files
function createNodes(conf) {
for (let [eType, elem] of Object.entries(conf)) {
eType = eType.toLowerCase();
for (let [eID, eConf] of Object.entries(elem)) {
eID = eID.toLowerCase();
if (toBool(params.sys) || (!uElements.defs[eType]) || (!toBool(uElements.defs[eType].sys))) {
// show this one.
const id = `${eType}/${eID}`;
// create node
layout.addNode(id, eType, eConf);
// create edges
for (let [key, actions] of Object.entries(eConf)) {
if (key.substring(0, 2) == 'on') {
actions.split(',').forEach(function(a) {
layout.addEdge(id, a.split('?')[0]);
});
}
}
}
}
}
} // createNodes()
// initial placement of all nodes
function placeNodes() {
var py = 1;
layout.analyseChains();
layout.placeSingleNodes();
layout.loadPlacements();
// heuristic initial placement from left to right
for (const n of Object.values(this.nodes)) {
if (!n._fixed) {
// nodes with edges vertically;
if (n._in === 0) {
n._x = 3;
} else if (n._out === 0) {
n._x = 8;
} else {
n._x = 6 + n._in - n._out;
}
n._x = Math.max(n._x, 0);
n._y = py++;
}
} // for
} // placeNodes()
function calcReset(unlock = false) {
for (const n of Object.values(this.nodes)) {
n._fx = 0;
n._fy = 0;
if ((unlock) && (n._out > 0 || n._in > 0)) {
n._fixed = false;
}
}
}
// calc force given by 2 nodes repel each other
function calcRepel(node1, node2) {
const dx = node2._x - node1._x;
const dy = node2._y - node1._y;
const d2 = dx * dx + dy * dy;
const f1 = 0.1;
const fx = f1 * dx / d2;
const fy = f1 * dy / d2;
node1._fx -= fx;
node1._fy -= fy;
node2._fx += fx;
node2._fy += fy;
} // calcRepel()
// calc force given by 2 connected nodes attacting each other
function calcSpring(node1, node2) {
if (node1 && node2) {
const dx = node2._x - node1._x;
const dy = node2._y - node1._y;
const d2 = dx * dx + dy * dy;
const d = Math.sqrt(d2);
const f1 = 2 * Math.log(d / 2);
let fx = f1 * dx / d;
let fy = f1 * dy / d;
// bended springs cause a force as well
fx -= 0.3;
fy = 2 * fy;
node1._fx += fx;
node1._fy += fy;
node2._fx -= fx;
node2._fy -= fy;
}
} // calcSpring
function moveForce(node) {
if (!node._fixed) {
node._x = constrain(node._x + node._fx * 0.1, 0, PANEL_WIDTH - 1);
node._y = constrain(node._y + node._fy * 0.1, 1, PANEL_HEIGHT - 1);
}
}
function moveNodes() {
calcReset();
const prev = [];
for (const node1 of Object.values(nodes)) {
if (node1._y > 0) {
// only use nodes with edges.
for (const node2 of prev) {
calcRepel(node1, node2);
}
prev.push(node1);
}
}
for (const edge of edges) {
calcSpring(nodes[edge.src], nodes[edge.tar]);
}
for (const node of Object.values(nodes)) {
moveForce(node);
}
} // moveNodes()
// create / update svg objects for all nodes
function drawNodes() {
for (var nodeId in nodes) {
var t = nodeId.split('/')[0];
var e = nodes[nodeId];
var ed = uElements.defs[t];
const sData = JSON.stringify(e.conf ?? {}, null, 2);
var obj = e.obj;
if (!obj) {
// create a new svg object for node
var nodesObj = document.getElementById('nodes');
obj = e.obj = document.querySelector('#templates .node').cloneNode(true);
nodesObj.appendChild(obj);
obj.id = nodeId;
// ingoing pin is always visible. disable outgoing pin ?
if (ed) {
if ((!ed.events) || (ed.events.length == 0)) {
const pin = obj.querySelector('[pin="out"]');
if (pin) pin.style.display = "none";
}
}
obj.querySelector('.config').addEventListener('click', function(evt) {
var t = evt.target;
while (t && !t.classList.contains('node')) t = t.parentElement;
const d = t.getAttribute('data');
const id = t.getAttribute('id').split('/');
DialogClass.openModalForm('configElement', { ...JSON.parse(d), type: id[0], id: id[1] });
});
}
// update svg object by node properties
if (e.icon)
obj.querySelector('.icon').setAttribute("href", "/icons.svg#" + e.icon);
obj.querySelector('title').textContent = sData;
obj.setAttribute("data", sData);
obj.querySelector('.id').firstChild.textContent = nodeId;
moveSVGGroup(obj, e._x * PANEL_GRIDSIZE + 4, e._y * PANEL_GRIDSIZE + 4);
} // for
// save pos
const uPos = {};
Object.values(nodes).forEach(n => {
if (n._fixed)
uPos[n.id] = { _x: n._x, _y: n._y };
});
window.localStorage.setItem(layout.XY, JSON.stringify(uPos));
} // drawNodes()
// create / update all svg objects edges to current position of nodes
function drawSingleEdge(obj, aPos, ePos) {
if (!obj) {
obj = linksObj.ownerDocument.createElementNS("http://www.w3.org/2000/svg", 'path');
linksObj.appendChild(obj);
} // if
obj.setAttribute("d", `M ${aPos.x},${aPos.y} C ${aPos.x + XPref},${aPos.y} ${ePos.x - XPref},${ePos.y} ${ePos.x - 12},${ePos.y} L ${ePos.x},${ePos.y}`);
return (obj);
} // drawSingleEdge()
// create / update all svg objects edges to current position of nodes
function drawEdges() {
var aPos, ePos;
for (var n = 0; n < edges.length; n++) {
var f = edges[n];
var sObj = nodes[f.src];
var tObj = nodes[f.tar];
if (sObj && tObj) {
var obj = f.obj;
aPos = _pinPos(sObj, f.srcPin);
ePos = _pinPos(tObj, f.tarPin);
// spline version
if (!obj) {
obj = f.obj = linksObj.ownerDocument.createElementNS("http://www.w3.org/2000/svg", 'path');
linksObj.appendChild(obj);
} // if
obj.setAttribute("d", `M ${aPos.x + 6},${aPos.y} C ${aPos.x + XPref},${aPos.y} ${ePos.x - XPref},${ePos.y} ${ePos.x - 18},${ePos.y} L ${ePos.x - 6},${ePos.y}`);
} // for
}
} // drawEdges()
window.addEventListener('load', async function() {
// get configuration data
var p2 = fetchJSON('/elements.json').then(json => uElements.defs = json);
var p3 = fetchJSON('/env.json').then(json => uElements.env = json);
var p4 = fetchJSON('/config.json').then(json => uElements.config = json);
var p5 = fetchJSON('/api/elements').then(json => uElements.impl = json);
// start when all data is available
Promise.all([p2, p3, p4, p5]).then(function() {
hub.write('env', JSON.stringify(uElements.env));
hub.write('config', JSON.stringify(uElements.config));
createNodes(uElements.env);
createNodes(uElements.config);
nodes = layout.nodes;
edges = layout.edges;
placeNodes();
for (let n = 0; n < ITERATE; n++) moveNodes();
drawNodes();
drawEdges();
loadPlugins();
});
});
// === drag & drop
var _conPos;
var _conObj;
panelObj.addEventListener("mousedown", function(evt) {
if (!DragObj) {
var o = evt.target;
// check for a draggable object.
while (o && o.attributes && (!o.attributes["draggable"]))
o = o.parentNode;
if (o && o.attributes && (o.attributes["draggable"]))
DragObj = o;
}
let obj = DragObj;
while (obj && !obj.classList.contains('node')) obj = obj.parentElement;
DragNode = Object.values(nodes).find(n => (n.obj === obj));
if (DragObj) {
if (DragObj.getAttribute('pin') === 'out') {
DragMode = 'c';
// create draggable circle
DragOffset = getSVGPos(panelObj, evt);
DragObj = createSVGNode(panelObj, 'circle', {
class: 'dragCircle',
cx: DragOffset.x,
cy: DragOffset.y,
r: 6
});
_conPos = { x: DragOffset.x, y: DragOffset.y };
_conObj = drawSingleEdge(undefined, _conPos, _conPos);
} else {
DragMode = 'n';
// calculate Drag Offset = mouse position - drag object position
DragOffset = getSVGPos(panelObj, evt);
var cc = DragObj.getCTM();
DragOffset.x -= cc.e;
DragOffset.y -= cc.f;
}
}
}); // mouseDown
panelObj.addEventListener("mousemove", function(evt) {
if (DragObj) {
var DragPos = getSVGPos(panelObj, evt);
moveSVGGroup(DragObj, DragPos.x - DragOffset.x, DragPos.y - DragOffset.y);
if (DragMode === 'n') {
drawEdges();
}
else {
drawSingleEdge(_conObj, _conPos, DragPos);
}
} // if
}); // mousemove
panelObj.addEventListener("mouseup", function(evt) {
if (DragObj) {
var DragPos = getSVGPos(panelObj, evt);
if (DragMode === 'c') {
// connector drop
DragObj.remove();
_conObj.remove();
// find target node
const x = DragPos.x / PANEL_GRIDSIZE;
const y = DragPos.y / PANEL_GRIDSIZE;
const node = Object.values(nodes).find(n =>
(n._x <= x) && (n._x + 1 > x) && (n._y <= y) && (n._y + 1 > y)
);
// Start the action connect dialog
if ((node) && (node !== DragNode)) {
DialogClass.openModalForm('action',
{ srcId: DragNode.id, tarId: node.id },
d => {
if ((d.srcEvent) && (d.target) && (d.action) && (d.value)) {
DragNode.conf[d.srcEvent] = `${d.target}?${d.action}=${d.value}`;
changeConfig(DragNode.id, DragNode.conf);
}
});
}
} else if (DragMode === 'n') {
// node drop
const node = Object.values(nodes).find(n => (n.obj === DragObj));
node._x = Math.floor(6 * (DragPos.x - DragOffset.x) / PANEL_GRIDSIZE) / 6;
node._y = Math.floor(6 * (DragPos.y - DragOffset.y) / PANEL_GRIDSIZE) / 6;
node._fixed = true;
}
// for (var n in nodes) {
// if (nodes[n].obj === DragObj) {
// nodes[n]._x = Math.floor(6 * (DragPos.x - DragOffset.x) / PANEL_GRIDSIZE) / 6;
// nodes[n]._y = Math.floor(6 * (DragPos.y - DragOffset.y) / PANEL_GRIDSIZE) / 6;
// nodes[n]._fixed = true;
// break;
// }
// } // for
drawNodes();
drawEdges();
} // if
DragObj = null;
}); // mouseup
if (window !== window.top) {
// disable header and navbar in portal mode.
document.querySelector('.u-header').style.display = 'none';
document.querySelector('.u-navbar').style.display = 'none';
} // if
</script>
</body>
</html>