-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
2681 lines (2317 loc) · 99.5 KB
/
app.js
File metadata and controls
2681 lines (2317 loc) · 99.5 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
// ---------------------------
// Simple router (Learn/Explore/Test/Visualization/About)
// ---------------------------
const pages = {
learn: document.getElementById("page-learn"),
concept: document.getElementById("page-concept"),
research: document.getElementById("page-research"),
data: document.getElementById("page-data"),
test: document.getElementById("page-test"),
about: document.getElementById("page-about"),
};
const navButtons = document.querySelectorAll(".nav__link");
const navDropdownItems = document.querySelectorAll(".nav__dropdown-item");
const mobileToggle = document.querySelector(".nav__mobile-toggle");
const navMenu = document.querySelector(".nav");
function setRoute(route) {
Object.entries(pages).forEach(([k, el]) => {
if (el) el.classList.toggle("page--active", k === route);
});
navButtons.forEach((b) => {
b.setAttribute("aria-current", b.dataset.route === route ? "page" : "false");
});
// Close mobile menu after navigation
if (navMenu) navMenu.classList.remove("nav--open");
}
navButtons.forEach((btn) => {
btn.addEventListener("click", () => setRoute(btn.dataset.route));
});
// Add click handlers for dropdown items
navDropdownItems.forEach((item) => {
item.addEventListener("click", () => {
const route = item.dataset.route;
const section = item.dataset.section;
// First switch to the correct page
setRoute(route);
// Then scroll to the section if specified
if (section) {
// Small delay to ensure page is visible before scrolling
setTimeout(() => {
const targetElement = document.getElementById(section);
if (targetElement) {
// For visualization tabs, also activate the tab
if (section.startsWith('tab-')) {
const tabName = section.replace('tab-', '');
// Activate the corresponding tab button
const tabButtons = document.querySelectorAll('.viz-step-btn');
tabButtons.forEach(btn => {
btn.classList.toggle('viz-step-btn--active', btn.dataset.tab === tabName);
});
// Show the corresponding tab content
const tabContents = document.querySelectorAll('.tab-content');
tabContents.forEach(content => {
content.classList.toggle('tab-content--active', content.id === section);
});
}
targetElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
}, 100);
}
});
});
// Mobile menu toggle
if (mobileToggle && navMenu) {
mobileToggle.addEventListener("click", () => {
navMenu.classList.toggle("nav--open");
});
}
// ---------------------------
// Methodology panel toggle (Story 2.2)
// ---------------------------
function toggleMethodology() {
const content = document.getElementById('methodology-content');
const icon = document.getElementById('methodology-toggle-icon');
if (content && icon) {
const isHidden = content.style.display === 'none';
content.style.display = isHidden ? 'block' : 'none';
icon.style.transform = isHidden ? 'rotate(180deg)' : 'rotate(0deg)';
}
}
// ---------------------------
// Story 1.2 mini-game placeholder
// ---------------------------
// Story 2: survey (4 questions) + PCA scoring
// ---------------------------
const choicesContainers = document.querySelectorAll(".choices");
const testState = { ethnic: null, trade: null, citizen: null, income: null };
function renderChoices(container, qKey) {
if (!container) return;
container.innerHTML = '';
const labels = ["Strongly Disagree", "Disagree", "Neutral", "Agree", "Strongly Agree"];
for (let v = 1; v <= 5; v++) {
const btn = document.createElement("button");
btn.type = "button";
btn.className = "choice choice--text";
btn.textContent = labels[v - 1];
btn.setAttribute("aria-pressed", "false");
btn.addEventListener("click", () => {
testState[qKey] = v;
[...container.children].forEach((c) => c.setAttribute("aria-pressed", "false"));
btn.setAttribute("aria-pressed", "true");
});
container.appendChild(btn);
}
}
choicesContainers.forEach((c) => renderChoices(c, c.dataset.q));
const computeBtn = document.getElementById("compute-btn");
const resetBtn = document.getElementById("reset-btn");
const testResults = document.getElementById("test-results");
const scoreDisplay = document.getElementById("score-display");
const percentileText = document.getElementById("percentile-text");
const interpretationLevel = document.getElementById("interpretation-level");
const interpretationTitle = document.getElementById("interpretation-title");
const interpretationDesc = document.getElementById("interpretation-desc");
let distributionChart = null;
// ZS4_unif 直方图数据(每5分为一个bin,共20个区间:0-5, 5-10, ..., 95-100)
// 通过对原始0.02粒度数据加权插值得到
const zs4Breaks = [0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1.0];
const zs4Counts = [
406, // 0-5
206, // 5-10
304, // 10-15
442, // 15-20
829, // 20-25
1040, // 25-30
1138, // 30-35
1539, // 35-40
1357, // 40-45
3167, // 45-50
1363, // 50-55
1779, // 55-60
1732, // 60-65
1132, // 65-70
1189, // 70-75
898, // 75-80
467, // 80-85
490, // 85-90
261, // 90-95
544 // 95-100
];
function isTestComplete() {
return testState.ethnic && testState.trade && testState.citizen && testState.income;
}
function createDistributionChart(userScore) {
const ctx = document.getElementById('distribution-chart');
if (!ctx) return;
// 构造labels为0-100的整数区间,如"0–10", "10–20"等
const labels = zs4Breaks.slice(0, -1).map((b, i) => {
const start = Math.round(b * 100);
const end = Math.round(zs4Breaks[i + 1] * 100);
return `${start}–${end}`;
});
const counts = zs4Counts;
// 找到用户得分所在bin
let userBinIndex = zs4Breaks.findIndex((b, i) =>
i < zs4Breaks.length - 1 && userScore >= zs4Breaks[i] && userScore < zs4Breaks[i+1]
);
// 若正好等于1.0,归到最后一个bin
if (userScore === 1) userBinIndex = zs4Counts.length - 1;
// Color scheme:
// - Below user: light blue (low saturation)
// - Above user: light purple (low saturation)
// - User's bin: orange (visible but neutral, not negative)
const backgroundColors = counts.map((_, i) => {
if (i === userBinIndex) {
return '#f97316'; // Orange for user's position (neutral, visible)
} else if (i < userBinIndex) {
return '#bfdbfe'; // Light blue for lower scores (low saturation)
} else {
return '#ddd6fe'; // Light purple for higher scores (low saturation)
}
});
if (distributionChart) {
distributionChart.destroy();
}
// 用户得分转换为0-100
const userScorePercent = Math.round(userScore * 100);
distributionChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'Number of Respondents',
data: counts,
backgroundColor: backgroundColors,
borderWidth: 0,
borderRadius: 6
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: { display: false },
tooltip: {
callbacks: {
title: (items) => `Score: ${labels[items[0].dataIndex]}`,
label: (item) => `${counts[item.dataIndex].toLocaleString()} respondents`
}
}
},
scales: {
x: {
title: { display: true, text: 'Zero-Sum Thinking Score (0–100)' },
ticks: { maxRotation: 0, minRotation: 0, autoSkip: false }
},
y: {
title: { display: true, text: 'Number of Respondents' },
beginAtZero: true
}
}
}
});
}
if (computeBtn) {
computeBtn.addEventListener("click", () => {
if (!isTestComplete()) {
alert("Please answer all four questions before calculating your score.");
return;
}
const score = ZeroSumTest.calculateScore(
testState.ethnic,
testState.trade,
testState.citizen,
testState.income
);
const percentileInfo = ZeroSumTest.getPercentileRank(score);
const interpretation = ZeroSumTest.getInterpretation(score, 'en');
const scorePercent = Math.round(score * 100);
const percentile = percentileInfo.percentile;
// Update main score display
if (scoreDisplay) scoreDisplay.textContent = scorePercent;
// 1️⃣ Relative position statement - distribution-based, neutral language
const percentileStatement = document.getElementById("percentile-statement");
if (percentileStatement) {
let positionText = '';
if (percentile < 25) {
positionText = `You scored higher than <strong>${percentile}%</strong> of the ~20,000 U.S. respondents in the study. This places you <strong>below the median</strong> in zero-sum thinking.`;
} else if (percentile < 50) {
positionText = `You scored higher than <strong>${percentile}%</strong> of the ~20,000 U.S. respondents in the study. This places you <strong>somewhat below the median</strong> in zero-sum thinking.`;
} else if (percentile < 75) {
positionText = `You scored higher than <strong>${percentile}%</strong> of the ~20,000 U.S. respondents in the study. This places you <strong>somewhat above the median</strong> in zero-sum thinking.`;
} else {
positionText = `You scored higher than <strong>${percentile}%</strong> of the ~20,000 U.S. respondents in the study. This places you <strong>above the median</strong> in zero-sum thinking.`;
}
percentileStatement.innerHTML = positionText;
}
createDistributionChart(score);
if (testResults) {
testResults.style.display = 'block';
testResults.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
});
}
if (resetBtn) {
resetBtn.addEventListener("click", () => {
testState.ethnic = testState.trade = testState.citizen = testState.income = null;
choicesContainers.forEach((c) => {
[...c.children].forEach((btn) => btn.setAttribute("aria-pressed", "false"));
});
if (testResults) testResults.style.display = 'none';
if (scoreDisplay) scoreDisplay.textContent = '--';
});
}
// ---------------------------
// Story 3: Visualization (Demographic patterns)
// ---------------------------
// Data storage - will be loaded from JSON files
let aggregatedData = null;
let variableOrder = null;
let variableMetadata = null;
let rawVizData = null; // Individual-level data for filtering (Story 3.1.2)
let vizDataLoaded = false;
// All demographic variables available for filtering
const demographicVariables = ['age', 'gender', 'race', 'education', 'income', 'hhIncome', 'party', 'partyDetail', 'urbanicity', 'immigrationStatus'];
// Current filter state (Story 3.1.2)
let currentFilters = {}; // { variableName: [selectedValues] }
const demoSelect = document.getElementById("demo-select");
const d3ChartContainer = document.getElementById("d3-chart-container");
const chartInfo = document.getElementById("chart-info");
const chartTitle = document.getElementById("chart-title");
const chartSubtitle = document.getElementById("chart-subtitle");
const missingDataInfo = document.getElementById("missing-data-info");
const variableNote = document.getElementById("variable-note");
const filtersPanel = document.getElementById("filters-panel");
const resetFiltersBtn = document.getElementById("reset-filters-btn");
// Variable labels and descriptions for dynamic titles
const variableLabels = {
age: {
label: "Age Group",
description: "Average zero-sum thinking index across age groups."
},
gender: {
label: "Gender",
description: "Comparison of zero-sum thinking by gender."
},
race: {
label: "Race/Ethnicity",
description: "Average zero-sum thinking across racial and ethnic groups."
},
education: {
label: "Education Level",
description: "Zero-sum thinking by educational attainment."
},
income: {
label: "Relative Income",
description: "Zero-sum thinking by self-reported relative income."
},
hhIncome: {
label: "Household Income",
description: "Zero-sum thinking by household income brackets."
},
party: {
label: "Party Affiliation",
description: "Comparison of zero-sum thinking across political parties."
},
partyDetail: {
label: "Party Affiliation (Detailed)",
description: "Zero-sum thinking by detailed partisan identity."
},
urbanicity: {
label: "Urbanicity",
description: "Zero-sum thinking by residential area type."
},
immigrationStatus: {
label: "Immigration Status",
description: "Zero-sum thinking by generational immigration status."
}
};
// Research insights from the paper for each demographic variable
// Strictly based on paper content - only include mechanisms explicitly stated by authors
const demographicInsights = {
age: {
finding: "Younger respondents are more zero-sum; older respondents are less zero-sum. This is one of the clearest patterns in Figure 3.",
explanation: "The authors propose and test a specific mechanism: <em>birth cohort economic experience</em>. Younger cohorts grew up in conditions of lower growth and more stagnation. Using bottom-50% income growth during respondents' first 20 years of life, the paper shows: <em>'the answer to why younger individuals today are more zero-sum may be that they were born and raised in economic conditions that featured less growth and more stagnation.'</em>",
paperRef: "Figure 3, Figure 11, Figure 12, and Section 5"
},
gender: {
finding: "Women show slightly higher zero-sum thinking than men on average.",
explanation: "The paper documents this pattern as part of the broader demographic profile of zero-sum thinking. Gender differences are included in the analysis primarily as control variables and in interaction effects with policy preferences. The focus of the paper lies elsewhere — on origins (immigration, economic history) and consequences (policy views).",
paperRef: "Figure 3 (Section 3: Correlates of Zero-Sum Thinking)"
},
race: {
finding: "Black respondents are the most zero-sum. Asian/Asian American respondents are the least zero-sum. Hispanic/Latino respondents are slightly above White respondents.",
explanation: "The authors develop an extensive explanation centered on the history of slavery and systemic oppression, which created a 'fully zero-sum (or negative-sum)' environment. This experience is transmitted through: (1) direct ancestral experience, (2) local history (county-level slavery), and (3) cultural diffusion (Southern migration, Confederate culture). The paper states: <em>'we expect a history of slavery to correlate with more pronounced zero-sum thinking.'</em>",
paperRef: "Figure 3, Table 5, and Section 4.C (extensive discussion)"
},
education: {
finding: "Higher education is associated with lower zero-sum thinking. Those with high school or less are most zero-sum; college/postgraduate are least zero-sum.",
explanation: "The paper documents this gradient as a robust empirical pattern. Education serves as an important control variable throughout the analysis. The paper's focus is on other origins of zero-sum thinking (immigration experience, economic history) rather than the education channel.",
paperRef: "Figure 3 (Section 3: Correlates of Zero-Sum Thinking)"
},
income: {
finding: "Lower-income respondents are more zero-sum; higher-income respondents are less zero-sum. The relationship is <strong>monotonic</strong>.",
explanation: "The paper states: <em>'the lowest-income respondents … tend to be more zero-sum than higher-income respondents.'</em> Income is documented as part of the demographic correlates and used as a control variable. The paper's theoretical focus is on other determinants of zero-sum thinking.",
paperRef: "Figure 3 (Section 3: Correlates of Zero-Sum Thinking)"
},
hhIncome: {
finding: "Lower household income brackets are associated with higher zero-sum thinking. The gradient is monotonic.",
explanation: "Similar to relative income, this pattern is documented as part of the demographic profile. Household income serves as a control variable in the analysis. The paper explores other factors — particularly immigration and historical experiences — as primary explanations for variation in zero-sum thinking.",
paperRef: "Figure 3 (Section 3: Correlates of Zero-Sum Thinking)"
},
party: {
finding: "Democrats are on average more zero-sum than Republicans. However, there is substantial variation <em>within</em> each party.",
explanation: "The authors emphasize that zero-sum thinking is <strong>not caused by</strong> partisan identity — rather, it is <em>orthogonal</em> to partisanship. Zero-sum thinking helps explain <strong>within-party heterogeneity</strong>: zero-sum Democrats are more anti-immigration; zero-sum Republicans are more pro-redistribution. It functions as an 'interpretive lens' that shapes policy views independently of party affiliation.",
paperRef: "Figure 3, Figure 4, and Section 4"
},
partyDetail: {
finding: "Strong Democrats show the highest zero-sum thinking; Strong Republicans show the lowest. But the key insight is the variation <em>within</em> partisan categories.",
explanation: "The paper's central argument is that zero-sum thinking cuts across party lines. It predicts policy preferences <em>even after controlling for party</em>. A zero-sum Republican looks different from a non-zero-sum Republican on many policy questions — and the same applies to Democrats. This is what makes zero-sum thinking analytically distinct from partisanship.",
paperRef: "Figure 4, Table 3, and Section 4"
},
urbanicity: {
finding: "Urban residents show higher zero-sum thinking than suburban or rural residents.",
explanation: "The paper documents this as part of the demographic correlates of zero-sum thinking. Urbanicity is included as a control variable in the regression analyses. The paper's main focus is on other sources of variation in zero-sum beliefs.",
paperRef: "Demographic controls in regression analyses (Section 3)"
},
immigrationStatus: {
finding: "First-generation immigrants are the <strong>least</strong> zero-sum. Second-generation are still low but weaker. Third-generation effect fades substantially toward the baseline.",
explanation: "This is a central finding with a clearly articulated mechanism: the immigration experience provides direct evidence of a non-zero-sum world — immigrants observe that their economic success does not require harming others. The paper states: <em>'the immigrant experience benefits the newcomer and their descendants economically without detriment to others.'</em> This 'lived proof' is strongest for immigrants themselves and weakens across generations.",
paperRef: "Figure 14, Table 3, and Section 5 (Origins of Zero-Sum Thinking)"
}
};
// Function to update the insight card based on selected variable
function updateDemographicInsight(variable) {
const insightCard = document.getElementById("demographic-insight-content");
if (!insightCard) return;
const insight = demographicInsights[variable];
if (!insight) {
insightCard.innerHTML = '<p style="margin: 0; color: var(--muted); font-size: 13px;">Select a variable to see research insights from the paper.</p>';
return;
}
insightCard.innerHTML = `
<p style="margin: 0 0 12px 0; font-size: 14px; line-height: 1.6; color: var(--text);">
<strong>Key Finding:</strong> ${insight.finding}
</p>
<div style="padding: 12px; background: rgba(255,255,255,0.7); border-radius: 8px; margin-bottom: 12px;">
<p style="margin: 0; font-size: 13px; line-height: 1.6; color: var(--text);">
<strong>Why?</strong> ${insight.explanation}
</p>
</div>
<p style="margin: 0; font-size: 11px; color: var(--muted);">
<em>Reference: Chinoy, Nunn, Sequeira & Stantcheva (2024) — ${insight.paperRef}</em>
</p>
`;
}
// Current state
let currentXAxis = "age";
// Load visualization data from JSON files
async function loadVizData() {
try {
const [aggRes, orderRes, metaRes, rawRes] = await Promise.all([
fetch('./data/vizplot/aggregated_data.json'),
fetch('./data/vizplot/variable_order.json'),
fetch('./data/vizplot/variable_metadata.json'),
fetch('./data/vizplot/viz_data.json') // Individual-level data for filtering
]);
aggregatedData = await aggRes.json();
variableOrder = await orderRes.json();
variableMetadata = await metaRes.json();
rawVizData = await rawRes.json(); // ~20k individual records
vizDataLoaded = true;
console.log(`Visualization data loaded successfully. ${rawVizData.length} individual records available for filtering.`);
return true;
} catch (error) {
console.error('Failed to load visualization data:', error);
return false;
}
}
// Render D3.js bar chart
function renderD3BarChart(variable) {
if (!vizDataLoaded) {
console.error('Data not loaded yet');
return;
}
// Update research insight card for selected variable
updateDemographicInsight(variable);
// Clear previous chart and tooltip
d3.select("#d3-chart-container").selectAll("*").remove();
d3.selectAll(".demo-chart-tooltip").remove();
// Check if any filters are active
const hasActiveFilters = Object.keys(currentFilters).length > 0;
let data;
let filteredCount = 0;
let totalCount = rawVizData ? rawVizData.length : 0;
if (hasActiveFilters && rawVizData) {
// Apply filters to raw data and aggregate
const filteredData = applyFiltersToData(rawVizData, currentFilters);
filteredCount = filteredData.length;
data = aggregateByVariable(filteredData, variable);
} else {
// Use pre-aggregated data for better performance
if (!aggregatedData[variable]) {
console.error('Data not available for variable:', variable);
return;
}
data = aggregatedData[variable].slice();
filteredCount = totalCount;
}
// Sort by defined order
const order = variableOrder[variable] || [];
data = data.slice().sort((a, b) => {
const indexA = order.indexOf(a.label);
const indexB = order.indexOf(b.label);
if (indexA === -1 && indexB === -1) return 0;
if (indexA === -1) return 1;
if (indexB === -1) return -1;
return indexA - indexB;
});
// Set up dimensions
const containerWidth = d3ChartContainer.clientWidth || 600;
const maxWidth = 700; // Maximum chart width for better aesthetics
const effectiveWidth = Math.min(containerWidth, maxWidth);
const margin = { top: 30, right: 30, bottom: 80, left: 60 };
const width = effectiveWidth - margin.left - margin.right;
const height = 480 - margin.top - margin.bottom;
// Create SVG
const svg = d3.select("#d3-chart-container")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);
// X scale
const x = d3.scaleBand()
.range([0, width])
.domain(data.map(d => d.label))
.padding(0.2);
// Y scale (0 to 1 for normalized zero-sum index)
const y = d3.scaleLinear()
.domain([0, 1])
.range([height, 0]);
// Color scale: blue (low) -> yellow (high) - avoiding red/blue partisan association
const colorScale = d3.scaleLinear()
.domain([0.35, 0.55, 0.65])
.range(["#2171b5", "#74c476", "#fec44f"])
.clamp(true);
// Add X axis
svg.append("g")
.attr("transform", `translate(0,${height})`)
.call(d3.axisBottom(x))
.selectAll("text")
.attr("transform", "rotate(-35)")
.style("text-anchor", "end")
.style("font-size", "12px");
// Add Y axis
svg.append("g")
.call(d3.axisLeft(y).ticks(5).tickFormat(d => d.toFixed(1)))
.selectAll("text")
.style("font-size", "12px");
// Y axis label
svg.append("text")
.attr("transform", "rotate(-90)")
.attr("y", -45)
.attr("x", -height / 2)
.attr("text-anchor", "middle")
.style("font-size", "13px")
.style("fill", "#666")
.text("Zero-Sum Index (0–1)");
// Create tooltip (appended to body for correct positioning)
const tooltip = d3.select("body")
.append("div")
.attr("class", "demo-chart-tooltip")
.style("position", "fixed")
.style("visibility", "hidden")
.style("background-color", "rgba(0, 0, 0, 0.85)")
.style("color", "white")
.style("padding", "10px 14px")
.style("border-radius", "6px")
.style("font-size", "13px")
.style("pointer-events", "none")
.style("z-index", "1000")
.style("box-shadow", "0 2px 8px rgba(0,0,0,0.2)");
// Color: slate blue-gray for all bars (neutral, non-partisan)
const barColor = "#7b9cb5"; // Slate blue-gray (matches primary-light)
const hoverColor = "#f5a623"; // Warm amber/orange on hover
// Add bars with animation
svg.selectAll("rect")
.data(data)
.join("rect")
.attr("x", d => x(d.label))
.attr("width", x.bandwidth())
.attr("y", height)
.attr("height", 0)
.attr("fill", barColor)
.attr("rx", 4)
.style("cursor", "pointer")
.on("mouseover", function(event, d) {
d3.select(this)
.transition()
.duration(150)
.attr("fill", hoverColor);
const se = d.se || 0;
tooltip
.style("visibility", "visible")
.html(`<strong>${d.label}</strong><br/>Mean: ${d.mean.toFixed(3)}<br/>N: ${d.n.toLocaleString()}${se > 0 ? `<br/>SE: ±${se.toFixed(4)}` : ''}`);
})
.on("mousemove", function(event) {
tooltip
.style("top", (event.clientY - 10) + "px")
.style("left", (event.clientX + 15) + "px");
})
.on("mouseout", function(event, d) {
d3.select(this)
.transition()
.duration(200)
.attr("fill", barColor);
tooltip.style("visibility", "hidden");
})
.transition()
.duration(800)
.ease(d3.easeCubicOut)
.attr("y", d => y(d.mean))
.attr("height", d => height - y(d.mean));
// Add value labels on bars
svg.selectAll(".bar-label")
.data(data)
.join("text")
.attr("class", "bar-label")
.attr("x", d => x(d.label) + x.bandwidth() / 2)
.attr("y", d => y(d.mean) - 8)
.attr("text-anchor", "middle")
.style("font-size", "11px")
.style("font-weight", "600")
.style("fill", "#333")
.style("opacity", 0)
.text(d => d.mean.toFixed(2))
.transition()
.delay(600)
.duration(400)
.style("opacity", 1);
// Update dynamic title and subtitle
const varInfo = variableLabels[variable] || { label: variable, description: "" };
const metaInfo = variableMetadata[variable] || {};
// Note: hasActiveFilters is already declared above
// Build filter description for title/subtitle
let filterDescription = '';
if (hasActiveFilters) {
const filterParts = [];
for (const [filterVar, values] of Object.entries(currentFilters)) {
const filterLabel = variableLabels[filterVar]?.label || filterVar;
if (values.length <= 2) {
filterParts.push(`${filterLabel}: ${values.join(', ')}`);
} else {
filterParts.push(`${filterLabel}: ${values.length} selected`);
}
}
filterDescription = filterParts.join(' | ');
}
// Title is now fixed as "Zero-Sum Thinking by" with interactive dropdown
// Only update subtitle for filter status
if (chartSubtitle) {
if (hasActiveFilters) {
chartSubtitle.innerHTML = `<span style="color: #5b7c99; font-weight: 500;">Active Filters: ${filterDescription}</span>`;
chartSubtitle.style.display = 'block';
chartSubtitle.style.textAlign = 'right';
} else {
chartSubtitle.textContent = '';
chartSubtitle.style.display = 'none';
}
}
// Calculate statistics
const scores = data.map(d => d.mean);
const minScore = Math.min(...scores);
const maxScore = Math.max(...scores);
const minGroup = data.find(d => d.mean === minScore);
const maxGroup = data.find(d => d.mean === maxScore);
const totalN = data.reduce((sum, d) => sum + d.n, 0);
const diff = ((maxScore - minScore) * 100).toFixed(1);
// Build filter info string
const activeFilterCount = Object.values(currentFilters).reduce((sum, arr) => sum + arr.length, 0);
let filterInfo = '';
if (activeFilterCount > 0) {
filterInfo = `<br><span style="font-size: 11px; color: #5b7c99; font-weight: 500;">🔍 Filtered: ${filteredCount.toLocaleString()} of ${totalCount.toLocaleString()} records shown (${activeFilterCount} filter${activeFilterCount > 1 ? 's' : ''} applied)</span>`;
}
// Sample size warning thresholds
const SMALL_SAMPLE_THRESHOLD = 100; // Warning for total sample
const VERY_SMALL_GROUP_THRESHOLD = 30; // Warning for individual groups
// Check for small samples
const smallGroups = data.filter(d => d.n < VERY_SMALL_GROUP_THRESHOLD);
let sampleWarning = '';
if (totalN < SMALL_SAMPLE_THRESHOLD) {
sampleWarning = `<br><span style="font-size: 11px; color: #dc3545; font-weight: 600;">⚠️ Caution: Very small sample size (N = ${totalN}). Results may not be reliable.</span>`;
} else if (smallGroups.length > 0) {
const groupNames = smallGroups.map(g => `${g.label} (n=${g.n})`).join(', ');
sampleWarning = `<br><span style="font-size: 11px; color: #f59e0b; font-weight: 500;">⚠️ Small sample warning: ${smallGroups.length} group${smallGroups.length > 1 ? 's have' : ' has'} fewer than ${VERY_SMALL_GROUP_THRESHOLD} responses: ${groupNames}</span>`;
}
// Update summary info with comparison - now positioned above the chart
const sampleInfoEl = document.getElementById('sample-info');
// Chart summary (left box)
chartInfo.innerHTML = `
<span style="color: #4a90a4; font-weight: 600;">${minGroup.label}</span> shows the lowest zero-sum thinking (${minScore.toFixed(2)}),
while <span style="color: #e8a838; font-weight: 600;">${maxGroup.label}</span> shows the highest (${maxScore.toFixed(2)}) —
a difference of <strong>${diff} percentage points</strong>.${sampleWarning}
`;
// Sample info (above filters - subtle styling)
if (sampleInfoEl) {
const totalSample = 20278; // Full dataset size
if (hasActiveFilters) {
const percent = ((totalN / totalSample) * 100).toFixed(1);
sampleInfoEl.innerHTML = `<strong>N = ${totalN.toLocaleString()}</strong> <span style="opacity: 0.7;">(${percent}% of ${totalSample.toLocaleString()})</span>`;
sampleInfoEl.style.background = 'rgba(37, 99, 235, 0.08)';
sampleInfoEl.style.color = '#5b7c99';
} else {
sampleInfoEl.innerHTML = `<strong>N = ${totalN.toLocaleString()}</strong>`;
sampleInfoEl.style.background = 'rgba(108, 117, 125, 0.04)';
sampleInfoEl.style.color = 'var(--muted)';
}
}
// Data coverage info removed - now consolidated into chart summary above
// Show variable note if available (for special warnings)
if (variableNote) {
if (metaInfo.note && typeof metaInfo.note === 'string' && metaInfo.note.length > 0) {
variableNote.innerHTML = `<strong>⚠️ Important:</strong> ${metaInfo.note}`;
variableNote.style.display = 'block';
variableNote.style.background = 'rgba(255, 193, 7, 0.15)';
variableNote.style.padding = '8px 12px';
variableNote.style.borderRadius = '6px';
variableNote.style.borderLeft = '3px solid #ffc107';
} else {
variableNote.style.display = 'none';
}
}
}
// ========================================
// Story 3.1.2: Filter Functions
// ========================================
// Apply filters to raw data
function applyFiltersToData(data, filters) {
if (!data || Object.keys(filters).length === 0) return data;
return data.filter(record => {
for (const [variable, selectedValues] of Object.entries(filters)) {
if (selectedValues.length === 0) continue;
const recordValue = record[variable];
// Skip records with null/undefined values for this variable
if (recordValue === null || recordValue === undefined) return false;
if (!selectedValues.includes(recordValue)) return false;
}
return true;
});
}
// Aggregate filtered data by variable
function aggregateByVariable(data, variable) {
if (!data || data.length === 0) return [];
const groups = {};
data.forEach(record => {
const groupKey = record[variable];
if (groupKey === null || groupKey === undefined) return;
if (!groups[groupKey]) {
groups[groupKey] = { sum: 0, count: 0, values: [] };
}
if (record.zeroSumScore !== null && record.zeroSumScore !== undefined) {
groups[groupKey].sum += record.zeroSumScore;
groups[groupKey].count += 1;
groups[groupKey].values.push(record.zeroSumScore);
}
});
// Calculate mean and standard error for each group
const result = [];
Object.entries(groups).forEach(([label, stats]) => {
if (stats.count > 0) {
const mean = stats.sum / stats.count;
const variance = stats.values.reduce((acc, val) => acc + Math.pow(val - mean, 2), 0) / stats.count;
const se = Math.sqrt(variance / stats.count);
result.push({
label: label,
mean: Math.round(mean * 10000) / 10000,
n: stats.count,
se: Math.round(se * 10000) / 10000
});
}
});
return result;
}
// Get unique values for a variable from raw data
function getUniqueValuesFromData(variable) {
if (!rawVizData) return [];
const values = new Set();
rawVizData.forEach(record => {
if (record[variable] !== null && record[variable] !== undefined) {
values.add(record[variable]);
}
});
// Sort by predefined order if available
const order = variableOrder[variable] || [];
const sortedValues = Array.from(values).sort((a, b) => {
const indexA = order.indexOf(a);
const indexB = order.indexOf(b);
if (indexA === -1 && indexB === -1) return String(a).localeCompare(String(b));
if (indexA === -1) return 1;
if (indexB === -1) return -1;
return indexA - indexB;
});
return sortedValues;
}
// Render the filters panel (Story 3.1.2)
function renderFiltersPanel() {
if (!filtersPanel) return;
filtersPanel.innerHTML = '';
// Get all demographic variables except the current X-axis
const availableFilters = demographicVariables.filter(v => v !== currentXAxis);
availableFilters.forEach(variable => {
const varInfo = variableLabels[variable] || { label: variable };
const values = getUniqueValuesFromData(variable);
if (values.length === 0) return;
// Create filter group container
const filterGroup = document.createElement('div');
filterGroup.className = 'filter-group';
filterGroup.style.cssText = 'margin-bottom: 8px; padding-bottom: 8px; border-bottom: 1px solid var(--border);';
// Create collapsible header
const header = document.createElement('div');
header.style.cssText = 'display: flex; justify-content: space-between; align-items: center; cursor: pointer; margin-bottom: 4px;';
header.innerHTML = `
<span style="font-size: 12px; font-weight: 600; color: var(--text);">${varInfo.label}</span>
<span class="filter-toggle" style="font-size: 10px; color: var(--muted);">▼</span>
`;
// Create options container (collapsible)
const optionsContainer = document.createElement('div');
optionsContainer.className = 'filter-options';
optionsContainer.style.cssText = 'display: none; max-height: 120px; overflow-y: auto;';
// Track selected count
const selectedCount = (currentFilters[variable] || []).length;
if (selectedCount > 0) {
header.querySelector('.filter-toggle').textContent = `${selectedCount} selected`;
header.querySelector('.filter-toggle').style.color = '#5b7c99';
optionsContainer.style.display = 'block';
}
// Toggle collapse (accordion style - close others when opening one)
header.addEventListener('click', () => {
const isOpen = optionsContainer.style.display !== 'none';
// Close all other filter options first (accordion behavior)
if (!isOpen) {
const allFilterGroups = filtersPanel.querySelectorAll('.filter-group');
allFilterGroups.forEach(group => {
const otherOptions = group.querySelector('.filter-options');
const otherHeader = group.querySelector('.filter-toggle');
if (otherOptions && otherOptions !== optionsContainer) {
otherOptions.style.display = 'none';
// Reset toggle text if no selections
const otherSelectedCount = parseInt(otherHeader.textContent) || 0;
if (!otherHeader.textContent.includes('selected')) {
otherHeader.textContent = '▼';
}
}
});
}
optionsContainer.style.display = isOpen ? 'none' : 'block';
if (selectedCount === 0) {
header.querySelector('.filter-toggle').textContent = isOpen ? '▼' : '▲';
}
});
// Create checkboxes for each value
values.forEach(value => {
const checkboxWrapper = document.createElement('label');
checkboxWrapper.style.cssText = 'display: flex; align-items: center; gap: 6px; padding: 2px 0; cursor: pointer; font-size: 11px; color: var(--text);';
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.value = value;
checkbox.style.cssText = 'cursor: pointer; accent-color: #5b7c99;';
// Check if already selected
if (currentFilters[variable] && currentFilters[variable].includes(value)) {
checkbox.checked = true;
}
checkbox.addEventListener('change', () => {
handleFilterChange(variable, value, checkbox.checked);
});
const labelText = document.createElement('span');
labelText.textContent = value;
labelText.style.cssText = 'flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;';
checkboxWrapper.appendChild(checkbox);
checkboxWrapper.appendChild(labelText);
optionsContainer.appendChild(checkboxWrapper);
});
filterGroup.appendChild(header);
filterGroup.appendChild(optionsContainer);
filtersPanel.appendChild(filterGroup);
});
// Show active filters summary
const activeFilterCount = Object.values(currentFilters).reduce((sum, arr) => sum + arr.length, 0);
if (activeFilterCount > 0) {
const summary = document.createElement('div');
summary.style.cssText = 'margin-top: 12px; padding: 8px; background: rgba(37, 99, 235, 0.08); border-radius: 6px; font-size: 11px; color: var(--text);';
summary.innerHTML = `<strong>Active filters:</strong> ${activeFilterCount} selected across ${Object.keys(currentFilters).length} variable(s)`;
filtersPanel.appendChild(summary);
}
}
// Handle filter checkbox change
function handleFilterChange(variable, value, isChecked) {
if (!currentFilters[variable]) {
currentFilters[variable] = [];
}
if (isChecked) {
if (!currentFilters[variable].includes(value)) {
currentFilters[variable].push(value);
}
} else {
currentFilters[variable] = currentFilters[variable].filter(v => v !== value);
if (currentFilters[variable].length === 0) {
delete currentFilters[variable];
}
}
// Re-render chart with filtered data
renderD3BarChart(currentXAxis);
// Update filter panel to show selected counts
renderFiltersPanel();
}
// Reset all filters
function resetAllFilters() {
currentFilters = {};
renderFiltersPanel();
renderD3BarChart(currentXAxis);
}
// Event listener for demographic variable selector
if (demoSelect) {
demoSelect.addEventListener("change", (e) => {
const newXAxis = e.target.value;
// Remove the new X-axis variable from filters (can't filter on X-axis)
if (currentFilters[newXAxis]) {