-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1453 lines (1278 loc) · 58.2 KB
/
Copy pathindex.html
File metadata and controls
1453 lines (1278 loc) · 58.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>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sankey Diagram Generator - Web App</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: #f5f5f5;
padding: 10px 0 0 0;
margin: 0;
min-height: 100vh;
}
.container {
display: grid;
grid-template-columns: minmax(280px, 360px) 1fr;
gap: 10px;
width: 100%;
height: 98vh;
max-width: none;
margin: 0;
padding: 0 10px 10px;
}
.panel {
background: white;
border-radius: 8px;
padding: 15px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
.left-panel {
min-height: 0;
overflow-y: auto;
overflow-x: hidden;
}
.right-panel {
display: flex;
flex-direction: column;
min-height: 0;
}
h1 {
font-size: 18px;
margin-bottom: 15px;
color: #333;
}
h2 {
font-size: 14px;
margin: 15px 0 8px 0;
color: #555;
font-weight: 600;
}
.section {
margin-bottom: 15px;
padding: 12px;
background: #f9f9f9;
border-radius: 6px;
border: 1px solid #e0e0e0;
}
.param-row {
display: flex;
align-items: center;
margin-bottom: 8px;
gap: 8px;
}
.param-row label {
flex: 0 0 100px;
font-size: 13px;
color: #666;
}
input[type="number"], input[type="text"] {
flex: 1;
padding: 6px 8px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 13px;
}
button {
padding: 8px 16px;
background: #007bff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 13px;
transition: background 0.2s;
}
button:hover {
background: #0056b3;
}
button.secondary {
background: #6c757d;
}
button.secondary:hover {
background: #545b62;
}
button.success {
background: #28a745;
}
button.success:hover {
background: #218838;
}
.button-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 10px;
}
.button-grid button {
width: 100%;
}
canvas {
flex: 1;
border: 1px solid #ddd;
border-radius: 6px;
background: white;
}
.status {
padding: 8px 12px;
background: #e9ecef;
border-radius: 4px;
font-size: 12px;
margin-top: 10px;
color: #495057;
}
.info-text {
font-size: 11px;
color: #6c757d;
margin-top: 5px;
font-style: italic;
}
.value-display {
font-size: 12px;
color: #007bff;
padding: 6px;
background: #e7f3ff;
border-radius: 4px;
margin: 8px 0;
}
.scale-display {
font-size: 12px;
color: #28a745;
padding: 6px;
background: #d4edda;
border-radius: 4px;
margin: 8px 0;
}
select {
padding: 6px 8px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 13px;
background: white;
}
.radio-group {
display: flex;
gap: 15px;
margin: 8px 0;
}
.radio-group label {
display: flex;
align-items: center;
gap: 5px;
font-size: 13px;
color: #666;
cursor: pointer;
}
input[type="radio"] {
cursor: pointer;
}
.column-control {
position: absolute;
display: flex;
flex-direction: column;
align-items: center;
pointer-events: auto;
transform: translateX(-50%);
overflow: visible;
z-index: 10;
}
.column-control input.socket-input {
min-width: 42px;
width: 42px;
padding: 4px 6px;
font-size: 13px;
text-align: center;
box-sizing: border-box;
}
.column-control .align-btn {
padding: 4px 8px;
font-size: 11px;
margin-top: 4px;
}
#columnInputsOverlay {
overflow: visible;
}
.column-label-box {
background: rgba(30, 100, 200, 0.95);
border: 1.5px solid #1a5fb4;
border-radius: 4px;
color: #fff;
font-weight: bold;
font-size: 13px;
padding: 4px 10px;
cursor: crosshair;
user-select: none;
white-space: nowrap;
min-height: 22px;
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 4px;
}
.design-viewport {
flex: 1;
min-height: 0;
position: relative;
overflow: hidden;
border: 2px dashed #999;
border-radius: 6px;
background: #fafafa;
}
.design-inner {
position: absolute;
left: 50%;
top: 50%;
transform-origin: center center;
}
.design-inner canvas {
display: block;
}
.design-overlay {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
pointer-events: none;
}
.design-overlay .column-control {
pointer-events: auto;
}
.design-viewport.pan-cursor {
cursor: grab;
}
.design-viewport.pan-cursor:active {
cursor: grabbing;
}
.design-viewport.socket-cursor {
cursor: crosshair;
}
</style>
</head>
<body>
<div class="container">
<!-- Left Panel: Controls -->
<div class="panel left-panel">
<h1>🎨 Sankey Controls</h1>
<div class="section">
<h2>Columns</h2>
<div class="param-row">
<label>Number of columns:</label>
<input type="number" id="numColumns" value="6" min="2" max="20" title="Press Enter to apply">
</div>
<div class="info-text">Press Enter to apply</div>
</div>
<div class="section">
<h2>Thread Randomization</h2>
<div class="param-row">
<label>Thread ID:</label>
<input type="number" id="selectedThread" value="0" min="0">
<label style="flex: 0 0 50px;">Seed:</label>
<input type="number" id="seedValue" value="42" min="1">
</div>
<div class="button-grid">
<button onclick="setSeed()">Set Seed</button>
<button onclick="randomizeSeed()" class="secondary">Randomize</button>
</div>
<div class="info-text">Thread 0 = Col0→Col1, Thread 1 = Col1→Col2, etc.</div>
</div>
<div class="section">
<h2>Physical Dimensions (meters)</h2>
<div class="param-row">
<label>Width (X):</label>
<input type="number" id="scaleX" value="1.0" step="0.1" min="0.1">
<span style="flex: 0 0 20px;">m</span>
</div>
<div class="param-row">
<label>Height (Y):</label>
<input type="number" id="scaleY" value="1.0" step="0.1" min="0.1">
<span style="flex: 0 0 20px;">m</span>
</div>
<div class="scale-display" id="scaleDisplay">1.0m × 1.0m (1000mm × 1000mm)</div>
</div>
<button onclick="updatePreview()" class="success" style="width: 100%; font-size: 15px; padding: 12px; margin: 15px 0;">
↻ UPDATE PREVIEW
</button>
<div class="section">
<h2>Actions</h2>
<button onclick="autoGenerate()" style="width: 100%; margin-bottom: 8px;">Auto-Generate Random</button>
</div>
<div class="section">
<h2>SVG Export Mode</h2>
<div class="radio-group">
<label>
<input type="radio" name="svgMode" value="full" checked> Full Curves
</label>
<label>
<input type="radio" name="svgMode" value="segmented"> Segmented
</label>
</div>
</div>
<div class="section">
<h2>Import / Export</h2>
<input type="file" id="csvImport" accept=".csv" style="display: none;" onchange="importCSV(event)">
<div class="button-grid">
<button onclick="document.getElementById('csvImport').click()">Import CSV</button>
<button onclick="exportCSV()">Export CSV</button>
</div>
<button onclick="saveSVG()" style="width: 100%; margin-top: 8px;">Save SVG</button>
</div>
<div class="status" id="status">Ready. Click UPDATE PREVIEW to start.</div>
<div class="status" style="background: #fff3cd; color: #856404; margin-top: 5px;" id="connectionCount">
Connections: 0
</div>
</div>
<!-- Right Panel: Preview -->
<div class="panel right-panel">
<div class="preview-header" style="display: flex; align-items: center; gap: 16px; margin-bottom: 8px; flex-shrink: 0;">
<h1 style="margin-bottom: 0;">Real-time Preview</h1>
<label style="display: flex; align-items: center; gap: 8px; font-size: 13px; color: #666;">
Zoom:
<input type="range" id="zoomSlider" min="25" max="200" value="100" style="width: 220px;">
<span id="zoomValue">100%</span>
</label>
</div>
<div class="preview-viewport" style="display: flex; flex: 1; min-height: 0; gap: 8px;">
<div class="pan-y-slider-wrap" style="display: flex; flex-direction: column; align-items: center; flex-shrink: 0;">
<span style="font-size: 10px; color: #666;">Pan Y</span>
<div style="height: 100px; display: flex; align-items: center;">
<input type="range" id="panYSlider" min="-100" max="100" value="0" style="width: 100px; transform: rotate(-90deg); margin: 0;">
</div>
</div>
<div style="display: flex; flex-direction: column; flex: 1; min-width: 0; min-height: 0;">
<div class="design-viewport" id="designViewport">
<div class="design-inner" id="designInner">
<canvas id="preview"></canvas>
</div>
<div id="columnInputsOverlay" class="design-overlay"></div>
</div>
<div class="pan-x-slider-wrap" style="display: flex; align-items: center; gap: 8px; flex-shrink: 0; padding: 4px 0;">
<span style="font-size: 10px; color: #666;">Pan X</span>
<input type="range" id="panXSlider" min="-100" max="100" value="0" style="flex: 1;">
</div>
</div>
</div>
<div class="info-text" style="margin-top: 10px; text-align: center; flex-shrink: 0;">
Preview shows diagram structure. Drag sockets to adjust; drag column label to move column. SVG export uses exact physical dimensions.
</div>
</div>
</div>
<script>
// State
let connections = [];
let socketsPerColumn = {};
let threadSeeds = {};
let numColumns = 6;
let columnX = {}; // col -> x_mm (optional; column drag)
let socketPositions = {}; // node -> [x_mm, y_mm] (optional override; socket drag or import)
let dragNode = null;
let dragColumn = null;
let dragView = false;
let lastPanMousePx = [0, 0];
let columnCenterPx = {}; // col -> x pixel (for overlay positioning)
let previewZoom = 1;
let panX = 0, panY = 0;
let designDisplayW = 400, designDisplayH = 300;
let viewportW = 400, viewportH = 300;
let maxPanX = 0, maxPanY = 0;
// Initialize
function init() {
numColumns = parseInt(document.getElementById('numColumns').value);
for (let i = 0; i < numColumns; i++) {
socketsPerColumn[i] = 10;
if (i < numColumns - 1) {
threadSeeds[i] = 42;
}
}
updateScaleDisplay();
updatePreview();
}
function updateScaleDisplay() {
const x = parseFloat(document.getElementById('scaleX').value);
const y = parseFloat(document.getElementById('scaleY').value);
const xmm = (x * 1000).toFixed(0);
const ymm = (y * 1000).toFixed(0);
document.getElementById('scaleDisplay').textContent =
`${x}m × ${y}m (${xmm}mm × ${ymm}mm)`;
}
// Thread seed control
function setSeed() {
const threadId = parseInt(document.getElementById('selectedThread').value);
const seed = parseInt(document.getElementById('seedValue').value);
if (threadId >= 0 && threadId < numColumns - 1 && seed > 0) {
threadSeeds[threadId] = seed;
updatePreview();
setStatus(`Thread ${threadId} seed set to ${seed}`);
}
}
function randomizeSeed() {
const threadId = parseInt(document.getElementById('selectedThread').value);
const newSeed = Math.floor(Math.random() * 9999) + 1;
threadSeeds[threadId] = newSeed;
document.getElementById('seedValue').value = newSeed;
updatePreview();
setStatus(`Thread ${threadId} randomized with seed ${newSeed}`);
}
// Auto-generate
function autoGenerate() {
// Randomize all thread seeds
for (let i = 0; i < numColumns - 1; i++) {
threadSeeds[i] = Math.floor(Math.random() * 9999) + 1;
}
// Update displayed seed
const currentThread = parseInt(document.getElementById('selectedThread').value);
document.getElementById('seedValue').value = threadSeeds[currentThread] || 42;
updatePreview();
setStatus('Auto-generated with random seeds');
}
// Generate connections from parameters.
// Only column 0 defines the total number of lines; each line is one path from Col0 to last column.
function generateConnections() {
connections = [];
const nLines = socketsPerColumn[0] || 10;
for (let lineId = 0; lineId < nLines; lineId++) {
const path = [];
let current = `Col0_Socket${lineId}`;
for (let threadId = 0; threadId < numColumns - 1; threadId++) {
const colTo = threadId + 1;
const socketsTo = socketsPerColumn[colTo] || 10;
const seed = threadSeeds[threadId] || 42;
seededRandom(seed + lineId * 1000);
const targetIdx = Math.floor(seededRandom() * socketsTo);
const target = `Col${colTo}_Socket${targetIdx}`;
const value = Math.floor(seededRandom() * 9) + 1;
path.push({ source: current, target, value });
current = target;
}
for (const edge of path) {
connections.push(edge);
}
}
document.getElementById('connectionCount').textContent = `Connections: ${connections.length} (${nLines} lines from Col0)`;
}
// Seeded random number generator
let seed = 42;
function seededRandom(newSeed) {
if (newSeed !== undefined) {
seed = newSeed;
}
seed = (seed * 9301 + 49297) % 233280;
return seed / 233280;
}
// Update preview
function updatePreview() {
// Update number of columns
const newNumCols = parseInt(document.getElementById('numColumns').value);
if (newNumCols !== numColumns) {
numColumns = newNumCols;
columnX = {}; // reset column positions so they space evenly across physical dimensions
for (let i = 0; i < numColumns; i++) {
if (socketsPerColumn[i] === undefined) {
socketsPerColumn[i] = 10;
}
if (i < numColumns - 1 && threadSeeds[i] === undefined) {
threadSeeds[i] = 42;
}
}
document.getElementById('selectedThread').max = Math.max(0, numColumns - 2);
}
updateScaleDisplay();
generateConnections();
reframeDesign();
setStatus('Preview updated');
}
function reframeDesign() {
document.getElementById('zoomSlider').value = 100;
panX = 0;
panY = 0;
var sx = document.getElementById('panXSlider');
var sy = document.getElementById('panYSlider');
if (sx) sx.value = 0;
if (sy) sy.value = 0;
drawCanvas();
}
// Draw canvas: only the design viewport content; zoom/pan apply only inside the dashed frame
function drawCanvas() {
const canvas = document.getElementById('preview');
const ctx = canvas.getContext('2d');
const viewportEl = document.getElementById('designViewport');
const designInner = document.getElementById('designInner');
if (!viewportEl || !designInner) return;
viewportW = viewportEl.clientWidth;
viewportH = viewportEl.clientHeight;
if (viewportW <= 0 || viewportH <= 0) return;
previewZoom = (document.getElementById('zoomSlider')?.value ?? 100) / 100;
document.getElementById('zoomValue').textContent = Math.round(previewZoom * 100) + '%';
var scaleX = parseFloat(document.getElementById('scaleX').value);
var scaleY = parseFloat(document.getElementById('scaleY').value);
var aspectRatio = scaleX / scaleY;
designDisplayW = Math.min(viewportW, viewportH * aspectRatio);
designDisplayH = Math.min(viewportH, viewportW / aspectRatio);
if (designDisplayW < 1) designDisplayW = viewportW;
if (designDisplayH < 1) designDisplayH = viewportH;
maxPanX = Math.max(0, (designDisplayW * previewZoom - viewportW) / 2);
maxPanY = Math.max(0, (designDisplayH * previewZoom - viewportH) / 2);
var panXSlider = document.getElementById('panXSlider');
var panYSlider = document.getElementById('panYSlider');
panX = maxPanX > 0 ? (parseFloat(panXSlider?.value || 0) / 100) * maxPanX : 0;
panY = maxPanY > 0 ? (parseFloat(panYSlider?.value || 0) / 100) * maxPanY : 0;
panX = Math.max(-maxPanX, Math.min(maxPanX, panX));
panY = Math.max(-maxPanY, Math.min(maxPanY, panY));
if (panXSlider) panXSlider.value = maxPanX > 0 ? Math.round((panX / maxPanX) * 100) : 0;
if (panYSlider) panYSlider.value = maxPanY > 0 ? Math.round((panY / maxPanY) * 100) : 0;
designInner.style.width = designDisplayW + 'px';
designInner.style.height = designDisplayH + 'px';
designInner.style.transform = 'translate(-50%, -50%) translate(' + panX + 'px, ' + panY + 'px) scale(' + previewZoom + ')';
canvas.width = designDisplayW;
canvas.height = designDisplayH;
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (connections.length === 0) {
ctx.fillStyle = '#999';
ctx.font = '16px Arial';
ctx.textAlign = 'center';
ctx.fillText('Click UPDATE PREVIEW to generate diagram', canvas.width / 2, canvas.height / 2);
window._lastDrawState = null;
document.getElementById('columnInputsOverlay').innerHTML = '';
return;
}
var drawW = designDisplayW;
var drawH = designDisplayH;
var offsetX = 0;
var offsetY = 0;
ctx.strokeStyle = '#999';
ctx.lineWidth = 2;
ctx.setLineDash([5, 5]);
ctx.strokeRect(offsetX, offsetY, drawW, drawH);
ctx.setLineDash([]);
const [positionsMm, widthMm, heightMm] = calculatePositionsMm();
const toPx = (xMm, yMm) => [
offsetX + (xMm / widthMm) * drawW,
offsetY + (yMm / heightMm) * drawH
];
const positions = {};
columnCenterPx = {};
for (const [node, xy] of Object.entries(positionsMm)) {
positions[node] = toPx(xy[0], xy[1]);
const col = parseInt(node.split('_')[0].replace('Col', ''));
if (columnCenterPx[col] === undefined) columnCenterPx[col] = { sum: positions[node][0], n: 1 };
else { columnCenterPx[col].sum += positions[node][0]; columnCenterPx[col].n++; }
}
Object.keys(columnCenterPx).forEach(col => {
const o = columnCenterPx[col];
columnCenterPx[col] = o.sum / o.n;
});
// Draw connections
ctx.strokeStyle = '#3498db';
ctx.lineWidth = 2;
ctx.globalAlpha = 0.6;
for (const conn of connections) {
const p1 = positions[conn.source];
const p2 = positions[conn.target];
if (p1 && p2) {
drawBezierCurve(ctx, p1[0], p1[1], p2[0], p2[1]);
}
}
// Draw nodes
ctx.globalAlpha = 1.0;
for (const [node, [x, y]] of Object.entries(positions)) {
const colNum = parseInt(node.split('_')[0].replace('Col', ''));
if (colNum === 0) {
ctx.fillStyle = '#2ecc71'; // Green
} else if (colNum === numColumns - 1) {
ctx.fillStyle = '#e74c3c'; // Red
} else {
ctx.fillStyle = '#f39c12'; // Orange
}
ctx.beginPath();
ctx.arc(x, y, 4, 0, Math.PI * 2);
ctx.fill();
}
const labelY = offsetY + 20;
// Display aspect ratio and scale info
ctx.fillStyle = '#666';
ctx.font = '12px Arial';
ctx.textAlign = 'center';
ctx.fillText(`Scale: ${scaleX}m × ${scaleY}m (Aspect: ${aspectRatio.toFixed(2)}:1)`,
canvas.width / 2, canvas.height - 10);
window._lastDrawState = { offsetX, offsetY, drawW, drawH, widthMm, heightMm, positions, positionsMm, columnCenterPx: Object.assign({}, columnCenterPx), labelY: offsetY + 20, viewportW, viewportH, designDisplayW, designDisplayH };
updateColumnOverlay();
}
function designToViewportX(cx) {
return viewportW / 2 + panX + (cx - designDisplayW / 2) * previewZoom;
}
function designToViewportY(cy) {
return viewportH / 2 + panY + (cy - designDisplayH / 2) * previewZoom;
}
function updateColumnOverlay() {
const overlay = document.getElementById('columnInputsOverlay');
if (!overlay) return;
const cols = Object.keys(columnCenterPx).map(Number).sort((a, b) => a - b);
const labelY = (window._lastDrawState && window._lastDrawState.labelY != null) ? window._lastDrawState.labelY : 20;
overlay.innerHTML = '';
cols.forEach(col => {
const div = document.createElement('div');
div.className = 'column-control';
div.style.left = designToViewportX(columnCenterPx[col] || 0) + 'px';
div.style.top = designToViewportY(labelY) + 'px';
const labelEl = document.createElement('div');
labelEl.className = 'column-label-box';
labelEl.textContent = 'Col ' + col;
labelEl.dataset.col = col;
labelEl.addEventListener('mousedown', function(e) {
e.preventDefault();
dragColumn = parseInt(this.dataset.col);
lastMousePx = getCanvasMouse(e);
document.addEventListener('mousemove', docColumnDragMove);
document.addEventListener('mouseup', docColumnDragUp);
});
const inp = document.createElement('input');
inp.type = 'number';
inp.className = 'socket-input';
inp.min = 1;
inp.value = socketsPerColumn[col] ?? 10;
inp.dataset.col = col;
inp.addEventListener('change', function() {
const c = parseInt(this.dataset.col);
const v = parseInt(this.value) || 1;
socketsPerColumn[c] = v;
updatePreview();
});
const btn = document.createElement('button');
btn.className = 'align-btn secondary';
btn.textContent = 'Align';
btn.dataset.col = col;
btn.addEventListener('click', function() { alignColumn(parseInt(this.dataset.col)); });
div.appendChild(labelEl);
div.appendChild(inp);
div.appendChild(btn);
overlay.appendChild(div);
});
}
function alignColumn(col) {
const columns = getColumnsFromConnections();
const nodes = Array.from(columns[col] || []);
nodes.forEach(n => { delete socketPositions[n]; });
drawCanvas();
setStatus(`Column ${col} aligned`);
}
function calculateNodePositions(width, height, offsetX, offsetY) {
const columns = {};
for (const conn of connections) {
const srcCol = parseInt(conn.source.split('_')[0].replace('Col', ''));
const tgtCol = parseInt(conn.target.split('_')[0].replace('Col', ''));
if (!columns[srcCol]) columns[srcCol] = new Set();
if (!columns[tgtCol]) columns[tgtCol] = new Set();
columns[srcCol].add(conn.source);
columns[tgtCol].add(conn.target);
}
const positions = {};
const marginX = 60;
const marginY = 40;
const usableWidth = width - 2 * marginX;
const usableHeight = height - 2 * marginY;
const sortedCols = Object.keys(columns).sort((a, b) => a - b);
const xStep = sortedCols.length > 1 ? usableWidth / (sortedCols.length - 1) : 0;
sortedCols.forEach((col, colIdx) => {
const nodes = Array.from(columns[col]).sort((a, b) => {
const aSocket = parseInt(a.split('_Socket')[1]);
const bSocket = parseInt(b.split('_Socket')[1]);
return aSocket - bSocket;
});
const x = offsetX + marginX + (colIdx * xStep);
const yStep = nodes.length > 1 ? usableHeight / (nodes.length - 1) : 0;
nodes.forEach((node, nodeIdx) => {
const y = offsetY + marginY + (nodeIdx * yStep);
positions[node] = [x, y];
});
});
return positions;
}
function roundRect(ctx, x, y, w, h, r) {
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.lineTo(x + w - r, y);
ctx.quadraticCurveTo(x + w, y, x + w, y + r);
ctx.lineTo(x + w, y + h - r);
ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
ctx.lineTo(x + r, y + h);
ctx.quadraticCurveTo(x, y + h, x, y + h - r);
ctx.lineTo(x, y + r);
ctx.quadraticCurveTo(x, y, x + r, y);
ctx.closePath();
}
function drawBezierCurve(ctx, x1, y1, x2, y2) {
const dx = x2 - x1;
const cx1 = x1 + dx * 0.5;
const cy1 = y1;
const cx2 = x1 + dx * 0.5;
const cy2 = y2;
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.bezierCurveTo(cx1, cy1, cx2, cy2, x2, y2);
ctx.stroke();
}
// CSV Export with full parameters and socket positions (column#, socket#, X, Y)
function exportCSV() {
if (connections.length === 0) {
alert('No connections to export');
return;
}
const [positionsMm] = calculatePositionsMm();
let csv = '#SANKEY_PARAMETERS\n';
csv += `num_columns,${numColumns}\n`;
csv += `scale_x_meters,${document.getElementById('scaleX').value}\n`;
csv += `scale_y_meters,${document.getElementById('scaleY').value}\n`;
csv += '#SOCKET_CONFIGURATION\n';
for (let i = 0; i < numColumns; i++) {
csv += `col_${i}_sockets,${socketsPerColumn[i] || 10}\n`;
}
csv += '#THREAD_SEEDS\n';
for (let i = 0; i < numColumns - 1; i++) {
csv += `thread_${i}_seed,${threadSeeds[i] || 42}\n`;
}
csv += '#SOCKET_POSITIONS\n';
csv += 'column,socket,X,Y\n';
const socketRows = Object.entries(positionsMm).map(([node, xy]) => {
const col = parseInt(node.split('_')[0].replace('Col', ''));
const socket = parseInt(node.split('_Socket')[1]);
return { col, socket, x: xy[0], y: xy[1] };
});
socketRows.sort((a, b) => a.col !== b.col ? a.col - b.col : a.socket - b.socket);
for (const r of socketRows) {
csv += `${r.col},${r.socket},${r.x},${r.y}\n`;
}
csv += '#CONNECTIONS\n';
csv += 'source,target,value\n';
for (const conn of connections) {
csv += `${conn.source},${conn.target},${conn.value}\n`;
}
const blob = new Blob([csv], { type: 'text/csv' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'sankey_design.csv';
a.click();
setStatus('Exported complete design to CSV');
}
// CSV Import with full parameters
function importCSV(event) {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = function(e) {
const text = e.target.result;
const lines = text.split('\n');
let mode = 'connections';
connections = [];
const tempSockets = {};
const tempSeeds = {};
const tempSocketPositions = {};
let tempNumCols = null;
let tempScaleX = null;
let tempScaleY = null;
for (const line of lines) {
const parts = line.trim().split(',');
if (parts.length === 0 || !parts[0]) continue;
if (parts[0].startsWith('#')) {
if (parts[0] === '#SANKEY_PARAMETERS') mode = 'parameters';
else if (parts[0] === '#SOCKET_CONFIGURATION') mode = 'sockets';
else if (parts[0] === '#THREAD_SEEDS') mode = 'seeds';
else if (parts[0] === '#SOCKET_POSITIONS') mode = 'socket_positions';
else if (parts[0] === '#CONNECTIONS') mode = 'connections';
continue;
}
if (mode === 'parameters') {
if (parts[0] === 'num_columns') tempNumCols = parseInt(parts[1]);
else if (parts[0] === 'scale_x_meters') tempScaleX = parseFloat(parts[1]);
else if (parts[0] === 'scale_y_meters') tempScaleY = parseFloat(parts[1]);
} else if (mode === 'sockets') {
if (parts[0].startsWith('col_') && parts[0].endsWith('_sockets')) {
const colNum = parseInt(parts[0].split('_')[1]);
tempSockets[colNum] = parseInt(parts[1]);
}
} else if (mode === 'seeds') {
if (parts[0].startsWith('thread_') && parts[0].endsWith('_seed')) {
const threadId = parseInt(parts[0].split('_')[1]);
tempSeeds[threadId] = parseInt(parts[1]);
}
} else if (mode === 'socket_positions') {
if (parts[0] === 'column') continue; // Skip header
if (parts.length >= 4) {
const col = parseInt(parts[0]);
const socket = parseInt(parts[1]);
const x = parseFloat(parts[2]);
const y = parseFloat(parts[3]);
const node = `Col${col}_Socket${socket}`;
tempSocketPositions[node] = [x, y];
}
} else if (mode === 'connections') {
if (parts[0] === 'source') continue; // Skip header
if (parts.length >= 3) {
connections.push({
source: parts[0].trim(),
target: parts[1].trim(),
value: parseFloat(parts[2])
});
}
}
}
// Apply imported parameters
if (tempNumCols !== null) {
numColumns = tempNumCols;
document.getElementById('numColumns').value = tempNumCols;
}
if (tempScaleX !== null) {
document.getElementById('scaleX').value = tempScaleX;
}
if (tempScaleY !== null) {
document.getElementById('scaleY').value = tempScaleY;
}
if (Object.keys(tempSockets).length > 0) {
socketsPerColumn = tempSockets;
}
if (Object.keys(tempSeeds).length > 0) {
threadSeeds = tempSeeds;
const currentThread = parseInt(document.getElementById('selectedThread').value);
if (threadSeeds[currentThread] !== undefined) {
document.getElementById('seedValue').value = threadSeeds[currentThread];
}
}
if (Object.keys(tempSocketPositions).length > 0) {
socketPositions = tempSocketPositions;
}
updateScaleDisplay();
reframeDesign();
document.getElementById('connectionCount').textContent = `Connections: ${connections.length}`;
setStatus(`Imported complete design: ${connections.length} connections`);
alert(`Imported complete design:\n- ${connections.length} connections\n- ${numColumns} columns\n- All parameters restored`);
};
reader.readAsText(file);
// Reset file input
event.target.value = '';
}
// SVG Export
function saveSVG() {
if (connections.length === 0) {
alert('Generate connections first');
return;
}
const mode = document.querySelector('input[name="svgMode"]:checked').value;
if (mode === 'full') {
generateFullCurveSVG();
} else {
generateSegmentedCurveSVG();
}
}
function generateFullCurveSVG() {
// Build graph
const graph = {};
const nodeType = {};
for (const conn of connections) {