-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTimelineVisualization.tsx
More file actions
3159 lines (2844 loc) · 136 KB
/
Copy pathTimelineVisualization.tsx
File metadata and controls
3159 lines (2844 loc) · 136 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
import React, { useEffect, useRef, forwardRef, useImperativeHandle, useState, useCallback } from 'react';
import * as d3 from 'd3';
import { Course, CourseCredit, OptionGroup, Period, academicPeriods } from '@/types/course';
import kthColors from '@/data/kth-colors.json';
import type { ProgramCosmetics } from '@/types/cosmetics';
type Lang = 'sv' | 'en';
type CourseOrOptionGroup = Course | OptionGroup;
interface TimelineVisualizationProps {
courses: CourseOrOptionGroup[];
language?: Lang;
programName?: string;
programCode?: string;
studyplanUrl?: string;
programComment?: string;
cosmetics?: ProgramCosmetics | null;
}
// Type guard to distinguish between Course and OptionGroup
const isCourse = (item: CourseOrOptionGroup): item is Course => {
return 'code' in item && !('type' in item);
};
const isOptionGroup = (item: CourseOrOptionGroup): item is OptionGroup => {
return 'type' in item && item.type === 'optionGroup';
};
export interface TimelineVisualizationHandle {
exportChart: (format: 'png' | 'svg' | 'pdf', options?: { includeLegend?: boolean }) => Promise<void>;
}
// Centralized styling constants (module-level so they're stable across renders)
const STYLE = {
fontFamily: "Figtree, ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, Noto Sans, 'Apple Color Emoji', 'Segoe UI Emoji'",
legend: {
width: 170,
offsetX: 85,
offsetY: 30,
background: 'rgba(255,255,255,0.95)',
borderColor: '#e5e7eb',
requires: 'Särskild behörighet',
requiredFor: 'Krävs för',
textColor: kthColors.KthBlue?.HEX || '#004791'
}
} as const;
// Default color for courses not in any cosmetics group
const defaultColor = { fill: kthColors.KthHeaven?.HEX || '#6298D2', stroke: kthColors.KthBlue?.HEX || '#004791', text: kthColors.KthLightBlue?.HEX || '#DEF0FF' };
const getColorForFamily = (family: 'blue' | 'green' | 'turquoise' | 'brick' | 'yellow') => {
const families = {
blue: { fill: kthColors.KthBlue?.HEX || '#004791', stroke: kthColors.KthMarine?.HEX || '#000061', text: kthColors.KthLightBlue?.HEX || '#DEF0FF' },
green: { fill: kthColors.KthGreen?.HEX || '#4DA061', stroke: kthColors.KthDarkGreen?.HEX || '#0D4A21', text: kthColors.KthLightGreen?.HEX || '#C7EBBA' },
turquoise: { fill: kthColors.KthTurquoise?.HEX || '#339C9C', stroke: kthColors.KthDarkTurquoise?.HEX || '#1C434C', text: kthColors.KthLightTurquoise?.HEX || '#B2E0E0' },
brick: { fill: kthColors.KthBrick?.HEX || '#E86A58', stroke: kthColors.KthDarkBrick?.HEX || '#78001A', text: kthColors.KthLightBrick?.HEX || '#FFCCC4' },
yellow: { fill: kthColors.KthYellow?.HEX || '#FFBE00', stroke: kthColors.KthDarkYellow?.HEX || '#A65900', text: kthColors.KthLightYellow?.HEX || '#FFF0B0' }
};
return families[family];
};
const getFamilyVariants = (family: 'blue' | 'green' | 'turquoise' | 'brick' | 'yellow') => {
if (family === 'blue') {
return [
{ fill: kthColors.KthLightBlue?.HEX || '#6298D2', stroke: kthColors.KthMarine?.HEX || '#000061', text: kthColors.KthMarine?.HEX || '#000061' },
];
}
if (family === 'green') {
return [
{ fill: kthColors.KthLightGreen?.HEX || '#C7EBBA', stroke: kthColors.KthDarkGreen?.HEX || '#0D4A21', text: kthColors.KthLightGreen?.HEX || '#C7EBBA' },
];
}
if (family === 'turquoise') {
return [
{ fill: kthColors.KthLightTurquoise?.HEX || '#B2E0E0', stroke: kthColors.KthDarkTurquoise?.HEX || '#1C434C', text: kthColors.KthLightTurquoise?.HEX || '#B2E0E0' },
];
}
if (family === 'brick') {
return [
{ fill: kthColors.KthLightBrick?.HEX || '#FFCCC4', stroke: kthColors.KthDarkBrick?.HEX || '#78001A', text: kthColors.KthDarkBrick?.HEX || '#78001A' },
];
}
// yellow
return [
{ fill: kthColors.KthLightYellow?.HEX || '#FFF0B0', stroke: kthColors.KthDarkYellow?.HEX || '#A65900', text: kthColors.KthDarkYellow?.HEX || '#A65900' },
];
};
// Translations (static — module-level so they're stable across renders)
const tr = {
sv: {
legend: {
exams: 'Tentor',
reexams: 'Omtentor',
prerequisitesCompleted: 'Kräver avklarad kurs',
prerequisitesParticipation: 'Kräver deltagande',
courses: 'Kurser',
studyPeriods: 'Läsperioder',
examPeriods: 'Tentaperioder',
reexamPeriods: 'Omtentaperioder'
},
examPeriodLabel: 'Tentaperiod',
reexamPeriodLabel: 'Omtentaperiod',
period: 'Läsperiod',
start: 'Start',
lectureEnd: 'Föreläsningar slutar',
end: 'Slut',
exam: 'Tenta',
reexam: 'Omtenta',
year: 'År',
credits: 'hp',
teacher: 'Lärare',
viewCourse: 'kurshemsida',
viewSchedule: 'schema',
requires: 'Särskild behörighet',
requiredFor: 'Krävs för',
totalCredits: 'Totalt',
options: 'Alternativ',
months: ['jan','feb','mar','apr','maj','jun','jul','aug','sep','okt','nov','dec']
},
en: {
legend: {
exams: 'Exams',
reexams: 'Re-exams',
prerequisitesCompleted: 'Requires completion',
prerequisitesParticipation: 'Requires participation',
courses: 'Courses',
studyPeriods: 'Study periods',
examPeriods: 'Exam periods',
reexamPeriods: 'Re-exam periods'
},
examPeriodLabel: 'Exam period',
reexamPeriodLabel: 'Re-exam period',
period: 'Study period',
start: 'Start',
lectureEnd: 'Lecture end',
end: 'End',
exam: 'Exam',
reexam: 'Re-exam',
year: 'Year',
credits: 'ECTS',
teacher: 'Teacher',
viewCourse: 'course webpage',
viewSchedule: 'schedule',
requires: 'Requires',
requiredFor: 'Required for',
totalCredits: 'Total',
options: 'Options',
months: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
}
} as const;
const TimelineVisualization = forwardRef(function TimelineVisualization({ courses, language = 'sv', programName, programCode, studyplanUrl, programComment, cosmetics }: TimelineVisualizationProps, ref: React.ForwardedRef<TimelineVisualizationHandle>) {
const containerRef = useRef<HTMLDivElement>(null);
const svgRef = useRef<SVGSVGElement>(null);
// Preserve the initial chart height to keep a stable px-per-ECTS baseline across re-renders/toggles
const initialChartHeightRef = useRef<number | null>(null);
// Year focus state for highlighting a whole year
const [focusYear, setFocusYear] = useState<number | null>(null);
// Option group modal state
const [selectedOptionGroup, setSelectedOptionGroup] = useState<OptionGroup | null>(null);
// Track which option is currently highlighted in the modal
const [highlightedOptionCode, setHighlightedOptionCode] = useState<string | null>(null);
// Track user's selection: which course was chosen for each option group
// Maps option group name -> selected course code
const [selectedOptionPerGroup, setSelectedOptionPerGroup] = useState<Record<string, string>>({});
// When the modal opens/closes, reset or initialize highlighting.
// selectedOptionPerGroup is intentionally excluded: we only want to react to the
// modal open/close event, not to individual option selections within the modal.
useEffect(() => {
if (selectedOptionGroup) {
const currentSelection = selectedOptionPerGroup[selectedOptionGroup.name];
setHighlightedOptionCode(currentSelection || null);
} else {
setHighlightedOptionCode(null);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedOptionGroup]);
// Marker visual parameters - centralized for consistency
const EXAM_MARKER_RADIUS = 4;
const EXAM_MARKER_STROKE_WIDTH = 1;
const REEXAM_MARKER_RADIUS = 4;
const REEXAM_MARKER_STROKE_WIDTH = 1;
// Per-course color selection within a cosmetics group (depends only on cosmetics prop)
const getCourseColors = useCallback((course: Course) => {
const group = cosmetics?.courseToGroup.get(course.code);
if (!group) return defaultColor;
const variants = getFamilyVariants(group.colorFamily);
const idxInGroup = (group.courses || []).findIndex(c => c === course.code);
const baseIndex = idxInGroup >= 0 ? idxInGroup : Array.from(course.code).reduce((s, ch) => s + ch.charCodeAt(0), 0);
const variant = variants[baseIndex % variants.length];
return variant || getColorForFamily(group.colorFamily);
}, [cosmetics]);
// expose methods to parent via ref
useImperativeHandle(ref, () => ({
exportChart: async (format: 'png' | 'svg' | 'pdf', options?: { includeLegend?: boolean }) => {
if (!svgRef.current) return;
const svgEl = svgRef.current;
// Measure the on-screen SVG in CSS pixels
const svgRect = svgEl.getBoundingClientRect();
const exportWidth = Math.max(1, Math.round(svgRect.width));
const exportHeight = Math.max(1, Math.round(svgRect.height));
// Clone the SVG so we don't change the live DOM
const cloned = svgEl.cloneNode(true) as SVGSVGElement;
cloned.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
// Set explicit pixel dimensions on the cloned SVG so the rasterizer uses them
cloned.setAttribute('width', String(exportWidth));
cloned.setAttribute('height', String(exportHeight));
cloned.setAttribute('viewBox', `0 0 ${exportWidth} ${exportHeight}`);
// Ensure font family is applied for all text in export
cloned.setAttribute('style', `font-family: ${STYLE.fontFamily};`);
try {
const styleEl = document.createElementNS('http://www.w3.org/2000/svg', 'style');
styleEl.textContent = `* { font-family: ${STYLE.fontFamily}; }`;
cloned.insertBefore(styleEl, cloned.firstChild);
// Extract font families from the font stack and try to inline web fonts
// Parse font families from STYLE.fontFamily (e.g., "Figtree, ui-sans-serif, system-ui, ...")
const fontFamilies = STYLE.fontFamily.split(',').map(f => f.trim().replace(/['"]/g, ''));
// Try to fetch and embed web fonts (currently supports Google Fonts)
for (const fontFamily of fontFamilies) {
// Skip generic and system fonts
if (['ui-sans-serif', 'system-ui', 'sans-serif', 'serif', 'monospace', '-apple-system',
'Segoe UI', 'Roboto', 'Helvetica', 'Arial', 'Noto Sans'].some(s => fontFamily.includes(s))) {
continue;
}
try {
// Try to fetch from Google Fonts (works for common web fonts)
const fontUrl = `https://fonts.googleapis.com/css2?family=${encodeURIComponent(fontFamily)}:wght@300;400;500;600;700;800;900&display=swap`;
const cssResp = await fetch(fontUrl);
if (cssResp.ok) {
const cssText = await cssResp.text();
// Match all font URLs (for different weights)
const matches = cssText.matchAll(/url\((https:[^)]+\.(?:woff2|woff|ttf))\)/g);
const fontUrls = Array.from(matches).map(m => m[1]);
if (fontUrls.length > 0) {
// Fetch and embed all font files
for (const fontFileUrl of fontUrls) {
const fontResp = await fetch(fontFileUrl);
if (fontResp.ok) {
const buf = await fontResp.arrayBuffer();
const u8 = new Uint8Array(buf);
let binary = '';
for (let i = 0; i < u8.length; i++) binary += String.fromCharCode(u8[i]);
const fontBase64 = btoa(binary);
// Determine format from URL
const format = fontFileUrl.includes('.woff2') ? 'woff2' :
fontFileUrl.includes('.woff') ? 'woff' : 'truetype';
const fontStyle = document.createElementNS('http://www.w3.org/2000/svg', 'style');
fontStyle.textContent = `@font-face { font-family: '${fontFamily}'; src: url(data:font/${format};base64,${fontBase64}) format('${format}'); font-weight: 100 900; font-style: normal; }`;
cloned.insertBefore(fontStyle, cloned.firstChild);
}
}
break; // Successfully embedded a font, no need to try others
}
}
} catch {
// Continue to next font family if this one fails
}
}
} catch {}
// Optionally add an SVG legend into the cloned SVG for export
if (options?.includeLegend) {
try {
const NS = 'http://www.w3.org/2000/svg';
const legendPadding = 8;
const itemGap = 8;
const itemHeight = 18;
const items = [
{ key: tr[language].legend.exams, type: 'exam', active: layers.exams },
{ key: tr[language].legend.reexams, type: 'reexam', active: layers.reexams },
{ key: tr[language].legend.prerequisitesCompleted, type: 'prereqCompleted', active: layers.prereqCompleted },
{ key: tr[language].legend.prerequisitesParticipation, type: 'prereqParticipated', active: layers.prereqParticipation },
{ key: tr[language].legend.courses, type: 'course', active: layers.courseBars },
{ key: tr[language].legend.studyPeriods, type: 'study', active: layers.studyPeriods },
{ key: tr[language].legend.examPeriods, type: 'examPeriod', active: layers.examPeriods },
{ key: tr[language].legend.reexamPeriods, type: 'reexamPeriod', active: layers.reexamPeriods },
];
// container group
const legendG = document.createElementNS(NS, 'g');
// estimate width
const legendWidth = STYLE.legend.width;
const legendHeight = legendPadding*2 + items.length * (itemHeight + itemGap) - itemGap;
const svgW = exportWidth;
const svgH = exportHeight;
const legendX = svgW - legendWidth - STYLE.legend.offsetX;
const legendY = svgH - legendHeight - STYLE.legend.offsetY;
legendG.setAttribute('transform', `translate(${legendX},${legendY})`);
// background
const bg = document.createElementNS(NS, 'rect');
bg.setAttribute('x', '0');
bg.setAttribute('y', '0');
bg.setAttribute('width', String(legendWidth));
bg.setAttribute('height', String(legendHeight));
bg.setAttribute('rx', '8');
bg.setAttribute('ry', '8');
bg.setAttribute('fill', 'white');
bg.setAttribute('stroke', STYLE.legend.borderColor);
legendG.appendChild(bg);
// add rows
items.forEach((item, idx) => {
const rowG = document.createElementNS(NS, 'g');
rowG.setAttribute('transform', `translate(${legendPadding},${legendPadding + idx * (itemHeight + itemGap)})`);
rowG.setAttribute('opacity', item.active ? '1' : '0.4');
// icon
if (item.type === 'exam') {
const c = document.createElementNS(NS, 'circle');
c.setAttribute('cx', '9');
c.setAttribute('cy', String(itemHeight/2));
c.setAttribute('r', '6');
c.setAttribute('fill', kthColors.KthLightBrick?.HEX || '#FFCCC4');
c.style.stroke = kthColors.KthDarkBrick?.HEX || '#B35A4A';
c.style.strokeWidth = '1.5';
rowG.appendChild(c);
} else if (item.type === 'reexam') {
const c = document.createElementNS(NS, 'circle');
c.setAttribute('cx', '9');
c.setAttribute('cy', String(itemHeight/2));
c.setAttribute('r', '6');
c.setAttribute('fill', kthColors.KthLightBrick?.HEX || '#FFCCC4');
c.style.stroke = kthColors.KthDarkBrick?.HEX || '#B35A4A';
c.style.strokeWidth = '1.5';
c.style.strokeDasharray = '3 2';
rowG.appendChild(c);
} else if (item.type === 'prereqCompleted') {
const line = document.createElementNS(NS, 'line');
line.setAttribute('x1', '0');
line.setAttribute('y1', String(itemHeight/2));
line.setAttribute('x2', '18');
line.setAttribute('y2', String(itemHeight/2));
line.setAttribute('stroke', '#999');
line.setAttribute('stroke-width', '1.5');
rowG.appendChild(line);
} else if (item.type === 'prereqParticipated') {
const line = document.createElementNS(NS, 'line');
line.setAttribute('x1', '0');
line.setAttribute('y1', String(itemHeight/2));
line.setAttribute('x2', '18');
line.setAttribute('y2', String(itemHeight/2));
line.setAttribute('stroke', kthColors.KthBlue?.HEX || '#004791');
line.setAttribute('stroke-width', '1.5');
line.setAttribute('stroke-dasharray', '4,3');
rowG.appendChild(line);
} else if (item.type === 'course') {
const r = document.createElementNS(NS, 'rect');
r.setAttribute('x', '0');
r.setAttribute('y', String((itemHeight-12)/2));
r.setAttribute('width', '18');
r.setAttribute('height', '12');
r.setAttribute('fill', kthColors.KthHeaven?.HEX || '#6298D2');
r.setAttribute('stroke', 'rgba(0,0,0,0.06)');
rowG.appendChild(r);
} else if (item.type === 'study') {
const r = document.createElementNS(NS, 'rect');
r.setAttribute('x', '0');
r.setAttribute('y', String((itemHeight-12)/2));
r.setAttribute('width', '18');
r.setAttribute('height', '12');
r.setAttribute('fill', kthColors.KthSand?.HEX || '#f3f4f6');
r.setAttribute('stroke', 'rgba(0,0,0,0.06)');
rowG.appendChild(r);
} else if (item.type === 'examPeriod') {
const r = document.createElementNS(NS, 'rect');
r.setAttribute('x', '0');
r.setAttribute('y', String((itemHeight-12)/2));
r.setAttribute('width', '18');
r.setAttribute('height', '12');
r.setAttribute('fill', (kthColors.KthLightBlue?.HEX || '#DEF0FF'));
r.setAttribute('stroke', 'rgba(0,0,0,0.06)');
rowG.appendChild(r);
} else if (item.type === 'reexamPeriod') {
const r = document.createElementNS(NS, 'rect');
r.setAttribute('x', '0');
r.setAttribute('y', String((itemHeight-12)/2));
r.setAttribute('width', '18');
r.setAttribute('height', '12');
r.setAttribute('fill', kthColors.KthLightGray?.HEX || '#eee');
r.setAttribute('stroke', 'rgba(0,0,0,0.06)');
rowG.appendChild(r);
}
// label
const text = document.createElementNS(NS, 'text');
text.setAttribute('x', '26');
text.setAttribute('y', String(itemHeight/2 + 4));
text.setAttribute('fill', STYLE.legend.textColor);
text.setAttribute('font-size', '12');
text.textContent = item.key;
rowG.appendChild(text);
legendG.appendChild(rowG);
});
// Add course groups if cosmetics available
if (cosmetics && cosmetics.groups.length > 0) {
// defs for gradients
const defs = document.createElementNS(NS, 'defs');
legendG.appendChild(defs);
let currentIdx = items.length;
// Add a separator line
const separatorY = legendPadding + currentIdx * (itemHeight + itemGap) - itemGap/2;
const separatorLine = document.createElementNS(NS, 'line');
separatorLine.setAttribute('x1', String(legendPadding));
separatorLine.setAttribute('y1', String(separatorY));
separatorLine.setAttribute('x2', String(legendWidth - legendPadding));
separatorLine.setAttribute('y2', String(separatorY));
separatorLine.setAttribute('stroke', '#e5e7eb');
separatorLine.setAttribute('stroke-width', '1');
legendG.appendChild(separatorLine);
currentIdx++; // account for separator space
cosmetics.groups.forEach((group, gIdx) => {
const variants = getFamilyVariants(group.colorFamily);
const rowG = document.createElementNS(NS, 'g');
rowG.setAttribute('transform', `translate(${legendPadding},${legendPadding + (currentIdx + gIdx) * (itemHeight + itemGap)})`);
// Make group header clickable: add a transparent rect for hit area
const hitRect = document.createElementNS(NS, 'rect');
hitRect.setAttribute('x', '0');
hitRect.setAttribute('y', '0');
hitRect.setAttribute('width', String(legendWidth - legendPadding * 2));
hitRect.setAttribute('height', String(itemHeight));
hitRect.setAttribute('fill', 'transparent');
hitRect.setAttribute('cursor', 'pointer');
hitRect.addEventListener('click', () => toggleGroup(group.name));
rowG.appendChild(hitRect);
const r = document.createElementNS(NS, 'rect');
r.setAttribute('x', '0');
r.setAttribute('y', String((itemHeight-12)/2));
r.setAttribute('width', '18');
r.setAttribute('height', '12');
// Create linear gradient for this group
const gradId = `legendGrad_${gIdx}`;
const lg = document.createElementNS(NS, 'linearGradient');
lg.setAttribute('id', gradId);
lg.setAttribute('x1', '0%');
lg.setAttribute('y1', '0%');
lg.setAttribute('x2', '100%');
lg.setAttribute('y2', '0%');
const n = Math.max(1, variants.length);
variants.forEach((v, i) => {
const start = Math.round((i / n) * 100);
const end = Math.round(((i + 1) / n) * 100);
const s1 = document.createElementNS(NS, 'stop');
s1.setAttribute('offset', `${start}%`);
s1.setAttribute('stop-color', v.fill);
const s2 = document.createElementNS(NS, 'stop');
s2.setAttribute('offset', `${end}%`);
s2.setAttribute('stop-color', v.fill);
lg.appendChild(s1);
lg.appendChild(s2);
});
defs.appendChild(lg);
r.setAttribute('fill', `url(#${gradId})`);
r.setAttribute('stroke', (variants[0]?.stroke) || '#999');
rowG.appendChild(r);
const text = document.createElementNS(NS, 'text');
text.setAttribute('x', '26');
text.setAttribute('y', String(itemHeight/2 + 4));
text.setAttribute('fill', STYLE.legend.textColor);
text.setAttribute('font-size', '12');
text.textContent = language === 'en' ? (group.nameEn || group.name) : group.name;
rowG.appendChild(text);
legendG.appendChild(rowG);
});
// Update legend height to include groups
const totalItems = items.length + 1 + cosmetics.groups.length; // +1 for separator
const newLegendHeight = legendPadding*2 + totalItems * (itemHeight + itemGap) - itemGap;
bg.setAttribute('height', String(newLegendHeight));
// Reposition to stay in bottom-right
const newLegendY = svgH - newLegendHeight - STYLE.legend.offsetY;
legendG.setAttribute('transform', `translate(${legendX},${newLegendY})`);
}
// append legend to cloned
cloned.appendChild(legendG);
} catch (e) {
console.warn('Failed to add legend to export', e);
}
}
// Optionally add a bottom comment into the cloned SVG for export
if (programComment && programComment.trim().length > 0) {
try {
const NS = 'http://www.w3.org/2000/svg';
const commentText = document.createElementNS(NS, 'text');
// place inside left margin area at bottom
const x = 12; // small left padding within SVG
const y = exportHeight - 8; // a few pixels from bottom
commentText.setAttribute('x', String(x));
commentText.setAttribute('y', String(y));
commentText.setAttribute('fill', '#6b7280');
commentText.setAttribute('font-size', '11');
commentText.textContent = programComment;
cloned.appendChild(commentText);
} catch {
// ignore comment failures
}
}
const serializer = new XMLSerializer();
const svgString = serializer.serializeToString(cloned);
if (format === 'svg') {
const blob = new Blob([svgString], { type: 'image/svg+xml;charset=utf-8' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'program-visualization.svg';
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
return;
}
// PDF export: use Puppeteer via API for perfect font rendering
if (format === 'pdf') {
// Create a complete HTML document with embedded SVG and fonts
const htmlDoc = `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
@import url('https://fonts.googleapis.com/css2?family=Figtree:wght@300;400;500;600;700;800;900&display=swap');
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Figtree, ui-sans-serif, system-ui, -apple-system, sans-serif;
}
@page {
size: ${exportWidth}px ${exportHeight}px;
margin: 0;
}
svg {
display: block;
width: ${exportWidth}px;
height: ${exportHeight}px;
}
</style>
</head>
<body>
${svgString}
</body>
</html>`;
try {
const response = await fetch('/api/export-pdf', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ html: htmlDoc })
});
if (!response.ok) {
const errorText = await response.text();
console.error('PDF export failed:', errorText);
alert('PDF export failed: ' + errorText);
return;
}
const pdfBlob = await response.blob();
const url = URL.createObjectURL(pdfBlob);
const a = document.createElement('a');
a.href = url;
a.download = 'program-visualization.pdf';
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
} catch (error) {
console.error('PDF export error:', error);
alert('PDF export failed. Check console for details.');
}
return;
}
// Convert to PNG via canvas
const svg64 = btoa(unescape(encodeURIComponent(svgString)));
const image64 = 'data:image/svg+xml;base64,' + svg64;
const img = new Image();
img.crossOrigin = 'anonymous';
img.onload = () => {
// Use devicePixelRatio to create a higher-resolution export (clamped)
const dpr = typeof window !== 'undefined' ? (window.devicePixelRatio || 1) : 1;
const scale = Math.min(4, Math.max(1, dpr * 2)); // e.g. DPR 1 -> 2, DPR 2 -> 4 (clamped at 4)
const canvas = document.createElement('canvas');
canvas.width = Math.round(exportWidth * scale);
canvas.height = Math.round(exportHeight * scale);
// keep CSS size equal to logical SVG size
canvas.style.width = `${exportWidth}px`;
canvas.style.height = `${exportHeight}px`;
const ctx = canvas.getContext('2d');
if (!ctx) return;
// Map drawing so that 1 unit = 1 CSS px in SVG space, while canvas pixels are scaled
ctx.setTransform(scale, 0, 0, scale, 0, 0);
// Fill white background in SVG coordinates
ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, exportWidth, exportHeight);
// Draw the SVG raster (img) into SVG coordinate space
ctx.drawImage(img, 0, 0, exportWidth, exportHeight);
// PNG export
canvas.toBlob((blob) => {
if (!blob) return;
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'program-visualization.png';
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
}, 'image/png');
};
img.src = image64;
}
}));
// layer visibility state
const [layers, setLayers] = useState(() => {
const base = {
exams: true,
reexams: true,
prereqCompleted: true,
prereqParticipation: true,
courseBars: true,
studyPeriods: true,
examPeriods: true,
reexamPeriods: true,
groups: {} as Record<string, boolean>
};
if (cosmetics && cosmetics.groups) {
cosmetics.groups.forEach(g => { base.groups[g.name] = true; });
}
return base;
});
// Handler to toggle group visibility
const toggleGroup = (groupName: string) => {
setLayers(l => ({
...l,
groups: {
...l.groups,
[groupName]: l.groups[groupName] === false ? true : false
}
}));
};
// focused course code for fading non-relevant elements
const [focusCourse, setFocusCourse] = useState<string | null>(null);
// Info panel selection
const [selectedInfo, setSelectedInfo] = useState<{
course: Course;
credit?: { period: string; credits: number; year: number };
} | null>(null);
useEffect(() => {
if (!svgRef.current || !containerRef.current || !courses.length) return;
const container = d3.select(containerRef.current);
// setup tooltip container
container.selectAll('.pv-tooltip').remove();
const tooltip = container.append('div')
.attr('class', 'pv-tooltip')
.style('position', 'absolute')
.style('pointer-events', 'none')
.style('display', 'none')
.style('background', `rgba(${(kthColors.KthMarine?.RGB || [0, 0, 97]).join(',')}, 0.8)`)
.style('color', '#fff')
.style('padding', '6px 8px')
.style('border-radius', '4px')
.style('font-size', '12px')
.style('z-index', '1001');
const svg = d3.select(svgRef.current);
// Apply global font family to all SVG text
svg.style('font-family', STYLE.fontFamily);
const margin = { top: 100, right: 40, bottom: 40, left: 100 }; // Increased top margin for title and period labels
const width = svgRef.current.clientWidth - margin.left - margin.right;
let height = svgRef.current.clientHeight - margin.top - margin.bottom;
if (initialChartHeightRef.current == null) {
initialChartHeightRef.current = height;
}
// Clear previous content
svg.selectAll('*').remove();
// Create SVG defs for patterns (option group stripes)
const defs = svg.append('defs');
// Create a striped pattern for each option group using colors of its option courses
courses.filter(isOptionGroup).forEach(og => {
const optionGroup = og as OptionGroup;
const patternId = `option-group-pattern-${optionGroup.name.replace(/\s+/g, '-')}`;
// Get colors for each option course
const optionColors = optionGroup.options
.map(optionCode => {
const optionCourse = courses.find(c => isCourse(c) && (c as Course).code === optionCode) as Course | undefined;
return optionCourse ? getCourseColors(optionCourse).fill : null;
})
.filter(color => color !== null) as string[];
// Create diagonal striped pattern at 45 degrees
if (optionColors.length > 0) {
const stripeWidth = 16; // Width of each diagonal stripe
const pattern = defs.append('pattern')
.attr('id', patternId)
.attr('patternUnits', 'userSpaceOnUse')
.attr('width', optionColors.length * stripeWidth)
.attr('height', optionColors.length * stripeWidth)
.attr('patternTransform', 'rotate(45)');
// Add a rect for each color
optionColors.forEach((color, index) => {
pattern.append('rect')
.attr('x', index * stripeWidth)
.attr('y', 0)
.attr('width', stripeWidth)
.attr('height', '100%')
.attr('fill', color);
});
}
});
const g = svg.append('g')
.attr('transform', `translate(${margin.left},${margin.top})`); // Create scales
const timeScale = d3.scaleTime()
.domain([academicPeriods[0].start, academicPeriods[3].reExamEnd])
.range([0, width]);
// Clicking on empty SVG space clears focus and closes popup
svg.on('click', () => {
setFocusCourse(null);
setSelectedInfo(null);
setFocusYear(null);
});
const maxYear = Math.max(1, ...courses.flatMap(c => {
if (isCourse(c)) {
return c.credits.map(cr => cr.year || c.year || 1);
} else {
return [(c as OptionGroup).year || 1];
}
}));
const numYears = Math.max(1, maxYear);
// Separate option groups and individual courses, and identify courses that should be hidden
const optionGroups = courses.filter(isOptionGroup);
const coursesInOptionGroups = new Set<string>();
optionGroups.forEach(og => {
og.options.forEach(optionCode => {
// Don't hide courses that have been selected as the chosen option
if (selectedOptionPerGroup[og.name] !== optionCode) {
coursesInOptionGroups.add(optionCode);
}
});
});
// Filter courses to only include individual courses (not in option groups)
const individualCourses = courses.filter(c => {
if (isOptionGroup(c)) return false;
return !coursesInOptionGroups.has((c as Course).code);
}) as Course[];
// Combine individual courses with option groups for rendering (selected courses are now in individualCourses)
const displayItems: Array<Course | OptionGroup> = [
...individualCourses,
...optionGroups.filter(og => !selectedOptionPerGroup[og.name])
];
// Increased vertical gap between year rows (px)
// Increase inter-year gap by 20% (from 48 to ~57.6). Use integer for pixel grid.
const yearRowGap = 58; // was 48
const totalGaps = Math.max(0, numYears - 1) * yearRowGap;
// Base band height from current SVG height, used to derive a baseline pixels-per-ECTS
// Use the initial chart height for baseline band height so layer toggles don't create feedback loops
const baseYearBandHeight = ((initialChartHeightRef.current || height) - totalGaps) / numYears;
// Baseline pixels per ECTS (15 ECTS previously mapped to a year band)
const pxPerECTS = baseYearBandHeight / 15;
// Minimum ECTS to enforce for bar height so labels fit nicely
const MIN_ECTS_FOR_HEIGHT = 2;
const STACK_GAP_PX = 4; // gap between stacked bars
// Build mapping of courses per year+period to compute stacking lanes (needed for sizing and layout)
const slotsByYearPeriod: Record<string, Array<{ item: Course | OptionGroup; credit: { period: string; credits: number; year: number } }>> = {};
displayItems.forEach((item) => {
const credits = isCourse(item) ? item.credits : Object.entries((item as OptionGroup).periodCredits)
.filter(([, credits]) => credits > 0)
.map(([period, credits]) => ({
period: period as 'P1' | 'P2' | 'P3' | 'P4',
credits,
year: (item as OptionGroup).year
}));
credits.forEach((credit) => {
const key = `${credit.year}-${credit.period}`;
if (!slotsByYearPeriod[key]) slotsByYearPeriod[key] = [];
slotsByYearPeriod[key].push({ item, credit });
});
});
// Compute required band height per year considering the minimum bar height corresponding to 2 ECTS
const yearBandHeights: number[] = Array.from({ length: numYears }, () => 0);
for (let y = 1; y <= numYears; y++) {
// for this year, find all 4 periods
let maxPeriodHeightNeeded = 0;
academicPeriods.forEach((p) => {
const list = slotsByYearPeriod[`${y}-${p.id}`] || [];
if (list.length === 0) return;
const heightSum = list.reduce((sum, it) => {
const effECTS = Math.max(it.credit.credits, MIN_ECTS_FOR_HEIGHT);
return sum + effECTS * pxPerECTS;
}, 0);
const gaps = Math.max(0, list.length - 1) * STACK_GAP_PX;
maxPeriodHeightNeeded = Math.max(maxPeriodHeightNeeded, heightSum + gaps);
});
// Ensure at least the baseline height is kept, even if no courses
yearBandHeights[y - 1] = Math.max(baseYearBandHeight, maxPeriodHeightNeeded);
}
// If required total height exceeds current height, expand the SVG to fit to avoid compressing bars below the minimum
const requiredTotalHeight = yearBandHeights.reduce((a, b) => a + b, 0) + totalGaps;
if (requiredTotalHeight > height) {
height = requiredTotalHeight;
// also set explicit height on the SVG node so layout picks it up
d3.select(svgRef.current)
.attr('height', height + margin.top + margin.bottom);
}
// Compute cumulative Y offsets per year using the (possibly) expanded band heights
const yearYOffset: number[] = [];
for (let i = 0; i < numYears; i++) {
const prev = i === 0 ? 0 : (yearYOffset[i - 1] + yearBandHeights[i - 1] + yearRowGap);
yearYOffset.push(prev);
}
const verticalOffset = 0;
const periodExtension = 10; // How much the period backgrounds extend beyond course area (reduced for better alignment)
// Draw program title first (at the top)
if (programName && programCode) {
const title = g.append('text')
.attr('x', width / 2)
.attr('y', -75)
.attr('text-anchor', 'middle')
.attr('fill', kthColors.KthBlue?.HEX)
.attr('font-weight', 400)
.attr('font-size', 18);
title.append('tspan').text(`${programName} `);
const codeText = `(${programCode})`;
const linkUrl = studyplanUrl ? (language === 'en' ? `${studyplanUrl}?l=en` : studyplanUrl) : undefined;
if (linkUrl) {
const anchor = title.append('a')
.attr('href', linkUrl)
.attr('target', '_blank');
anchor.append('tspan')
.text(codeText)
.attr('fill', kthColors.KthHeaven?.HEX || '#6298D2')
.style('text-decoration', 'none')
.style('cursor', 'pointer');
} else {
title.append('tspan')
.text(codeText);
}
}
// Draw period backgrounds with extension above and below
academicPeriods.forEach((period, i) => {
const periodHeight = height + 2 * periodExtension;
const yOffset = -periodExtension;
// Main period background
g.append('rect')
.attr('x', timeScale(period.start))
.attr('y', yOffset)
.attr('width', timeScale(period.lectureEnd) - timeScale(period.start))
.attr('height', periodHeight)
.attr('class', 'study-period')
.attr('fill', (kthColors.KthSand?.HEX ? d3.color(kthColors.KthSand.HEX)!.copy({ opacity: 0.25 }).formatRgb() : 'rgba(235,229,224,0.25)'))
.attr('stroke', 'none')
.on('mouseover', () => {
tooltip.html(`
<strong>${tr[language].period} P${i + 1}</strong>
`).style('display', 'block');
})
.on('mousemove', (event: MouseEvent) => {
tooltip.style('left', (event.pageX + 50) + 'px').style('top', (event.pageY + 50) + 'px');
})
.on('mouseout', () => tooltip.style('display', 'none'));
// Add period label (P1, P2, etc.)
g.append('text')
.attr('x', timeScale(period.start) + (timeScale(period.lectureEnd) - timeScale(period.start)) / 2)
.attr('y', -50) // Increased distance from the period fields
.attr('text-anchor', 'middle')
.attr('fill', kthColors.KthBlue?.HEX)
.attr('font-weight', 400)
.attr('font-size', 14)
.text(`P${i + 1}`);
});
// Month labels across the whole timeline
{
const start = academicPeriods[0].start;
const end = academicPeriods[academicPeriods.length - 1].reExamEnd;
const months: Date[] = [];
const d = new Date(start.getFullYear(), start.getMonth(), 1);
while (d <= end) {
months.push(new Date(d));
d.setMonth(d.getMonth() + 1);
}
// vertical month boundary lines with same gray and roughly label height
const monthLabelY = -28;
const labelHeight = 12;
months.forEach((md, idx) => {
if (idx > 0) {
const xBoundary = timeScale(new Date(md.getFullYear(), md.getMonth(), 1));
g.append('line')
.attr('x1', xBoundary)
.attr('y1', monthLabelY - labelHeight / 2)
.attr('x2', xBoundary)
.attr('y2', monthLabelY + labelHeight / 2)
.attr('stroke', '#f0f2f5ff')
.attr('stroke-width', 5);
}
});
months.forEach((md) => {
const label = tr[language].months[md.getMonth()];
// position in the middle of the month
const monthStart = new Date(md.getFullYear(), md.getMonth(), 1);
const monthEnd = new Date(md.getFullYear(), md.getMonth() + 1, 0);
const mid = new Date((monthStart.getTime() + monthEnd.getTime()) / 2);
g.append('text')
.attr('x', timeScale(mid))
.attr('y', monthLabelY)
.attr('text-anchor', 'middle')
.attr('fill', '#9ca3af')
.attr('font-size', 10)
.text(label);
});
}
// Draw exam periods with extension above and below
academicPeriods.forEach(period => {
const examHeight = height + 2 * periodExtension;
const yOffset = -periodExtension;
// Regular exam period (subtle KTH light blue)
g.append('rect')
.attr('x', timeScale(period.examStart))
.attr('y', yOffset)
.attr('width', timeScale(period.examEnd) - timeScale(period.examStart))