-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1386 lines (1211 loc) · 52.9 KB
/
script.js
File metadata and controls
1386 lines (1211 loc) · 52.9 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
// Singapore Budget Speeches - Storytelling Visualization
// Inspired by Pudding.cool's democracy piece
// =============================================================================
// CONSTANTS - No more magic numbers
// =============================================================================
const TIMING = {
HOVER_PANEL_HIDE_DELAY: 500,
INTERACTIVE_MODE_DELAY: 300,
INTERACTIVE_MODE_COOLDOWN: 1000,
WHEEL_RESET_TIMEOUT: 500,
CUMULATIVE_WHEEL_THRESHOLD: 500,
RESIZE_DEBOUNCE: 250
};
const DATA_URLS = {
VIZ: 'data/viz_data.json',
STORY: 'data/curated_story.json',
TRENDS: 'data/word_trends.json'
};
// =============================================================================
// STATE - Module-scoped, not global window.*
// =============================================================================
let vizData = null;
let storyData = null;
let wordTrendsData = null;
let svg = null;
let dots = null;
let currentSection = null;
let filteredParagraphs = null;
let yearPositions = {};
let interactiveModeCooldown = false;
let interactiveModeTimeout = null;
let hoverPanelTimeout = null;
let selectedDot = null;
// Touch event listener references for cleanup
let touchEventListeners = {
start: null,
move: null,
end: null
};
// Cached DOM elements (initialized after DOMContentLoaded)
let domElements = {
currentEra: null,
currentContext: null,
progressFill: null,
timelineViz: null,
scrollSections: null,
hoverPanel: null,
exploreSection: null
};
// Initialize cached DOM elements
function initDomElements() {
domElements.currentEra = document.querySelector('.current-era');
domElements.currentContext = document.querySelector('.current-context');
domElements.progressFill = document.querySelector('.progress-fill');
domElements.timelineViz = document.getElementById('timeline-viz');
domElements.scrollSections = document.getElementById('scroll-sections');
domElements.hoverPanel = document.getElementById('hover-panel');
domElements.exploreSection = document.querySelector('[data-step="explore"]');
}
// Responsive sizing helper
function getResponsiveConfig() {
const width = window.innerWidth;
const isMobile = width <= 768;
const isSmallMobile = width <= 480;
return {
dotSize: isSmallMobile ? 2.2 : (isMobile ? 2.8 : 3.3),
dotGap: isSmallMobile ? 0.3 : (isMobile ? 0.4 : 0.6),
marginTop: isSmallMobile ? 85 : (isMobile ? 95 : 240),
marginRight: isMobile ? 10 : 25,
marginBottom: isSmallMobile ? 30 : (isMobile ? 40 : 50),
marginLeft: isMobile ? 10 : 25,
hideAnnotations: isMobile,
maxCols: isSmallMobile ? 4 : (isMobile ? 5 : 6),
isMobile: isMobile,
isSmallMobile: isSmallMobile,
hideSvgLegend: isMobile, // Hide SVG legend on mobile, use CSS legend
fontSize: {
year: isSmallMobile ? '7px' : (isMobile ? '8px' : '10px'),
legend: isSmallMobile ? '8px' : (isMobile ? '9px' : '10.5px'),
event: isSmallMobile ? '7px' : (isMobile ? '8px' : '9px')
}
};
}
// =============================================================================
// TOUCH EVENT HANDLING - With proper cleanup to prevent memory leaks
// =============================================================================
let touchState = {
active: false,
lastTouchedDot: null
};
function handleTouchMove(e) {
if (!e.touches || e.touches.length === 0) return;
const touch = e.touches[0];
const element = document.elementFromPoint(touch.clientX, touch.clientY);
// Check if element is a dot (SVG uses getAttribute for class)
const isDot = element && (
element.classList?.contains('dot') ||
element.getAttribute?.('class')?.includes('dot')
);
if (isDot && element !== touchState.lastTouchedDot) {
// Clear previous selection
if (selectedDot && selectedDot !== element) {
d3.select(selectedDot).classed('selected', false);
}
// Get the data bound to this element
const d = d3.select(element).datum();
if (d) {
selectedDot = element;
touchState.lastTouchedDot = element;
d3.select(element).classed('selected', true).raise();
showHoverPanel(d);
}
}
}
function setupTouchListeners(svgNode) {
// Clean up any existing listeners first
cleanupTouchListeners();
touchState.active = false;
touchState.lastTouchedDot = null;
touchEventListeners.start = function(e) {
if (!document.body.classList.contains('interactive-mode')) return;
touchState.active = true;
handleTouchMove(e);
};
touchEventListeners.move = function(e) {
if (!document.body.classList.contains('interactive-mode') || !touchState.active) return;
handleTouchMove(e);
};
touchEventListeners.end = function(e) {
if (!document.body.classList.contains('interactive-mode')) return;
touchState.active = false;
if (touchState.lastTouchedDot) {
pinQuote();
}
};
// Store reference to the node for cleanup
touchEventListeners.node = svgNode;
svgNode.addEventListener('touchstart', touchEventListeners.start, { passive: true });
svgNode.addEventListener('touchmove', touchEventListeners.move, { passive: true });
svgNode.addEventListener('touchend', touchEventListeners.end, { passive: true });
}
function cleanupTouchListeners() {
if (touchEventListeners.node) {
if (touchEventListeners.start) {
touchEventListeners.node.removeEventListener('touchstart', touchEventListeners.start);
}
if (touchEventListeners.move) {
touchEventListeners.node.removeEventListener('touchmove', touchEventListeners.move);
}
if (touchEventListeners.end) {
touchEventListeners.node.removeEventListener('touchend', touchEventListeners.end);
}
touchEventListeners.node = null;
}
}
// Prevent browser from restoring scroll position
if ('scrollRestoration' in history) {
history.scrollRestoration = 'manual';
}
// =============================================================================
// DATA FETCHING - With proper error handling
// =============================================================================
async function fetchJSON(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to fetch ${url}: ${response.status} ${response.statusText}`);
}
return response.json();
}
function showLoadingState() {
const container = document.getElementById('timeline-viz');
if (container) {
container.innerHTML = '<div style="display:flex;align-items:center;justify-content:center;height:100%;color:#7a7a7a;font-size:0.9rem;">Loading data...</div>';
}
}
function showErrorState(error) {
const container = document.getElementById('timeline-viz');
if (container) {
container.innerHTML = `<div style="display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;color:#C41E3A;font-size:0.9rem;text-align:center;padding:2rem;">
<p style="margin-bottom:0.5rem;">Failed to load data</p>
<p style="font-size:0.75rem;color:#7a7a7a;">${error.message}</p>
<button onclick="location.reload()" style="margin-top:1rem;padding:0.5rem 1rem;border:1px solid #C41E3A;background:transparent;color:#C41E3A;border-radius:4px;cursor:pointer;">Retry</button>
</div>`;
}
console.error('Data loading error:', error);
}
// Initialize
document.addEventListener('DOMContentLoaded', async () => {
// Cache DOM elements first
initDomElements();
// Scroll to top on page load
window.scrollTo(0, 0);
// Also scroll after a brief delay to override any browser restoration
setTimeout(() => window.scrollTo(0, 0), 100);
// Show loading state
showLoadingState();
try {
console.log('[Init] Fetching data...');
// Fetch all data with proper error handling
const [vizResult, storyResult, trendsResult] = await Promise.all([
fetchJSON(DATA_URLS.VIZ),
fetchJSON(DATA_URLS.STORY),
fetchJSON(DATA_URLS.TRENDS)
]);
console.log('[Init] Data fetched successfully');
vizData = vizResult;
storyData = storyResult;
wordTrendsData = trendsResult;
// Validate data structure
if (!vizData.paragraphs || !Array.isArray(vizData.paragraphs)) {
throw new Error('Invalid viz_data.json: missing paragraphs array');
}
if (!storyData.sections || !Array.isArray(storyData.sections)) {
throw new Error('Invalid curated_story.json: missing sections array');
}
console.log('[Init] Data validated');
// Add unique IDs for D3 keying if not present
filteredParagraphs = vizData.paragraphs
.filter(p => p.primary_value && p.primary_value !== 'none')
.map((p, idx) => ({ ...p, _uid: p.id || `para_${idx}` }));
console.log('[Init] Filtered paragraphs:', filteredParagraphs.length);
generateStorySections();
console.log('[Init] Story sections generated');
// Re-cache explore section after it's created by generateStorySections()
domElements.exploreSection = document.querySelector('[data-step="explore"]');
initVisualization();
console.log('[Init] Visualization initialized');
setupScrollTriggers();
setupButtonListeners();
console.log('[Init] Complete');
} catch (error) {
console.error('[Init] Error:', error);
showErrorState(error);
}
});
// Wire up button event listeners (replacing inline onclick)
function setupButtonListeners() {
const mobileBackBtn = document.getElementById('mobile-back-btn');
if (mobileBackBtn) {
mobileBackBtn.addEventListener('click', exitInteractiveModeAndScrollTop);
}
const hoverPanelClose = document.getElementById('hover-panel-close');
if (hoverPanelClose) {
hoverPanelClose.addEventListener('click', unpinQuote);
}
}
// Generate story sections from curated data
function generateStorySections() {
const container = domElements.scrollSections;
storyData.sections.forEach((section, index) => {
const el = document.createElement('section');
el.className = 'step';
el.dataset.step = section.id;
el.dataset.yearStart = section.year_range[0];
el.dataset.yearEnd = section.year_range[1];
let content = '';
if (section.type === 'word_trends_intro') {
// Introduction to word trends
content = `
<div class="step-content trends-intro-content">
${section.era_label ? `<span class="era-badge">${section.era_label}</span>` : ''}
<h3>${section.title}</h3>
<p class="setup">${section.setup}</p>
</div>
`;
} else if (section.type === 'stat_highlight') {
// Big stat highlight with bar chart
const stats = storyData.stats;
content = `
<div class="step-content stat-highlight-content">
${section.era_label ? `<span class="era-badge">${section.era_label}</span>` : ''}
${section.title ? `<h3>${section.title}</h3>` : ''}
<p class="setup">${section.setup}</p>
<div class="word-change-viz">
<div class="word-bars">
<div class="word-bar-row">
<span class="bar-label">${stats.then.year}</span>
<div class="bar-container">
<div class="bar bar-then" style="width: 4%"></div>
<span class="bar-value">${stats.headline.then_rate}</span>
</div>
</div>
<div class="word-bar-row">
<span class="bar-label">${stats.now.year}</span>
<div class="bar-container">
<div class="bar bar-now" style="width: 100%"></div>
<span class="bar-value">${stats.headline.now_rate}</span>
</div>
</div>
</div>
<div class="word-change-multiplier">${stats.headline.multiplier} increase</div>
<div class="word-change-unit">(mentions ${stats.headline.unit})</div>
</div>
${section.reflection ? `<p class="reflection">${section.reflection}</p>` : ''}
</div>
`;
} else if (section.type === 'pm_era_chart') {
// PM Era chart showing promises vs demands as stacked bars
const pmData = section.pm_data || [];
content = `
<div class="step-content pm-era-content">
${section.era_label ? `<span class="era-badge">${section.era_label}</span>` : ''}
${section.title ? `<h3>${section.title}</h3>` : ''}
${section.setup ? `<p class="setup">${section.setup}</p>` : ''}
<div class="pm-era-chart">
${pmData.map((d, i) => {
const total = d.promises + d.demands;
const promisePct = (d.promises / total) * 100;
const demandPct = (d.demands / total) * 100;
return `
<div class="pm-era-row">
<div class="pm-era-label">
<span class="pm-name">${d.pm}</span>
<span class="pm-years">${d.years}</span>
</div>
<div class="pm-era-bar-container stacked">
<div class="pm-era-bar-segment promises" style="width: ${promisePct}%">
<span class="segment-label">${d.promises}</span>
</div>
<div class="pm-era-bar-segment demands" style="width: ${demandPct}%">
<span class="segment-label">${d.demands}</span>
</div>
</div>
</div>
`}).join('')}
</div>
<div class="pm-era-legend">
<div class="pm-era-legend-item">
<span class="legend-color promises"></span>
<span>Promises</span>
</div>
<div class="pm-era-legend-item">
<span class="legend-color demands"></span>
<span>Demands</span>
</div>
</div>
${section.reflection ? `<p class="reflection">${section.reflection}</p>` : ''}
</div>
`;
} else if (section.type === 'decade_chart') {
// Decade chart showing promises vs demands as stacked bars
const decadeData = section.decade_data || [];
content = `
<div class="step-content decade-era-content">
${section.era_label ? `<span class="era-badge">${section.era_label}</span>` : ''}
${section.title ? `<h3>${section.title}</h3>` : ''}
${section.setup ? `<p class="setup">${section.setup}</p>` : ''}
<div class="decade-chart">
${decadeData.map((d, i) => {
const total = d.promises + d.demands;
const promisePct = (d.promises / total) * 100;
const demandPct = (d.demands / total) * 100;
return `
<div class="decade-row">
<div class="decade-label">
<span class="decade-name">${d.decade}</span>
</div>
<div class="decade-bar-container stacked">
<div class="decade-bar-segment promises" style="width: ${promisePct}%">
<span class="segment-label">${d.promises}</span>
</div>
<div class="decade-bar-segment demands" style="width: ${demandPct}%">
<span class="segment-label">${d.demands}</span>
</div>
</div>
</div>
`}).join('')}
</div>
<div class="decade-legend">
<div class="decade-legend-item">
<span class="legend-color promises"></span>
<span>Promises</span>
</div>
<div class="decade-legend-item">
<span class="legend-color demands"></span>
<span>Demands</span>
</div>
</div>
${section.reflection ? `<p class="reflection">${section.reflection}</p>` : ''}
</div>
`;
} else if (section.type === 'word_trends') {
// Word trends with sparklines
const trends = section.trend_type === 'rising' ? wordTrendsData.rising : wordTrendsData.declining;
const color = section.trend_type === 'rising' ? '#D35F5F' : '#3D5A80';
content = `
<div class="step-content trends-content ${section.trend_type}">
<span class="era-badge">${section.era_label}</span>
<h3>${section.title}</h3>
${section.setup ? `<p class="setup">${section.setup}</p>` : ''}
<div class="sparkline-grid" data-trend-type="${section.trend_type}">
${trends.slice(0, 9).map(w => `
<div class="sparkline-item">
<div class="sparkline-word">${w.word}</div>
<svg class="sparkline" data-values="${w.timeseries.map(d => d.per_10k).join(',')}" data-color="${color}"></svg>
<div class="sparkline-change ${section.trend_type}">${w.change > 0 ? '+' : ''}${w.change}</div>
</div>
`).join('')}
</div>
${section.reflection ? `<p class="reflection">${section.reflection}</p>` : ''}
</div>
`;
} else if (section.type === 'final') {
// Final section
content = `
<div class="step-content final-content">
<h3>${section.title}</h3>
<div class="final-text">${section.reflection.split('\n\n').map(p => `<p>${p}</p>`).join('')}</div>
</div>
`;
} else if (section.type === 'explore') {
// Final explore section - scrolls away to reveal interactive chart
el.classList.add('step-explore');
// Use different text for mobile (click) vs desktop (hover)
const isMobileDevice = window.innerWidth <= 768;
const exploreText = isMobileDevice
? 'Tap any square to see the paragraph it represents.'
: section.reflection;
content = `
<div class="step-content explore-content">
<span class="era-badge">${section.era_label}</span>
<h3>${section.title}</h3>
<div class="explore-text">${exploreText.split('\n\n').map(p => `<p>${p}</p>`).join('')}</div>
<div class="explore-hint">
<span class="hint-icon">↓</span>
<span>Keep scrolling, then hover over any square</span>
</div>
</div>
`;
} else if (section.type === 'fullscreen') {
// Full-screen interstitial - no card, just content
el.classList.add('step-fullscreen');
content = `
<div class="fullscreen-content">
${section.title ? `<h2 class="fullscreen-title">${section.title}</h2>` : ''}
${section.setup ? `<div class="fullscreen-text">${section.setup.split('\n\n').map(p => `<p>${p}</p>`).join('')}</div>` : ''}
</div>
`;
} else if (section.type === 'fm_table') {
// FM fingerprints table
const fmData = section.fm_words || [];
content = `
<div class="step-content fm-table-content">
${section.era_label ? `<span class="era-badge">${section.era_label}</span>` : ''}
${section.title ? `<h3>${section.title}</h3>` : ''}
${section.setup ? `<p class="setup">${section.setup}</p>` : ''}
<table class="fm-table">
<thead>
<tr><th>Era</th><th>Finance Minister</th><th>Pet Words</th></tr>
</thead>
<tbody>
${fmData.map(d => `
<tr>
<td class="fm-era">${d.era}</td>
<td class="fm-name">${d.fm}</td>
<td class="fm-words">${d.words}</td>
</tr>
`).join('')}
</tbody>
</table>
${section.reflection ? `<p class="reflection">${section.reflection}</p>` : ''}
</div>
`;
} else if (section.type === 'persistent_words_chart') {
// Persistent words heatmap-style table
const wordData = section.word_data || [];
const decades = section.decades || ['60s', '70s', '80s', '90s', '00s', '10s', '20s'];
content = `
<div class="step-content persistent-words-content">
${section.era_label ? `<span class="era-badge">${section.era_label}</span>` : ''}
${section.title ? `<h3>${section.title}</h3>` : ''}
${section.setup ? `<p class="setup">${section.setup}</p>` : ''}
<table class="persistent-words-table">
<thead>
<tr>
<th></th>
${decades.map(d => `<th>${d}</th>`).join('')}
</tr>
</thead>
<tbody>
${wordData.map(w => `
<tr>
<td class="word-label">${w.word}</td>
${w.rates.map(r => {
const intensity = Math.min(r / 20, 1); // normalize to 0-1
const bg = `rgba(61, 90, 128, ${intensity * 0.7 + 0.1})`;
const color = intensity > 0.4 ? 'white' : 'var(--charcoal)';
return `<td class="rate-cell" style="background:${bg};color:${color}">${r.toFixed(1)}</td>`;
}).join('')}
</tr>
`).join('')}
</tbody>
</table>
<p class="table-note">Mentions per 10,000 words</p>
${section.reflection ? `<p class="reflection">${section.reflection}</p>` : ''}
</div>
`;
} else if (section.type === 'prose') {
// Regular article text - no card, just body text
el.classList.add('step-prose');
content = `
<div class="prose-content">
${section.setup ? `<div class="prose-text">${section.setup.split('\n\n').map(p => `<p>${p}</p>`).join('')}</div>` : ''}
</div>
`;
} else {
// Regular quote section
content = `
<div class="step-content">
<span class="era-badge">${section.era_label}</span>
${section.setup ? `<p class="setup">${section.setup}</p>` : ''}
${section.quote ? `
<blockquote class="quote">"${section.quote}"</blockquote>
<p class="attribution">— ${section.speaker}, ${section.year}</p>
` : ''}
${section.reflection ? `<p class="reflection">${section.reflection}</p>` : ''}
</div>
`;
}
el.innerHTML = content;
container.appendChild(el);
});
// Draw sparklines after DOM is ready
drawSparklines();
}
// Draw sparklines for word trends
function drawSparklines() {
document.querySelectorAll('.sparkline').forEach(svg => {
const values = svg.dataset.values.split(',').map(Number);
const color = svg.dataset.color;
const width = 80;
const height = 24;
svg.setAttribute('width', width);
svg.setAttribute('height', height);
svg.setAttribute('viewBox', `0 0 ${width} ${height}`);
const max = Math.max(...values);
const min = Math.min(...values);
const range = max - min || 1;
const points = values.map((v, i) => {
const x = (i / (values.length - 1)) * width;
const y = height - ((v - min) / range) * (height - 4) - 2;
return `${x},${y}`;
}).join(' ');
const polyline = document.createElementNS('http://www.w3.org/2000/svg', 'polyline');
polyline.setAttribute('points', points);
polyline.setAttribute('fill', 'none');
polyline.setAttribute('stroke', color);
polyline.setAttribute('stroke-width', '1.5');
polyline.setAttribute('stroke-linecap', 'round');
polyline.setAttribute('stroke-linejoin', 'round');
svg.appendChild(polyline);
});
}
// Initialize visualization
function initVisualization() {
const container = domElements.timelineViz;
// Clear any loading state content
container.innerHTML = '';
const width = container.clientWidth;
// Get responsive configuration
const config = getResponsiveConfig();
// Use full height to ensure chart is never cut off
const height = container.clientHeight || 500;
const margin = {
top: config.marginTop,
right: config.marginRight,
bottom: config.marginBottom,
left: config.marginLeft
};
svg = d3.select('#timeline-viz')
.append('svg')
.attr('width', width)
.attr('height', height);
const yearGroups = d3.group(filteredParagraphs, d => d.year);
const years = [...yearGroups.keys()].sort((a, b) => a - b);
// Variable width calculation - now responsive
const dotSize = config.dotSize;
const dotGap = config.dotGap;
const yearGap = 2;
const maxCols = config.maxCols;
const availableWidth = width - margin.left - margin.right;
let yearWidths = {};
let totalWidth = 0;
years.forEach(year => {
const count = yearGroups.get(year).length;
const cols = Math.min(count, maxCols);
const yearWidth = cols * (dotSize + dotGap) + yearGap;
yearWidths[year] = { count, cols, width: yearWidth };
totalWidth += yearWidth;
});
const scale = totalWidth > 0 ? availableWidth / totalWidth : 1;
let currentX = margin.left;
yearPositions = {};
years.forEach(year => {
const scaledWidth = yearWidths[year].width * scale;
yearPositions[year] = {
start: currentX,
center: currentX + scaledWidth / 2,
end: currentX + scaledWidth - yearGap * scale,
width: scaledWidth - yearGap * scale
};
currentX += scaledWidth;
});
// Position dots - Diverging chart: promises ABOVE baseline, demands BELOW baseline
// Calculate baseline position (middle of chart area)
const chartHeight = height - margin.top - margin.bottom;
const baseline = margin.top + chartHeight * 0.5; // Middle of chart
years.forEach(year => {
const yearParas = yearGroups.get(year);
const yearPos = yearPositions[year];
const effectiveWidth = yearPos.width;
const cols = Math.max(1, Math.floor(effectiveWidth / (dotSize + dotGap)));
const gridWidth = cols * (dotSize + dotGap);
const offsetX = (effectiveWidth - gridWidth) / 2;
// Separate promises and obligations
const promises = yearParas.filter(p => p.primary_type === 'promise');
const obligations = yearParas.filter(p => p.primary_type === 'obligation');
// Sort promises: darker (citizen) closer to baseline, lighter (firm) further up
promises.sort((a, b) => {
const order = (p) => p.primary_value === 'citizen' ? 0 : 1;
return order(a) - order(b);
});
// Sort obligations: darker (citizen) closer to baseline, lighter (firm) further down
obligations.sort((a, b) => {
const order = (p) => p.primary_value === 'citizen' ? 0 : 1;
return order(a) - order(b);
});
// Position promises ABOVE baseline (going upward)
promises.forEach((p, idx) => {
const row = Math.floor(idx / cols);
const col = idx % cols;
p.xPos = yearPos.start + offsetX + col * (dotSize + dotGap) + dotSize / 2;
p.yPos = baseline - dotSize - row * (dotSize + dotGap); // Above baseline
});
// Position obligations BELOW baseline (going downward)
obligations.forEach((p, idx) => {
const row = Math.floor(idx / cols);
const col = idx % cols;
p.xPos = yearPos.start + offsetX + col * (dotSize + dotGap) + dotSize / 2;
p.yPos = baseline + dotSize + row * (dotSize + dotGap); // Below baseline
});
});
// Year labels positioned dynamically below where each year's boxes end
const labelYears = [1965, 1980, 2000, 2020, 2026];
const yearLabelPadding = config.isMobile ? 12 : 15;
// Calculate max y position for each label year
const yearMaxY = {};
labelYears.forEach(year => {
const yearParas = filteredParagraphs.filter(p => p.year === year);
if (yearParas.length > 0) {
yearMaxY[year] = Math.max(...yearParas.map(p => p.yPos)) + dotSize / 2;
} else {
yearMaxY[year] = baseline; // fallback
}
});
svg.selectAll('.year-label')
.data(labelYears.filter(y => yearPositions[y]))
.join('text')
.attr('class', 'year-label')
.attr('x', d => yearPositions[d].center)
.attr('y', d => yearMaxY[d] + yearLabelPadding)
.attr('text-anchor', 'middle')
.attr('fill', '#7a7a7a')
.attr('font-size', config.fontSize.year)
.attr('font-weight', '500')
.style('pointer-events', 'none')
.text(d => d)
.raise(); // Bring to front
// Central baseline (dividing promises above from demands below)
svg.append('line')
.attr('class', 'center-baseline')
.attr('x1', margin.left)
.attr('x2', width - margin.right)
.attr('y1', baseline)
.attr('y2', baseline)
.attr('stroke', '#aaa')
.attr('stroke-width', 1)
.attr('stroke-dasharray', '4,2');
// Axis labels for diverging chart
if (!config.isMobile) {
// "Promises" label above baseline
svg.append('text')
.attr('class', 'axis-label')
.attr('x', margin.left + 5)
.attr('y', baseline - 30)
.attr('text-anchor', 'start')
.attr('fill', '#C44F4F')
.attr('font-size', '10px')
.attr('font-weight', '600')
.text('↑ PROMISES');
// "Demands" label below baseline
svg.append('text')
.attr('class', 'axis-label')
.attr('x', margin.left + 5)
.attr('y', baseline + 50)
.attr('text-anchor', 'start')
.attr('fill', '#3D5A80')
.attr('font-size', '10px')
.attr('font-weight', '600')
.text('↓ DEMANDS');
}
// Legend (subtle, on left side) - hide on mobile (CSS legend used instead)
if (!config.hideSvgLegend) {
const legendData = [
{ label: 'Promise to you', color: '#C44F4F' },
{ label: 'Promise to firms', color: '#E89898' },
{ label: 'Ask of you', color: '#2B4460' },
{ label: 'Ask of firms', color: '#6B8CAE' }
];
const legendX = 30;
const legendY = margin.top; // Position at top-left, above promises
const legendSpacing = 18;
const legendRectSize = 9;
const legend = svg.append('g')
.attr('class', 'legend')
.attr('transform', `translate(${legendX}, ${legendY})`);
legendData.forEach((item, i) => {
const legendRow = legend.append('g')
.attr('transform', `translate(0, ${i * legendSpacing})`);
legendRow.append('rect')
.attr('width', legendRectSize)
.attr('height', legendRectSize)
.attr('fill', item.color)
.attr('opacity', 0.8);
legendRow.append('text')
.attr('x', legendRectSize + 5)
.attr('y', legendRectSize - 1)
.attr('font-size', config.fontSize.legend)
.attr('fill', '#999')
.attr('opacity', 0.8)
.text(item.label);
});
}
// Dots - use unique ID for stable data binding across resize
dots = svg.selectAll('.dot')
.data(filteredParagraphs, d => d._uid)
.join('rect')
.attr('class', 'dot')
.attr('x', d => d.xPos - dotSize / 2)
.attr('y', d => d.yPos - dotSize / 2)
.attr('width', dotSize - 0.5)
.attr('height', dotSize - 0.5)
.attr('rx', 0)
.attr('fill', d => {
// Grey for none/other paragraphs
if (!d.primary_value || d.primary_value === 'none') return '#CCCCCC';
// Color based on type (promise/obligation) and target (citizen/firm)
if (d.primary_type === 'promise') {
return d.primary_value === 'citizen' ? '#C44F4F' : '#E89898'; // darker coral : lighter coral
} else if (d.primary_type === 'obligation') {
return d.primary_value === 'citizen' ? '#2B4460' : '#6B8CAE'; // darker blue : lighter blue
}
return '#b0b0b0';
})
.attr('opacity', 0.9)
.attr('stroke', 'none')
.attr('stroke-width', 0)
.style('cursor', d => {
// Only show pointer for promises and obligations
return (d.primary_value && d.primary_value !== 'none') ? 'pointer' : 'default';
})
.on('mouseenter', function(_event, d) {
if (!document.body.classList.contains('interactive-mode')) return;
// Clear pending hide timeout
if (hoverPanelTimeout) {
clearTimeout(hoverPanelTimeout);
hoverPanelTimeout = null;
}
// Clear previous selection, add new selection using class
if (selectedDot && selectedDot !== this) {
d3.select(selectedDot).classed('selected', false);
}
selectedDot = this;
d3.select(this).classed('selected', true).raise();
showHoverPanel(d);
})
.on('mouseleave', function(_event, d) {
if (!document.body.classList.contains('interactive-mode')) return;
// Delay hiding panel and removing selection
hoverPanelTimeout = setTimeout(() => {
if (selectedDot) {
d3.select(selectedDot).classed('selected', false);
selectedDot = null;
}
hideHoverPanel();
}, TIMING.HOVER_PANEL_HIDE_DELAY);
})
.on('click', function(_event, d) {
if (!document.body.classList.contains('interactive-mode')) return;
// Clear previous, select this one
if (selectedDot && selectedDot !== this) {
d3.select(selectedDot).classed('selected', false);
}
selectedDot = this;
d3.select(this).classed('selected', true);
showHoverPanel(d);
pinQuote();
});
// Touch slide support for mobile - allows sliding finger across squares
// Store references for cleanup on resize
setupTouchListeners(svg.node());
// Highlight box - must not block pointer events on dots
svg.append('rect')
.attr('class', 'highlight-box')
.attr('y', margin.top)
.attr('height', height - margin.top - margin.bottom)
.attr('fill', '#fad8ac8f')
.attr('opacity', 0)
.style('pointer-events', 'none');
}
// Scroll triggers
function setupScrollTriggers() {
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const step = entry.target.dataset.step;
const yearStart = parseInt(entry.target.dataset.yearStart);
const yearEnd = parseInt(entry.target.dataset.yearEnd);
if (step !== currentSection) {
currentSection = step;
highlightYearRange(yearStart, yearEnd);
updateHeader(entry.target);
updateProgress(yearStart, yearEnd);
}
}
});
}, {
rootMargin: '-35% 0px -35% 0px',
threshold: 0
});
document.querySelectorAll('.step').forEach(el => observer.observe(el));
// Detect when explore section comes into view - enable interactive mode
const exploreSection = document.querySelector('[data-step="explore"]');
if (exploreSection) {
const exploreObserver = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting && entry.intersectionRatio >= 0.5) {
// User is viewing the explore section - schedule interactive mode
scheduleInteractiveMode(true);
} else {
// Not intersecting - cancel pending timeout
cancelPendingInteractiveMode();
// Check if user scrolled PAST the explore section (not above it)
const rect = entry.boundingClientRect;
const isAboveExploreSection = rect.top > window.innerHeight * 0.5;
if (!isAboveExploreSection) {
// User scrolled past - enable immediately
enableInteractiveMode();
}
}
});
}, {
threshold: [0, 0.1, 0.5]
});
exploreObserver.observe(exploreSection);
} else {
console.error('Explore section not found! Interactive mode will not work.');
}
// Fallback for fast scrollers - no throttle, no RAF delay
window.addEventListener('scroll', () => {
if (document.body.classList.contains('interactive-mode') || interactiveModeCooldown) return;
const exploreEl = document.querySelector('[data-step="explore"]');
if (!exploreEl) return;
const rect = exploreEl.getBoundingClientRect();
if (rect.top < window.innerHeight * 0.5) {
// Explore section has entered upper half of viewport - enable immediately
cancelPendingInteractiveMode();
enableInteractiveMode();
}
}, { passive: true });
}
// =============================================================================
// INTERACTIVE MODE - Single entry point, no race conditions
// =============================================================================
function scheduleInteractiveMode(withDelay = false) {
// Already in interactive mode or cooldown active
if (document.body.classList.contains('interactive-mode') || interactiveModeCooldown) return;
// Already scheduled
if (interactiveModeTimeout) return;
if (withDelay) {
interactiveModeTimeout = setTimeout(() => {
interactiveModeTimeout = null;
enableInteractiveMode();
}, TIMING.INTERACTIVE_MODE_DELAY);
} else {