-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathsimple.js
More file actions
2621 lines (2513 loc) · 81.8 KB
/
simple.js
File metadata and controls
2621 lines (2513 loc) · 81.8 KB
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
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const graphModule = (function() {
const showFullTree = true;
const acolors = [ "#28a745", "#72b741", "#b0c13f", "#e6be3d", "#ffc107",
"#fba145", "#f37d4f", "#e65b53", "#d93f4e", "#dc3545"];
const lcolors = {};
let raw;
let treeData;
let selector = '#graph';
function setSelector(newSelector) {
selector = newSelector;
}
function create_raw(dt) {
const kmap = {};
Object.entries(dt.decision_points).forEach(([k, v]) => {
kmap[k] = v.name;
});
function find_value(k, dp) {
let dpm = dp.values.find(dpv => dpv.key == k);
if(dpm)
return dpm.name;
}
let thash = {};
let dps = Object.keys(dt.decision_points);
let yraw = dps.map(x => []);
let zraw = [];
const final_k = dt.outcome;
const dpo = dt.decision_points[final_k];
const ocolors = arrayReduce(acolors,dpo.values.length);
dpo.values.forEach(function(dpv,i) {
lcolors[dpv.name] = ocolors[i];
});
dt.decision_points[final_k].values.forEacj
const final_keyword = dt.decision_points[final_k].name;
const mapping = dt.mapping;
let id = 1;
for(let i=0; i <dt.mapping.length; i++) {
const lhs = find_value(dt.mapping[i][final_k], dt.decision_points[final_k]);
let tname = lhs +":"+
dps.map(t => find_value(dt.mapping[i][t],dt.decision_points[t]))
.slice(0,-1).join(":");
for( let j=0; j< dps.length-1; j++) {
const tparent = dt.decision_points[dps[dps.length-2-j]].name + ":" +
dps.slice(0,dps.length-2-j).map(q =>
find_value(dt.mapping[i][q],dt.decision_points[q])).join(":");
if(!(tname in thash))
var yt = {name:tname.replace(/\:+$/,''),
id:id++,
parent:tparent.replace(/\:+$/,''),
props:"{}",children:[]}
else
continue
thash[yt.name] = 1;
tname = tparent;
yraw[j].push(yt);
}
}
for(var j=yraw.length; j> -1; j--) {
if(yraw.length > 0)
zraw = zraw.concat(yraw[j])
}
zraw[0] = {name:dt.decision_points[dps[0]].name,id:id+254,children:[],parent:null,props:"{}"}
return zraw;
}
function grapharray_open(marray){
var map = {};
for(var i = 0; i < marray.length; i++){
var obj = marray[i];
obj.children= [];
map[obj.name] = obj;
var parent = obj.parent || '-';
if(!map[parent]){
map[parent] = {
children: []
};
}
map[parent].children.push(obj);
}
return map['-'].children;
}
function draw_graph() {
var margin = {top: 20, right: 120, bottom: 20, left: 120},
width = 1060 - margin.right - margin.left,
height = 800 - margin.top - margin.bottom
if(showFullTree) {
var add_offset = 0
if(raw.length > 60)
add_offset = (raw.length - 60)*10
height = Math.max(1300, raw.length * 20) - margin.top - margin.bottom + add_offset
}
duration = 750
tree = d3.layout.tree()
.size([height, width]);
diagonal = d3.svg.diagonal()
.projection(function(d) { return [d.y, d.x]; });
var default_translate = "translate(" + margin.left + "," + margin.top + ")"
var svg_width = width + margin.right + margin.left
var svg_height = height + margin.top + margin.bottom
if(window.innerWidth <= 1000) {
default_translate = "translate(10,0) scale(0.75)"
if(window.innerWidth <= 750)
default_translate = "translate(30,0) scale(0.42)"
}
let zdiv = $('<div>').css({position: "absolute"});
let zinp = $('<input>').attr({type: 'range',
min: '0',
max: '100',
value: '100',
accentColor: 'lightskyblue',
orient: 'vertical',
alt: 'Zoom Graph',
title: 'Zoom Graph'});
zinp[0].onclick = function() {
const zf = this.value/this.max;
const fh = parseInt($('svg.mgraph').attr("height"));
const fw = parseInt($('svg.mgraph').attr("width"));
const vbox = "0 0 "+String(parseInt(fw/zf)) + " " + String(parseInt(fh/zf))
$('svg.mgraph').attr('viewBox',vbox);
}
$(selector).html('').append(zdiv.append(zinp));
svg = d3.select(selector).append("svg")
.attr("xmlns","http://www.w3.org/2000/svg")
.attr("preserveAspectRatio","none")
.attr("class","mgraph")
.attr("width", svg_width)
.attr("height", svg_height)
.append("g")
.attr("transform", default_translate)
.attr("id","pgroup");
root = treeData[0];
root.x0 = height / 2;
root.y0 = 0;
update(root)
d3.select(self.frameElement).style("height", "700px");
}
function update(source) {
var i = 0
var nodes = tree.nodes(root).reverse()
var links = tree.links(nodes)
nodes.forEach(function(d) { d.y = d.depth * 200;})
var node = svg.selectAll("g.node")
.data(nodes, function(d) { return d.id || (d.id = ++i); });
var nodeEnter = node.enter().append("g")
.attr("class", "node bof")
.attr("transform", function(d) {
return "translate(" + source.y0 + "," + source.x0 + ")";
})
.attr("class", function(d) {
var finale = "";
if(!('children' in d))
finale = " finale";
if('depth' in d)
return "node depth-"+String(d.depth)+finale;
return "node depth-none";})
.on("click", doclick)
.on("contextmenu",dorightclick)
.on("mouseover",showdiv)
.on("mouseout",hidediv);
nodeEnter.append("circle")
.attr("r", 1e-6)
.attr("class",function(d, i) {
if(!('children' in d))
return "junction gvisible finale ";
return "junction gvisible"
})
.style("fill", function(d, i) {
if(d._children) return "lightsteelblue"
if(!('children' in d)) {
/* Last node no children */
var dname = d.name.split(":").shift();
if(dname in lcolors)
return undefined;
}
return undefined;
} );
var font = "20px"
if(showFullTree)
font = "18px"
nodeEnter.append("text")
.attr("x",function(d) { return check_children(d,"-55","+20") })
.attr("y",function(d) { return check_children(d,"-37","0") })
.attr("dy", ".35em")
.attr("class",function(d) {
var fclass = d.name.split(":").shift().toLowerCase();
if(!('children' in d))
return "gvisible prechk-"+fclass+" finale";
return "gvisible prechk-"+fclass;})
.text(function(d) { return d.name.split(":")[0]; })
.style("font-size",font)
.style("fill", function(d) {
var t = d.name.split(":").shift();
var x;
if(t in lcolors)
x = lcolors[t];
return x;
})
/* hidden circle */
nodeEnter.append("circle")
.attr("r","10")
.attr("class","ghidden d-none")
.style("fill","steelblue");
var nodeUpdate = node.transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; });
nodeUpdate.select("circle")
.attr("r", 10)
.attr("sid",function(d) { return d.id;})
.attr("nameid",function(d) { if(!d) return "1";
if(d.name) return d.name.split(":").pop();
})
.style("fill", function(d) {
if(d._children) return "lightsteelblue"
if(!('children' in d)) {
var dname = d.name.split(":").shift()
if(dname in lcolors)
return lcolors[dname];
}
return undefined;
})
.style("stroke",function(d) {
if(!('children' in d)) {
var dname = d.name.split(":").shift()
if(dname in lcolors)
return undefined;
}
return "steelblue";
})
nodeUpdate.select("text")
.style("fill-opacity", 1);
var nodeExit = node.exit().transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; })
.remove();
nodeExit.select("circle")
.attr("r", 1e-6);
nodeExit.select("text")
.style("fill-opacity", 1e-6);
var link = svg.selectAll("path.link")
.data(links, function(d) { if(d.target) return d.target.id; })
link.enter().insert("path","g")
.style("fill","none").style("stroke", "#ccc").attr("class","link")
.attr("id", function(d) { return 'l'+Math.random().toString(36).substr(3); })
.attr("kdata", function(d) { return d.source.name.split(":").shift(); })
.attr("ldata", function(d) { return d.target.name.split(":").pop(); })
.attr("ldeep", function (d) { return d.target.name.split(":").length })
.attr("csid",function(d) { return d.target.id;})
.attr("d", function(d) {
var o = {x: source.x0, y: source.y0};
return diagonal({source: o, target: o});
})
link.transition()
.duration(duration)
.attr("d", diagonal);
link.exit().transition()
.duration(duration)
.attr("d", function(d) {
var o = {x: source.x, y: source.y};
return diagonal({source: o, target: o});
})
.remove();
nodes.forEach(function(d) {
d.x0 = d.x;
d.y0 = d.y;
});
if(showFullTree === false) {
var d = source;
if(('depth' in d) && (!isNaN(parseInt(d.depth)))) {
$('g.depth-'+String(d.depth)+' .ghidden').addClass('d-none');
$('g.depth-'+String(d.depth)+' .gvisible').show();
$('g.depth-'+String(d.depth)).removeClass('opthide');
var idepth = String(parseInt(d.depth) + 1)
if($('g.depth-'+idepth).length > 0) {
$('g.depth-'+idepth+' .ghidden').removeClass('d-none');
$('g.depth-'+idepth+' .gvisible').hide();
$('g.depth-'+idepth).addClass('opthide');
}
}
}
setTimeout(update_links,1500);
var xMin = d3.min(nodes, function(d) { return d.x; });
var xMax = d3.max(nodes, function(d) { return d.x; });
var yOffset = 90;
var xOffset = -xMin + yOffset;
var newHeight = xMax - xMin + 2 * yOffset;
if (newHeight > parseInt($('svg.mgraph').attr("height"))) {
$('svg.mgraph').attr("height", newHeight);
}
svg.attr("transform", "translate(" + 100 + "," + xOffset + ")");
}
function check_children(d,a,b) {
if((d.children) && (d.children.length)) return a
if((d._children) && (d._children.length)) return a
return b
}
function arrayReduce(arr,n) {
if(n > arr.length)
return arr.concat(Array(n-arr.length).fill(arr.at(-1)))
return arr.filter(function(_,i) {
if (i === 0 || i === arr.length - 1) return true;
const step = (arr.length-1)/(n-1);
for (let j = 1; j < n - 1; j++)
if (Math.round(j * step) === i)
return true;
return false;
});
}
function dt_graph(dt) {
raw = create_raw(dt);
treeData = grapharray_open(raw);
draw_graph();
}
function update_links() {
$('.pathlink').remove()
var i = 0
d3.selectAll("path.link").each(function(w) {
var t = $(this);
var id=t.attr("id");
var xd = t.attr("d")
var csid = t.attr("csid")
var depth = parseInt(t.attr("ldeep")) || 0
var text = t.attr("ldata")
var pname = t.attr("kdata")
var xclass = "btext prechk-"+text
var mclass = $(this).attr("class")
if((mclass) && mclass.indexOf("chosen") > -1) {
xclass += " chosen"
}
if(showFullTree)
xclass += " fullTree"
d3.select("g")
.insert("g","path.link").attr("class","pathlink cdepth-"+String(depth)).attr("id","x"+id)
.append("path").attr("d",xd).attr("id","f"+id)
.style("fill","none").style("stroke","#ccc")
.attr("class","xlink");
var doffset = parseInt(70 - (4-depth)*5.5)
var yoffset = -10
if(showFullTree)
yoffset = -6
d3.select("g#x"+id).append("text").attr("dx",-6).attr("dy",yoffset).attr("class","gtext")
.append("textPath").attr("href","#f"+id).attr("class",xclass)
.attr("text-anchor","middle")
.attr("id","t"+id)
.attr("csid",csid)
.attr("parentname",pname)
.text(text).attr("startOffset",doffset+"%")
.on("click",pathclick)
.on("mouseover",showdiv)
.on("mouseout",hidediv);
});
}
function graph_dynamic(input) {
const dpContainer = input.parentElement.parentElement.parentElement;
const finddpIndex = $(input).data("dpdepth");
const nodes = d3.selectAll("g.node.depth-"+String(finddpIndex));
function traverse_remove(xnode) {
if(!xnode.__data__) {
console.log("Error no nodes to descend!");
}
if(!xnode.__data__._schildren) {
console.log("Error no node _schildren data to restore from!");
}
let removeValues = [];
xnode.__data__.children = Array.from(xnode.__data__._schildren);
dpContainer.querySelectorAll("input").forEach(function(cinput) {
if(!cinput.checked)
removeValues.push($(cinput).data("dpvdepth"));
});
removeValues.reverse().forEach(function(rindex) {
removevalueIndex = parseInt(rindex);
xnode.__data__.children.splice(removevalueIndex,1);
});
update(xnode.__data__);
}
if(nodes.length) {
nodes[0].forEach(function(xnode) {
if(xnode.__data__) {
if(xnode.__data__._schildren) {
traverse_remove(xnode);
} else if(xnode.__data__.children) {
let removevalueIndex = $(input).data("dpvdepth");
xnode.__data__._schildren = Array.from(xnode.__data__.children);
xnode.__data__.children.splice(removevalueIndex,1);
update(xnode.__data__);
}
}
});
}
}
/* Helper function for advanced UI affects */
function pathclick() {};
function showdiv() {};
function hidediv() {};
function dorightclick() {};
function doclick() {};
function togglehelp() {};
return {
pathclick:pathclick,
showdiv:showdiv,
hidediv:hidediv,
dorightclick:dorightclick,
doclick:doclick,
togglehelp:togglehelp,
graph_dynamic: graph_dynamic,
dt_graph: dt_graph,
setSelector: setSelector,
__version__: "1.0.10"
};
})();
const SSVC = (function() {
let outcomes = [];
let results = {};
let decision_points = [];
let decision_trees = [];
let form = null;
let dpMap = {};
let default_namespace = "x_com.example#psirt";
let namespaces = [];
let __version__ = "1.0.12";
function niceString(str) {
if (str.length)
return str.charAt(0).toUpperCase() + str.slice(1);
return "";
}
function add_dash_n(str, strSet) {
if(!(str in strSet))
return str;
const regex = /(-\d+)$/;
const match = str.match(regex);
let newNumber = -1;
let nstr = str + newNumber.toString();
if (match) {
const numberPart = parseInt(match[1], 10);
newNumber = numberPart - 1;
nstr = str.replace(regex, newNumber.toString());
}
while(nstr in strSet) {
newNumber = newNumber - 1;
nstr = str.replace(regex, newNumber.toString());
}
return nstr;
}
function name_version(obj) {
if(obj.name && obj.version)
return obj.name + " (" + obj.version + ")";
else if (obj.name)
return obj.name + " (0.0.1)";
else
return "";
}
function dtreeSort(a, b) {
const nameA = a.data.namespace.toUpperCase() + a.data.name.toUpperCase()
+ a.data.version.toUpperCase();
const nameB = b.data.namespace.toUpperCase() + b.data.name.toUpperCase()
+ b.data.version.toUpperCase();
if (nameA < nameB)
return -1;
if (nameA > nameB)
return 1;
return 0;
}
function simpleCopy(inobj) {
return JSON.parse(JSON.stringify(inobj));
}
window.addEventListener("beforeunload", function(e) {
if(sessionStorage.getItem("ssvc-pending")) {
var confirmationMessage = 'Are you sure to leave the page?';
const event = (e || window.event);
event.preventDefault();
event.returnValue = confirmationMessage;
return confirmationMessage;
}
return null;
});
function applyStyle(div, props) {
Object.entries(props).forEach(function(k,_) {
div.style[k[0]] = k[1];
});
}
function topalert(msg, level, timeOut) {
const colors = {
"danger": "#dc3545",
"info": "#0d6efd",
"warn": "#ffc107",
"success": "#198754"
};
let div = document.querySelector("[data-topalert]");
if (!div) {
div = document.createElement("div");
div.setAttribute("data-topalert", "1");
const props = {
width: "100%",
top: "0px",
left: "0px",
"text-align": "center",
color: "white",
border: "2px solid transparent",
"border-radius": "4px",
padding: "12px",
opacity: 0,
"font-size": "1.2em",
"transition": "opacity 0.5s ease",
"z-index": "9999",
"background-color": "transparent",
position: "relative"
};
applyStyle(div, props);
document.body.prepend(div);
}
if (!msg) {
div.style.opacity = 0;
div.style.backgroundColor = "transparent";
div.innerHTML = "";
return;
}
div.innerHTML = "";
div.innerText = msg + " ";
const span = document.createElement("span");
span.innerHTML = "✕";
applyStyle(span, {
cursor: "pointer",
color: "white",
padding: "2px 6px",
border: "1px solid white",
"border-radius": "2px",
margin: "3px"
});
div.appendChild(span);
div.onclick = () => div.remove();
div.style.backgroundColor = colors[level] || colors["info"];
div.style.display = "block";
div.style.opacity = 0.95;
if (timeOut) {
if (div._timer) clearTimeout(div._timer);
div._timer = setTimeout(() => {
div.style.opacity = 0;
setTimeout(() => div.remove(), 600);
}, timeOut * 1000);
}
}
function compareObj(o1,o2) {
const keys = Object.keys(o1);
if(keys.length != Object.keys(o2).length)
return false;
for(let i=0; i < keys.length; i++) {
const key = keys[i];
if(o1[key] != o2[key]) {
return false;
}
}
return true;
}
function h5button(text, current, type) {
const h5 = document.createElement("h5");
h5.innerText = text;
h5.style.display = "inline-block";
if(current)
h5.style.backgroundColor = "#007bff";
else
h5.style.backgroundColor = "#555555";
h5.style.padding = "2px";
h5.style.color = "white";
h5.style.borderRadius = "4px";
h5.setAttribute("data-tabs", type);
h5.addEventListener("click", function() {
const btn = this;
const current = btn.getAttribute("data-tabs");
btn.parentElement.querySelectorAll("[data-tabs]").forEach(function(el) {
el.style.backgroundColor = "#555555";
});
btn.style.backgroundColor = "#007bff";
btn.parentElement.querySelectorAll("[data-tab]").forEach(function(el) {
if(el.getAttribute("data-tab") == current)
el.style.display = "block";
else
el.style.display = "none";
});
});
return h5;
}
function rand_namespace(dtype) {
if(!dtype)
dtype = "generic"
return "x_example." + crypto.randomUUID() + "#" + dtype.toLowerCase();
}
function lock_unlock(lock) {
const select = form.parentElement.querySelector("[id='sampletrees']");
const btnAll = form.parentElement.querySelector("[data-toggleall]");
if(lock) {
const nextel = select.nextElementSibling;
/* Add custom data entry points */
select.style.display = "none";
select.parentElement.children[0].innerText = "Custom Decision Model";
if(nextel.tagName.toUpperCase() == "DIV") {
const inp = nextel.querySelector("input[name='namespace'");
} else {
const div = document.createElement("div");
const clbtn = form.parentElement.querySelector("[data-clear]");
let dt;
if(clbtn.hasAttribute("data-json")) {
dt = JSON.parse(clbtn.getAttribute("data-json"));
} else {
dt = {namespace: default_namespace,
name: "Custom Decision Tree",
definition: "Uploaded Custom Decistion Tree from CSV",
version: "1.0.1"};
}
div.style.display = "inline-block";
applyStyle(div, {border: "1px dotted darkblue",
display: "inline-block",
borderRadius: "2px",
padding: "4px"
});
["name","namespace","definition","version"].forEach(function(nprop) {
const label = document.createElement("label");
const input = document.createElement("input");
input.name = nprop;
const nproper = niceString(nprop);
input.placeholder = "Decision Tree " + nproper;
if(nprop != "namespace")
input.value = dt[nprop];
else
input.value = rand_namespace("decisiontables");
applyStyle(input, {background: "transparent",
padding: "0px 2px",
display: "inline",
fontWeight: "bolder",
border: "1px solid #198754"});
applyStyle(label, {display: "block",
textAlign: "right",
fontWeight: "bolder"});
label.innerText = nproper + ": ";
label.append(input);
div.append(label);
});
select.after(div);
}
select.setAttribute("disabled", true);
btnAll.setAttribute("disabled", true);
btnAll.style.opacity = 0.5;
sessionStorage.setItem("ssvc-pending",1);
}else {
select.parentElement.children[0].innerText = "Sample Decision Models::";
if(select.nextElementSibling.nodeName.toUpperCase() == "DIV") {
select.nextElementSibling.remove();
}
select.style.display = "inline-block";
select.removeAttribute("disabled");
btnAll.removeAttribute("disabled");
btnAll.style.opacity = 1.0;
sessionStorage.removeItem("ssvc-pending");
}
}
function clear() {
const sampletrees = form.parentElement.querySelector("[id='sampletrees']");
const nextel = sampletrees.nextElementSibling;
if(nextel.tagName.toUpperCase() == "DIV")
nextel.remove();
sessionStorage.removeItem("ssvc-pending");
sampletrees.style.display = "inline-block";
sampletrees.disabled = false;
sampletrees.dispatchEvent(new Event('change'));
const cbtn = form.parentElement.querySelector("[data-customize='1']");
cbtn.innerHTML = "Customize";
const btnAll = form.parentElement.querySelector("[data-toggleall]");
btnAll.disabled = false;
btnAll.style.opacity = 1.0;
}
function toNumberTable(table, headers) {
const encoders = {};
const numberTable = table.map(function(row) {
return headers.reduce(function(r,head) {
const col = row[head];
if(head in encoders) {
if (!(col in encoders[head])) {
const max = Math.max.apply(this,Object.values(encoders[head]));
encoders[head][col] = max + 1;
}
} else {
encoders[head] = {};
encoders[head][col] = 0;
}
r.push(encoders[head][row[head]]);
return r;
}, []);
});
return numberTable;
}
function csvline(cols) {
cols = cols.map(x => x.replace('"','\\"'))
return '"' + cols.join('","') + '"\n';
}
function get_decision_point(name, version, namespace) {
/* version 1.0.0 name mapping in CSV files */
if(name in dpMap && !version) {
version = dpMap[name]["version"]
namespace = dpMap[name]["namespace"];
/* Check if name is remapped in CSVs*/
if("name" in dpMap[name])
name = dpMap[name]["name"];
}
if(!version)
version = "1.0.0";
if(!namespace)
namespace = "ssvc";
for(let i = 0; i < decision_points.length; i++) {
if(decision_points[i].data.name == name &&
decision_points[i].data.namespace == namespace &&
decision_points[i].data.version == version) {
return decision_points[i].data;
}
}
return {};
}
function update_stats() {
results = {};
form.querySelectorAll("[data-outcome]").forEach(function(el) {
let outcome;
if(el.querySelector("input"))
outcome = el.querySelector("input").value
else
outcome = el.innerText;
if(outcome in results ) {
if(el.parentElement.style.display != "none")
results[outcome] += 1;
} else {
if(el.parentElement.style.display != "none")
results[outcome] = 1;
else
results[outcome] = 0;
}
});
let outcomeMax = Math.max.apply(null, Object.values(results));
Object.keys(results).forEach( function(outcome) {
outcome = outcome.replaceAll('"','\\"');
let rlabel = form.querySelector('[data-result="'+outcome+'"] > label > span');
rlabel.innerText = " (" + String(results[outcome]) + ")";
let dbar = document.createElement("span");
dbar.innerHTML = " ";
dbar.style.marginLeft = "6px";
dbar.style.display = "inline-block";
dbar.style.width = String(parseInt(70 * results[outcome]/outcomeMax)) + "px";
dbar.style.backgroundColor = "#5480de";
/* dbar.style.position = "fixed"; */
rlabel.appendChild(dbar);
});
const dtstamp = (new Date()).toISOString().replace(/[^0-9a-zA-Z]/g,"-")
const download_filename = "SSVC_Custom_" + dtstamp + "_json.txt";
let clbutton = form.parentElement.querySelector("[data-clear]");
let jsonTreedump = clbutton.getAttribute("data-json");
const btn = form.parentElement.querySelector("[data-download-json]");
btn.href = "data:text/plain;charset=utf-8,"+
encodeURIComponent(jsonTreedump);
btn.setAttribute("download", download_filename);
const btncsv = form.parentElement.querySelector("[data-download-csv]");
let CSV = form.parentElement.querySelector("[data-tab='CSV']").dataset.csv;
if(!CSV) {
/* Force render to ensure the elment is visible properly*/
let tab = form.parentElement.querySelector("[data-tab='CSV']");
let oldv = tab.style.display;
tab.style.display = "block";
CSV = form.parentElement.querySelector("[data-tab='CSV']").innerText;
tab.style.display = oldv;
}
btncsv.href = "data:text/plain;charset=utf-8," +
encodeURIComponent(CSV);
const csv_filename = "SSVC_Custom_" + dtstamp + ".csv";
btncsv.setAttribute("download", csv_filename);
}
function createSSVC(csv, uploaded) {
const exporter = { "ssvcV1_0_1": {
"id": "CVE-1999-1234",
"selections": [],
"timestamp": (new Date()).toISOString(),
"schemaVersion": "1-0-1"
}};
const ssvcTable = [];
let jsonTree = {}
let CSV = "";
let outcomeTitle;
let lines = [];
let headers = [];
let dset = [];
if(typeof(csv) === "object") {
/* This is JSON data more powerful use it */
jsonTree = simpleCopy(csv);
if(('schemaVersion' in jsonTree) &&
(jsonTree.schemaVersion === '2.0.0') &&
('decision_points' in jsonTree)) {
if(('outcome' in jsonTree) &&
(jsonTree.outcome in jsonTree.decision_points))
outcomeTitle = jsonTree.decision_points[jsonTree.outcome].name;
let hkeys = [];
dpMap = {};
let outcomeset = [];
Object.entries(jsonTree.decision_points).forEach(function([k,dp]) {
/* Dynamically build the name map per Tree. Assumption is there
are NO two decision points with the same name */
if(dp.name in dpMap)
topalert("danger", "Duplicate Names found in Decision Table can cause confusion", 0);
dpMap[dp.name] = {name: dp.name, version: dp.version,
namespace: dp.namespace, data: dp};
if(k != jsonTree.outcome) {
dset.push(dp.values.map(x => x.name));
headers.push(dp.name);
hkeys.push(k);
} else {
/* Make sure the dset has the last entry as outcome*/
outcomeset = dp.values.map(x => x.name);
}
});
dset.push(outcomeset);
headers.push(outcomeTitle);
hkeys.push(jsonTree.outcome);
if('mapping' in jsonTree)
jsonTree.mapping.forEach(function(dvpair) {
const line = hkeys.map(function(k) {
const vk = dvpair[k];
const dp = jsonTree.decision_points[k];
for(let i = 0; i < dp.values.length; i++)
if(dp.values[i].key == vk)
return dp.values[i].name;
});
lines.push(line);
});
}
} else {
lines = csv.split('\n');
headers = lines.shift().split(',');
if(headers[0] == "row") {
/* CSV with row numbering setup so remove the first element*/
headers.shift();
}
}
const main = document.createElement("main");
function destroytip() {
let div = form.querySelector("[data-temp]");
if(div)
div.remove();
}
function tooltip(event, info) {
let div = form.querySelector("[data-temp]");
if(!div) {
div = document.createElement("div");
div.setAttribute("data-temp",1);
}
div.innerText = info;
const style = {
"display": "block",
"backgroundColor": "#333",
"opacity": "0.9",
"maxWidth": "300px",
"color": "white",
"borderRadius": "8px",
"position": "absolute",
"left": String(event.pageX + 10) + "px",
"top": String(event.pageY + 10) + "px",
"padding": "4px",
"border": "2px solid aqua"
};
Object.assign(div.style,style);
form.appendChild(div);
}
function helptip(event) {
let dp = {};
/* Check for Decision Point or Outcome and return helptip */
const isdp = ["data-dp","data-outcomename"].some(function(fdp) {
if(event.target.hasAttribute(fdp)) {
/* A Decision Point help tip */
dp = get_decision_point(event.target.getAttribute(fdp));
if(dp.definition) {
tooltip(event, dp.definition);
return true;
}
}
/* This is more like continue */
return false;
});
if(isdp)
return false;
/* A Decision Point value helptip */
const dpInput = event.target.querySelector("input");
if(dpInput) {
if(dpInput.parentElement.parentElement.getAttribute("data-help")) {
dp = JSON.parse(dpInput.parentElement.parentElement.getAttribute("data-help"));
} else {
dp = get_decision_point(dpInput.name);
if(dp.definition)
dpInput.parentElement.parentElement.setAttribute("data-help",JSON.stringify(dp));
}
}
if(dp.values) {
for(let i=0; i<dp.values.length; i++) {
if(dp.values[i].name.toLowerCase() == dpInput.value.toLowerCase()) {
return tooltip(event,dp.values[i].definition);
}
}
}
}
if(uploaded) {
/* Remove any name conflict */
headers.forEach(function(dpName,i) {
while(dpName in dpMap) {
let idx = 1;
dpName = dpName + "-" + idx;
idx = idx + 1;
}
headers[i] = dpName;
dpMap[dpName] = {"namespace": "x_com.example#psirt",
"version": "1.0.0"};
});
}
main.style.display = "flex";
main.style.verticalAlign = "top";
const allrows = document.createElement("div");
CSV = CSV + csvline(headers);
lines.forEach(function(line) {
if(!line)
return;
let cols;
if(Array.isArray(line)) {
cols = line;
} else {
cols = line.split(',');
if(cols[0].match(/^\d+$/)) {
/* Remove first element of columns if they are row numbers */
cols.shift();
}
}
CSV = CSV + csvline(cols);
const row = {};
const rowDiv = document.createElement("div");
rowDiv.style.display = "table-row";
headers.forEach(function(dpName,i) {
const colDiv = document.createElement("div");
colDiv.innerText = cols[i];
colDiv.style.padding = "0px";
colDiv.style.border = "1px solid cyan";
colDiv.style.display = "table-cell";
if( i == headers.length - 1)
colDiv.setAttribute("data-outcome", cols[i]);
rowDiv.append(colDiv);
row[dpName] = cols[i];
});
rowDiv.style.display = "none";
rowDiv.setAttribute("data-row",JSON.stringify(row));
allrows.append(rowDiv);
ssvcTable.push(row);
});
const rowDiv = document.createElement("div");