-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathindex.html
More file actions
1253 lines (1110 loc) · 61.2 KB
/
index.html
File metadata and controls
1253 lines (1110 loc) · 61.2 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
<!DOCTYPE html>
<head>
<script src="https://cdn.rawgit.com/eligrey/FileSaver.js/e9d941381475b5df8b7d7691013401e171014e89/FileSaver.min.js"></script>
<script src="https://d3js.org/d3.v4.js"></script>
<!-- Google Analytics -->
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-15242862-11"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-15242862-11');
</script>
<!-- End Google Analytics -->
<script type="module">
import {csvParse} from "https://cdn.skypack.dev/d3-dsv@3";
</script>
<script src="saveSvgAsPng.js"></script> <!--- From: https://github.com/exupero/saveSvgAsPng -->
<style>
body {
font-family: Arial, Helvetica, sans-serif;
display: flex;
flex-direction: row;
justify-content: center;
background-color:lightgray;
}
#wrapper {
width: 1000px;
background-color: white;
padding: 30px;
}
#container, #output-container {
display: flex;
flex-direction: row;
justify-content: space-between;
margin-top: 20px;
}
.input-buttons {
margin-top: 10px;
display: flex;
flex-direction: row;
}
button, .button-ref {
flex-grow: 1;
margin: 2px;
font-size: 1em;
color: white;
background-color: #5599EE;
}
#controls {
display: flex;
flex-direction: column;
}
#data-wrapper {
padding: 0;
border: 1px solid darkgray;
width: 500px;
height: 300px;
overflow: auto;
}
#input-container {
margin: 0;
}
textarea#input-data {
margin: 0;
border: 1px solid darkgray;
padding: 0;
width: 500px;
height: 100px;
white-space: nowrap;
overflow: auto;
resize: none;
}
#input-table, th {
margin: 0;
border: 1px solid darkgray;
border-collapse: collapse;
}
th, td {
padding-left: 10px;
padding-right: 10px;
}
#input-table {
width: 500px;
}
#additional-info {
padding: 20px;
}
#oppscores-table {
width:auto;
border: 1px solid black;
border-collapse: collapse;
margin-top: 10px;
}
#oppscores-table th {
border: 1px solid black;
}
#oppscores-table td {
border: 0.5px solid darkgray;
}
td {
font-family: monospace;
}
.important {
font-style: italic;
}
#footer {
width: 100%;
margin-top: 20px;
text-align: right;
}
.big-red {
font-size: 2em;
color: red;
padding-top: -5px;
padding-bottom: -5px;
}
.hidden-button {
visibility: hidden;
}
.ext-info {
font-style: italic;
}
#status {
color: red;
}
textarea#alt-data {
width: 80%;
height: 100px;
resize: none;
margin: 20px;
overflow: scroll;
word-wrap: unset;
}
#alt-message {
color: red;
}
#alt-close {
position: absolute;
top: 8px;
right: 18px;
font-size: 1.5em;
user-select: none;
}
#alt-close:hover {
color: #5599EE;
}
.emph {
text-decoration: underline;
}
#output-log {
font-family: monospace;
border: 1px solid darkgray;
}
/* Tab Navigation Styles */
.tab-container {
margin-top: 20px;
}
.tab-nav {
display: flex;
border-bottom: 2px solid #ddd;
margin-bottom: 0;
}
.tab-button {
background-color: #f8f9fa;
border: 1px solid #ddd;
border-bottom: none;
padding: 12px 20px;
cursor: pointer;
font-size: 14px;
font-weight: bold;
color: #333;
margin-right: 2px;
transition: background-color 0.3s;
border-radius: 5px 5px 0 0;
}
.tab-button:hover {
background-color: #e9ecef;
}
.tab-button.active {
background-color: white;
color: #5599EE;
border-bottom: 2px solid white;
margin-bottom: -2px;
}
.input-style-page {
display: none;
padding: 20px;
border: 1px solid #ddd;
border-top: none;
background-color: white;
}
.input-style-page.active {
display: block;
}
</style>
</head>
<body>
<div id="wrapper">
<h2>Opportunity Score and Map Generator (beta)</h2>
<i>
<b>Outcome Categories is an experimentall feature. Please <a href="https://github.com/jpcarrascal/OppScoreWeb" target="_blank">file an issue</a> or <a href="mailto:juanpcarrascal@gmail.com">contact me</a> if you run into problems when using it.</b>
<br/>
For more information about the Opportunity Score and Map, check <a href="https://medium.com/uxr-microsoft/what-is-the-opportunity-score-and-how-to-obtain-it-bb81fcbf79b7" target="_blank">this blog post</a>.
<br/>
This is an open-source tool, currently in beta. Please file issues or bugs in the <a href="https://github.com/jpcarrascal/OppScoreWeb" target="_blank">GitHub repo</a>,
</i>
<div id="container">
<div id="controls">
<div id="input-container">
<!-- Tab Navigation -->
<div class="tab-nav">
<div class="tab-button" data-tab="survey-tab">Input: Survey data (row per response)</div>
<div class="tab-button active" data-tab="datapoint-tab">Input: Row per datapoint</div>
</div>
<!-- Survey data tab -->
<div class="input-style-page" id="survey-tab">
<div style="margin-bottom: 15px;">
<label>
<input type="checkbox" id="survey-categories-checkbox"> My data has categories
</label>
</div>
Use this tab if your data comes from a survey tool. Each row should be a response from a unique participant.
<ul>
<li>Sample data included for you to play around with. Click "Clear data" to import yours.</li>
<li>Paste your <span class="emph">tab-separated</span> data below.</li>
<li>Columns contain <b>importance</b> and <b>satisfaction</b> for each outcome. This means that each outcome appears in <i>two</i> columns.</li>
<li>Qualtrics and Survey Monkey exports should be almost ready to go. just make sure you add 'importance' and 'satisfaction' labels to each column (first row of your data).</li>
<li><b>importance</b> and <b>satisfaction</b> should be in a 1-5 scale (1=low importance/5=high importance; 1=low satisfaction/5=high satisfaction).</li>
</ul>
<textarea id="alt-data" rows="20" cols="70" wrap="off"></textarea>
</div>
<!-- Row per datapoint tab -->
<div class="input-style-page active" id="datapoint-tab">
<div style="margin-bottom: 15px;">
<label>
<input type="checkbox" id="datapoint-categories-checkbox"> My data has categories
</label>
</div>
Use this tab if your data is already in the format of <span class="important">one row per outcome</span>. This means that each unique participant probably has multiple rows.
<ul>
<li>Sample data included for you to play around with. Click "Clear data" to import yours.</li>
<li id="datapoint-description">Paste <span class="emph">tab-separated</span> data formatted in <span class="important">3 columns <b>[outcome, importance, satisfaction]</b></span></li>
<li><b>importance</b> and <b>satisfaction</b> should be in a 1-5 scale (1=low importance/5=high importance; 1=low satisfaction/5=high satisfaction).</li>
</ul>
<table id="input-table">
<tr>
<th id="category-header" style="display: none;">category</th>
<th>outcome</th>
<th>importance</th>
<th>satisfaction</th>
</tr>
</table>
<textarea id="input-data" placeholder="Paste tab or comma-separated data here"></textarea>
<br/>
<!-- <input type="file" id="file-selector" accept=".csv" single /> -->
</div>
</div>
<p id="status"> </p>
<div class="input-buttons">
<button class="map-data">Map data</button>
<button id="clear">Clear data</button>
</div>
</div>
</div>
<div id="output-container">
<div>
<h3>Opportunity Scores</h3>
<button id="export-table" class="hidden-button">Copy scores to clipboard</button>
<table id="oppscores-table">
<tr>
<th class="big-red">•</th>
<th id="category-output-header" style="display: none;">Category</th>
<th>Outcome</th>
<th>Importance</th>
<th>Satisfaction</th>
<th>OppScore</th>
</tr>
</table>
</div>
<div>
<h3>Opportunity Landscape/Map</h3>
<button id="export-map" class="hidden-button">Export landscape/map to PNG</button>
<div id="map-area"></div>
</div>
</div>
<h4>Output log:</h4>
<div id="output-log">
</div>
<div id="footer">
<a href="https://jpcarrascal.github.io" target="_blank">jpcarrascal.github.io</a>
</div>
</div>
<script>
window.onload = function() {
var removeMissing = true;
var verboseLog = true;
var categoriesEnabled = false;
var dataWasCleared = false; // Flag to track when data was explicitly cleared
if (window.location.search.substr("keepMissing")) {
console.log("Rows with missing values will not be removed")
removeMissing = false;
}
function refresh(data) {
// set the dimensions and margins of the graph
var margin = {top: 10, right: 10, bottom: 50, left: 50},
width = 520 - margin.left - margin.right,
height = 470 - margin.top - margin.bottom;
// append the svg object to the body of the page
var SVG = d3.select("#map-area")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
SVG.append("rect")
.attr("width", "100%")
.attr("height", "100%")
.attr("fill", "white")
.attr("transform",
"translate(-" + margin.left + ",-" + margin.top + ")");
// X scale and Axis
var x = d3.scaleLinear()
.domain([0, 10]) // This is the min and the max of the data: 0 to 100 if percentages
.range([0, width]); // This is the corresponding value I want in Pixel
SVG
.append('g')
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
// X scale and Axis
var y = d3.scaleLinear()
.domain([0, 10]) // This is the min and the max of the data: 0 to 100 if percentages
.range([height, 0]); // This is the corresponding value I want in Pixel
SVG
.append('g')
.call(d3.axisLeft(y));
SVG.append("line")
.attr("x1", x(10))
.attr("y1", y(0))
.attr("x2", x(10))
.attr("y2", y(10))
.style("stroke", "black");
SVG.append("line")
.attr("x1", x(0))
.attr("y1", y(10))
.attr("x2", x(10))
.attr("y2", y(10))
.style("stroke", "black");
SVG.append("line")
.attr("x1", x(0))
.attr("y1", y(0))
.attr("x2", x(10))
.attr("y2", y(10))
.style("stroke", "lightgrey");
SVG.append("line")
.attr("x1", x(5))
.attr("y1", y(0))
.attr("x2", x(10))
.attr("y2", y(10))
.style("stroke", "lightgrey");
SVG.append("line")
.attr("x1", x(6))
.attr("y1", y(0))
.attr("x2", x(10))
.attr("y2", y(8))
.style("stroke-dasharray", ("3, 3"))
.style("stroke", "lightgrey");
SVG.append("line")
.attr("x1", x(7.5))
.attr("y1", y(0))
.attr("x2", x(10))
.attr("y2", y(5))
.style("stroke-dasharray", ("3, 3"))
.style("stroke", "lightgrey");
SVG.append("text")
.attr("x", function (d) { return x(3); } )
.attr("y", function (d) { return y(6); } )
.style("text-anchor", "middle")
.text("Overserved")
.attr("font-family", "sans-serif")
.style("font-size", "17px")
.style("fill", "lightgrey");
SVG.append("text")
.attr("x", function (d) { return x(4.1); } )
.attr("y", function (d) { return y(2); } )
.style("text-anchor", "middle")
.text("Appropriately Served")
.attr("font-family", "sans-serif")
.style("font-size", "17px")
.style("fill", "lightgrey");
SVG.append("text")
.attr("x", function (d) { return x(8); } )
.attr("y", function (d) { return y(2); } )
.style("text-anchor", "middle")
.text("Underserved")
.attr("font-family", "sans-serif")
.style("font-size", "17px")
.style("fill", "lightgrey");
// Underserved pportunity areas
SVG.append("text")
.attr("x", function (d) { return x(8.7); } )
.attr("y", function (d) { return y(6.25); } )
.style("text-anchor", "middle")
.text("OppScore > 10")
.attr("font-family", "sans-serif")
.style("font-size", "13px")
.style("fill", "lightgrey");
SVG.append("text")
.attr("x", function (d) { return x(8.7); } )
.attr("y", function (d) { return y(5.95); } )
.style("text-anchor", "middle")
.text("Solid opportunity")
.attr("font-family", "sans-serif")
.style("font-size", "11px")
.style("fill", "lightgrey");
SVG.append("text")
.attr("x", function (d) { return x(8.8); } )
.attr("y", function (d) { return y(3.75); } )
.style("text-anchor", "middle")
.text("OppScore > 12")
.attr("font-family", "sans-serif")
.style("font-size", "13px")
.style("fill", "lightgrey");
SVG.append("text")
.attr("x", function (d) { return x(8.8); } )
.attr("y", function (d) { return y(3.45); } )
.style("text-anchor", "middle")
.text("High opportunity")
.attr("font-family", "sans-serif")
.style("font-size", "11px")
.style("fill", "lightgrey");
SVG.append("text")
.attr("x", function (d) { return x(8.9); } )
.attr("y", function (d) { return y(0.5); } )
.style("text-anchor", "middle")
.text("OppScore > 15")
.attr("font-family", "sans-serif")
.style("font-size", "13px")
.style("fill", "lightgrey");
SVG.append("text")
.attr("x", function (d) { return x(8.9); } )
.attr("y", function (d) { return y(0.2); } )
.style("text-anchor", "middle")
.text("Extreme opportunity")
.attr("font-family", "sans-serif")
.style("font-size", "11px")
.style("fill", "lightgrey");
// Axis labels
SVG.append("text")
.attr("x", function (d) { return x(-4.5); } )
.attr("y", function (d) { return y(10.6); } )
.style("text-anchor", "middle")
.text("Satisfaction")
.attr("font-family", "sans-serif")
.style("font-size", "15px")
.style("fill", "grey")
.attr("transform", function(d) {
return "rotate(-90)"
});
SVG.append("text")
.attr("x", function (d) { return x(5); } )
.attr("y", function (d) { return y(-0.8); } )
.style("text-anchor", "middle")
.text("Importance")
.attr("font-family", "sans-serif")
.style("font-size", "15px")
.style("fill", "grey");
// points:
// Get unique categories for color mapping
var categories = [];
if (categoriesEnabled && data.length > 0) {
categories = [...new Set(data.map(item => item.category).filter(cat => cat))];
}
var points = SVG
.selectAll("whatever")
.data(data)
.enter()
.append("circle")
.attr("cx", function(d){ return x(d.x) })
.attr("cy", function(d){ return y(d.y) })
.style("fill", function(d) {
if (categoriesEnabled && d.category) {
return getCategoryColor(d.category, categories);
}
return "red";
})
.attr("r", 5)
var labels = SVG
.selectAll("whatever")
.data(data)
.enter()
.append("text")
.attr("x", function (d) { return x(d.x)-8; } )
.attr("y", function (d) { return y(d.y)+3; } )
.text(function(d) { return d.index; })
.attr("font-family", "sans-serif")
.style("text-anchor", "end")
.attr("font-size", "12px")
.attr("cursor","default")
.attr("fill", "#666")
}
refresh([]);
//generateRandomData();
var sampleDataURL = "https://raw.githubusercontent.com/jpcarrascal/OppScoreWeb/main/sampledata.csv";
var inputElement = document.querySelector("#input-data");
readSampleData(sampleDataURL, document.querySelector("#input-data"));
var surveyData = "https://raw.githubusercontent.com/jpcarrascal/OppScoreWeb/main/sampleSurveyData.csv";
fetch(surveyData)
.then(response => response.text())
.then(data => document.querySelector("#alt-data").value = data);
d3.select(".map-data").on('click', function(e){
clearLog();
d3.select("#table-body").remove();
var inputdata;
if(document.getElementById("survey-tab").classList.contains("active")) {
// Survey tab is active - get data from alt-data and reformat
var surveyData = document.querySelector("#alt-data").value;
try {
inputdata = reformatData(surveyData);
document.querySelector("#status").style.color = "forestgreen";
document.querySelector("#status").innerText = "Reformat sucessful! Transformed data is included below";
} catch(error) {
document.querySelector("#status").innerText = error;
return; // Exit early on error
}
} else {
// Datapoint tab is active - get data from input-data
inputdata = document.querySelector("#input-data").value;
}
var newData = parsePastedData(inputdata);
console.log("Parsed data: ", newData);
if (newData.length > 0) {
document.querySelectorAll(".hidden-button").forEach( elem => { elem.style.visibility = "visible" });
status.textContent = "";
var oppScoreData = calculateOppScores(newData);
if (d3.select("svg")) d3.select("svg").remove();
asTable(oppScoreData);
refresh(oppScoreData);
} else {
status.textContent = "Data missing or wrong format.";
}
});
d3.select("#export-map").on('click', function(e){
saveSvgAsPng(document.querySelector("svg"), "OppMap.png");
});
d3.select("#export-table").on('click', function(e){
var tableElement = document.querySelector("#oppscores-table");
selectElementContents(tableElement);
document.execCommand('copy');
document.querySelector("#export-table").innerText = "Copied!";
setTimeout(() => {document.querySelector("#export-table").innerText = "Copy scores to clipboard"}, 3000);
});
function clearData() {
// Set flag to indicate data was explicitly cleared
dataWasCleared = true;
// Clear output elements first
d3.select("svg").remove();
d3.select("#table-body").remove();
document.querySelectorAll(".hidden-button").forEach( elem => { elem.style.visibility = "hidden" });
status.textContent = "";
clearLog();
// Clear input data in both tabs
document.querySelector("#input-data").value = "";
document.querySelector("#input-data").style.display = "block";
document.querySelector("#alt-data").value = "";
document.querySelector("#alt-data").style.display = "block";
// Note: Category checkboxes are NOT reset - they maintain their state
// Users can manually change category settings independent of data clearing
// Update UI elements based on current category state (but don't change the checkboxes)
const categoryHeader = document.getElementById('category-header');
const categoryOutputHeader = document.getElementById('category-output-header');
if (categoriesEnabled) {
categoryHeader.style.display = 'table-cell';
categoryOutputHeader.style.display = 'table-cell';
} else {
categoryHeader.style.display = 'none';
categoryOutputHeader.style.display = 'none';
}
// Update column descriptions based on current category state
updateColumnDescriptions(categoriesEnabled);
// Reset map visualization
refresh([]);
}
d3.select("#clear").on('click', function(e){
if (document.querySelector("#file-selector"))
document.querySelector("#file-selector").value = null;
clearData();
});
// Load sample data
function readSampleData(sourceURL, destination) {
var result = Array();
// Clear the destination first
destination.value = "";
d3.csv(sourceURL, function(data) {
for (var i = 0; i < data.length; i++) {
if (categoriesEnabled && data[i].category) {
// Handle 4-column format with categories
result[i] = {category: data[i].category, outcome: data[i].outcome, x: data[i].importance, y: data[i].satisfaction}
destination.value += (result[i].category + "\t" + result[i].outcome + "\t"
+ result[i].x + "\t" + result[i].y + "\n");
} else {
// Handle 3-column format without categories
result[i] = {outcome: data[i].outcome, x: data[i].importance, y: data[i].satisfaction}
destination.value += (result[i].outcome + "\t"
+ result[i].x + "\t" + result[i].y + "\n");
}
}
console.log("Read "+i+" rows from sample file");
// Reset the flag since sample data was successfully loaded
dataWasCleared = false;
});
return result;
}
// Read CSV file (borrowed from https://web.dev/read-files/)
const status = document.getElementById('status');
if (window.FileList && window.File && window.FileReader) {
try {
document.getElementById('file-selector').addEventListener('change', event => {
clearData();
status.textContent = '';
const file = event.target.files[0];
if (!file.type) {
status.textContent = 'Error: The File.type property does not appear to be supported on this browser.';
return;
}
/*
if (!file.type.match('text/csv')) {
status.textContent = 'Error: The selected file does not appear to be a CSV file.'
return;
}
*/
const reader = new FileReader();
reader.addEventListener('load', event => {
const data = d3.csvParse( event.target.result.replace(/\t/g,",") );
parseFileData(data);
//parsePastedData(event.target.result);
});
reader.readAsText(file,"UTF-8");
});
} catch (e) {
console.log("File import button not found.");
}
}
function parseFileData(data) {
outputLog("Parsing data from file...");
initialDataLength = data.length;
var newDisplayData = "";
var incompleteRows = 0;
var garbageRows = 0;
var cols = data.columns;
cols = cols.map(c => c.toLowerCase());
if(! (cols.includes("outcome") && cols.includes("importance") && cols.includes("satisfaction")) ) {
status.textContent = "Some columns not found! (they should be [outcome, importance, satisfaction])";
return;
}
console.log(data.columns);
for(var i = 0; i<data.length; i++) {
data[i].importance = parseInt(data[i].importance);
data[i].satisfaction = parseInt(data[i].satisfaction);
if( !Number.isInteger(data[i].importance) && !Number.isInteger(data[i].satisfaction) ) {
incompleteRows++;
outputLog("Malformed row "+i+" removed: " + data[i]);
data.splice(i,1);
} else if( !Number.isInteger(data[i].importance) || !Number.isInteger(data[i].satisfaction) ) {
if(removeMissing) {
outputLog("Incomplete row "+i+" removed: " + data[i]);
data.splice(i,1);
}
incompleteRows++;
} else {
newDisplayData += data[i].outcome + "\t" + data[i].importance + "\t" + data[i].satisfaction + "\n";
}
}
document.querySelector("#input-data").value = newDisplayData;
outputLog(initialDataLength + " input rows.");
outputLog(incompleteRows + " rows with missing values found.");
outputLog(garbageRows + " invalid rows found.");
if(removeMissing) outputLog(incompleteRows + " rows removed.");
outputLog(data.length + " rows used in calculation.");
// Reset the flag since file data was successfully loaded
dataWasCleared = false;
return data;
}
function outputLog(line) {
if(verboseLog) {
console.log(line);
var log = document.getElementById("output-log");
log.innerText += line;
log.innerText += "\n";
}
}
function clearLog() {
document.getElementById("output-log").innerText = "";
}
function objJoin(obj) {
var str = "";
Object.values(obj).forEach(val => {
str += ", "+obj
});
return str;
}
function parsePastedData(inputdata) {
verboseLog = false;
var newData = Array();
var newDisplayData = "";
var incompleteRows = 0;
var garbageRows = 0;
var expectedColumns = categoriesEnabled ? 4 : 3;
var columnDescription = categoriesEnabled ? "[category, outcome, importance, satisfaction]" : "[outcome, importance, satisfaction]";
inputdata = inputdata.replace(/,/g,"\t"); // Replace commas with tabs
if(inputdata != "") {
var lines = inputdata.split(/\n/);
var initialDataLength = 0;
for(var i = 0; i<lines.length; i++) {
if(lines[i] != "") {
initialDataLength++;
var row = lines[i].split(separator);
// Parse numeric values based on whether categories are enabled
if (categoriesEnabled) {
row[2] = parseInt(row[2]); // importance
row[3] = parseInt(row[3]); // satisfaction
} else {
row[1] = parseInt(row[1]); // importance
row[2] = parseInt(row[2]); // satisfaction
}
if(row.length > expectedColumns) {
outputLog("Row "+i+" removed (row too long): " + row + "length: " + row.length);
status.textContent = "Too many columns! (they should be " + columnDescription + ")"
garbageRows++;
} else if(row.length == expectedColumns) {
var isValid = false;
var dataObj = {};
if (categoriesEnabled) {
if (Number.isInteger(row[2]) && Number.isInteger(row[3])) {
dataObj = {category: row[0], outcome: row[1], x: row[2], y: row[3]};
newDisplayData += row[0] + "\t" + row[1] + "\t" + row[2] + "\t" + row[3] + "\n";
isValid = true;
}
} else {
if (Number.isInteger(row[1]) && Number.isInteger(row[2])) {
dataObj = {outcome: row[0], x: row[1], y: row[2]};
newDisplayData += row[0] + "\t" + row[1] + "\t" + row[2] + "\n";
isValid = true;
}
}
if (isValid) {
newData.push(dataObj);
} else if (categoriesEnabled && (!Number.isInteger(row[2]) && !Number.isInteger(row[3]))) {
outputLog("Row "+i+" removed (non-numeric or missing values): " + row);
garbageRows++;
} else if (!categoriesEnabled && (!Number.isInteger(row[1]) && !Number.isInteger(row[2]))) {
outputLog("Row "+i+" removed (non-numeric or missing values): " + row);
garbageRows++;
} else {
// Handle missing values
if(removeMissing) {
outputLog("Row "+i+" removed (missing values): " + row);
} else {
if (categoriesEnabled) {
if(isNaN(row[2])) row[2] = "";
if(isNaN(row[3])) row[3] = "";
newData.push({category: row[0], outcome: row[1], x: row[2], y: row[3]});
newDisplayData += row[0] + "\t" + row[1] + "\t" + row[2] + "\t" + row[3] + "\n";
} else {
if(isNaN(row[1])) row[1] = "";
if(isNaN(row[2])) row[2] = "";
newData.push({outcome: row[0], x: row[1], y: row[2]});
newDisplayData += row[0] + "\t" + row[1] + "\t" + row[2] + "\n";
}
outputLog("Incomplete row "+i+" kept: " + row);
}
incompleteRows++;
}
} else {
outputLog("Row "+i+" removed: " + row);
garbageRows++;
}
}
}
verboseLog = true;
}
outputLog(initialDataLength + " input rows.");
outputLog(incompleteRows + " missing values found.");
outputLog(garbageRows + " rows with invalid values found.");
if(removeMissing) console.log(incompleteRows + " rows removed.");
outputLog(newData.length + " rows used in calculation.");
//document.querySelector("#input-data").value = newDisplayData;
return newData;
}
function calculateOppScores(data) {
var outcomes = Array();
var OppScores = Array();
for(var i = 0; i<data.length; i++)
if(!outcomes.includes(data[i].outcome))
outcomes.push(data[i].outcome);
for(var i = 0; i<outcomes.length; i++) {
var thisOutcome = outcomes[i];
var sumImp = 0, sumSat = 0, countImp = 0, countSat = 0;
var category = null;
for(var j = 0; j<data.length; j++) {
var d = data[j];
if( d.outcome == thisOutcome ) {
if (categoriesEnabled && category === null) {
category = d.category;
}
if(d.x > 3)
sumImp ++;
countImp ++;
if(d.y > 3)
sumSat ++;
countSat ++;
}
}
var meanImp = roundTwo(10 * (sumImp / countImp));
var meanSat = roundTwo(10 * (sumSat / countSat));
var oppScore = meanImp + (Math.max(meanImp-meanSat,0));
oppScore = Math.round((oppScore + Number.EPSILON) * 100) / 100;
var scoreObj = { index: 0, outcome: thisOutcome, x: meanImp, y: meanSat, oppScore: oppScore };
if (categoriesEnabled) {
scoreObj.category = category;
}
OppScores.push(scoreObj);
}
OppScores.sort( compare );
for(var i=0; i<OppScores.length; i++) {
OppScores[i].index = i+1;
}
return OppScores;
}
function asTable(newData) {
var table = document.querySelector("#oppscores-table");
var tBody = document.createElement('tbody');
tBody.id = "table-body";
// Get unique categories for color mapping
var categories = [];
if (categoriesEnabled) {
categories = [...new Set(newData.map(item => item.category))];
}
for(var i = 0; i<newData.length; i++) {
var row = tBody.insertRow();
// Index column (with colored background if categories enabled)
var c0 = row.insertCell();
c0.innerHTML = newData[i].index;
if (categoriesEnabled && newData[i].category) {
c0.style.backgroundColor = getCategoryColor(newData[i].category, categories);
c0.style.color = 'white';
c0.style.fontWeight = 'bold';
}
// Category column (if enabled)
if (categoriesEnabled) {
var cCat = row.insertCell();
cCat.innerHTML = newData[i].category || '';
}
// Outcome column
var c1 = row.insertCell();
c1.innerHTML = newData[i].outcome;
// Importance column
var c2 = row.insertCell();
c2.innerHTML = newData[i].x;
c2.style.textAlign = "right";
// Satisfaction column
var c3 = row.insertCell();
c3.innerHTML = newData[i].y;
c3.style.textAlign = "right";
// Opportunity Score column
var c4 = row.insertCell();
c4.innerHTML = newData[i].oppScore;
c4.style.textAlign = "right";
}
table.append(tBody);
}
var separator = "\t"; // separator = /[\t,\,]/;
function reformatData(input) {
var data = input.split("\n");
var categoriesRow, impsatsRow, outcomesRow, dataStartRow;
if (categoriesEnabled) {
// Category-enabled format: [categories, importance/satisfaction, outcomes, data...]
categoriesRow = 0;
impsatsRow = 1;
outcomesRow = 2;
dataStartRow = 3;
} else {
// Standard format: [importance/satisfaction, outcomes, data...]
categoriesRow = null;
impsatsRow = 0;
outcomesRow = 1;
dataStartRow = 2;
}
if(!data[impsatsRow].toLowerCase().includes("satisfaction") ||
!data[impsatsRow].toLowerCase().includes("importance")) {
throw("ERROR: Every column should be labeled as 'importance' or 'satisfaction'!!!");
}
var categories = categoriesEnabled ? data[categoriesRow].split(separator) : null;
var impsats = data[impsatsRow].split(separator);