-
-
Notifications
You must be signed in to change notification settings - Fork 330
/
Copy pathindex.html
2514 lines (2252 loc) · 125 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui" />
<title>U.S. Presidential Election Results</title>
<!-- include Tailwind CSS -->
<link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.16/dist/tailwind.min.css" rel="stylesheet" />
<style>
/* hide scroll bar */
/* html {
overflow-y: auto;
} */
body {
font-family: "Arial", sans-serif;
}
.nation,
.state,
.county {
fill: none;
stroke: #000000;
pointer-events: none;
}
.nation {
stroke-width: 0.4px;
}
.state {
stroke-width: 0.2px;
}
.county {
stroke: #000000;
stroke-width: 0.1px;
pointer-events: auto;
}
#state-title {
text-anchor: start;
/* Align text to the start */
font-size: 48px;
/* Bigger font size for better visibility */
font-weight: 900;
/* Very bold font weight */
fill: #333333;
/* Dark gray for a neutral and professional appearance */
stroke: white;
/* Add a stroke around the text for contrast */
stroke-width: 2px;
/* Width of the stroke */
paint-order: stroke fill;
/* Ensure stroke appears before the fill */
text-shadow: 2px 2px 5px rgba(0, 0, 0, 0.5);
/* Add a subtle shadow for better contrast */
pointer-events: none;
/* Prevent interaction with the text */
user-select: none;
/* Prevent text selection */
transition: opacity 0.3s ease-in-out;
/* Smooth transition when text changes */
}
.county:hover,
.highlighted-path {
stroke: #ffcc00;
/* A golden yellow for better contrast and aesthetics */
stroke-width: 2px;
/* Slightly thicker stroke to make it stand out */
fill: rgba(255, 204, 0, 0.2);
/* Add a subtle fill with transparency */
filter: drop-shadow(0px 0px 5px #ffcc00);
/* Add a glowing effect */
transition: all 0.3s ease-in-out;
/* Smooth transition for better aesthetics */
}
.dot:hover,
.highlighted-circle {
stroke: #ffcc00;
/* A golden yellow for better contrast and aesthetics */
stroke-width: 2px;
/* Slightly thicker stroke to make it stand out */
fill: rgba(255, 204, 0, 0.2);
/* Add a subtle fill with transparency */
filter: drop-shadow(0px 0px 5px #ffcc00);
/* Add a glowing effect */
transition: all 0.3s ease-in-out;
/* Smooth transition for better aesthetics */
}
.background {
fill: #fdfcfc;
fill-opacity: 0.7;
}
.bar text {
font-size: 10px;
}
.bar rect {
stroke: #000000;
stroke-width: 0.5px;
}
#county-legend {
text-anchor: middle;
}
/* John A. details Gomez dynamic details bar */
#details {
z-index: 999;
}
#details .title {
font-size: 1.25vmin;
}
.e-title {
font-size: 1.5vmin;
font-weight: 700;
}
/* custom tooltip */
.tooltip {
top: 100px;
left: 100px;
/* -moz-border-radius: 5px;
border-radius: 5px; */
/*border: 2px solid #000;*/
box-shadow: -4px 0 12px 0 rgba(0, 0, 0, 0.05);
background: #ffffff;
background-color: #fff;
border: 1px solid #ccc;
border-radius: 3px;
opacity: 1;
/* color: white; */
padding: 10px;
/* min-width: 375px; */
min-width: 36.75vmin;
font-family: "Arial", sans-serif;
font-size: 1.25vmin;
line-height: 18pt;
font-weight: lighter;
visibility: visible;
}
.tooltip.right::before {
content: "";
display: block;
width: 0;
height: 0;
position: absolute;
opacity: 0.9;
border-top: 8px solid transparent;
border-bottom: 8px solid transparent;
/* border-left: 8px solid #333; */
right: -8px;
top: 35px;
/* arbitrarily set */
}
.tooltip.left::before {
content: "";
display: block;
width: 0;
height: 0;
position: absolute;
opacity: 0.9;
border-top: 8px solid transparent;
border-bottom: 8px solid transparent;
left: -8px;
/* border-right: 8px solid #333; */
top: 35px;
/* arbitrarily set */
}
/* tooltip table */
.tooltip-table {
/* table-layout: fixed; */
width: 100%;
/* max-width: 380px; */
/* min-width: 375px; */
max-width: 36.75vmin;
white-space: nowrap;
border-collapse: collapse;
}
.tooltip-table tr:not(:nth-child(1)) {
border-top: 0.5px solid #ccc;
border-collapse: collapse;
}
.tooltip-table td:not(:nth-child(1)) {
padding-left: 3px;
}
.tooltip-table td:nth-child(1) {
width: 1%;
}
/* state table */
.highlighted-cell {
background-color: #86a1c1;
color: white;
/* Adjust text color for better readability */
font-weight: bold;
}
.state-table-header {
background-color: #095591;
color: white;
font-weight: bold;
}
.detail-table-header {
background-color: #095591;
color: white;
font-weight: bold;
}
/* radio buttons */
.radio-buttons-container {
position: absolute;
/* Position relative to the parent SVG */
bottom: 10px;
/* Adjust distance from the bottom edge of the SVG */
left: 10px;
/* Adjust distance from the right edge of the SVG */
z-index: 10;
/* Keep it on top of other content */
background-color: #ffffff;
padding: 10px;
border-radius: 5px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
border: 2px solid #095591;
}
.progress {
z-index: 100;
}
/* reset button */
/* taken from http://materialdesignblog.com/creating-a-simple-material-design-action-button-with-css/ */
/* uses Material Design principles, which is a plus */
.fab {
position: absolute;
/* Position relative to the parent SVG */
bottom: 10px;
/* Adjust distance from the bottom edge of the SVG */
right: 10px;
/* Adjust distance from the right edge of the SVG */
z-index: 100;
/* Keep it on top of other content */
width: 70px;
height: 70px;
background-color: #095591;
border-radius: 50%;
box-shadow: 0 6px 10px 0 #666;
transition: all 0.1s ease-in-out;
font-size: 50px;
color: #ffffff;
text-align: center;
line-height: 70px;
cursor: pointer;
padding: 10px;
display: flex;
justify-content: center;
align-items: center;
}
.fab:hover {
box-shadow: 0 6px 14px 0 #666;
transform: scale(1.05);
}
.app-bar {
background-color: #095591;
}
</style>
</head>
<body>
<div id="app">
<div class="min-h-screen bg-gray-100 flex flex-col">
<!-- app bar -->
<header class="app-bar fixed top-0 left-0 right-0 text-white shadow-md h-16 flex items-center px-4">
<div class="text-2xl font-bold">
United States Presidential Election Results, 2024
</div>
<div class="flex-grow"></div>
<div class="flex space-x-4">
<a href="https://github.com/tonmcg" target="_blank" class="hover:text-gray-300">
<svg class="w-9 h-9" xmlns="http://www.w3.org/2000/svg" fill="#ffffff" viewBox="0 0 24 24">
<path
d="M12 2C6.48 2 2 6.48 2 12c0 4.42 2.87 8.167 6.839 9.487.5.092.683-.217.683-.483 0-.237-.009-.868-.013-1.703-2.782.605-3.369-1.342-3.369-1.342-.454-1.154-1.11-1.462-1.11-1.462-.909-.621.069-.609.069-.609 1.003.071 1.53 1.031 1.53 1.031.892 1.529 2.341 1.087 2.91.831.092-.647.35-1.087.637-1.337-2.22-.253-4.555-1.113-4.555-4.95 0-1.093.39-1.988 1.029-2.688-.104-.254-.446-1.27.099-2.647 0 0 .84-.269 2.75 1.025a9.549 9.549 0 0 1 5.003 0c1.91-1.294 2.75-1.025 2.75-1.025.545 1.377.202 2.393.1 2.647.64.7 1.028 1.595 1.028 2.688 0 3.848-2.337 4.695-4.563 4.945.359.309.678.92.678 1.855 0 1.337-.012 2.416-.012 2.743 0 .267.18.578.688.48A10.013 10.013 0 0 0 22 12c0-5.52-4.48-10-10-10z">
</path>
</svg>
</a>
<a href="https://x.com/tonmcg" target="_blank" class="hover:text-gray-300">
<svg class="w-9 h-9" xmlns="http://www.w3.org/2000/svg" fill="#ffffff" viewBox="0 0 24 24">
<path
d="M22.46 6c-.77.35-1.6.59-2.46.7a4.16 4.16 0 0 0 1.84-2.3 8.1 8.1 0 0 1-2.64 1.02 4.09 4.09 0 0 0-7.08 3.73A11.62 11.62 0 0 1 3.17 5.16a4.11 4.11 0 0 0 1.27 5.47 4.05 4.05 0 0 1-1.85-.51v.05a4.1 4.1 0 0 0 3.28 4 4.09 4.09 0 0 1-1.84.07 4.12 4.12 0 0 0 3.83 2.84A8.2 8.2 0 0 1 2 18.55a11.5 11.5 0 0 0 6.29 1.84c7.55 0 11.67-6.26 11.67-11.67 0-.18-.01-.35-.02-.53a8.32 8.32 0 0 0 2.07-2.12z">
</path>
</svg>
</a>
<a href="https://www.linkedin.com/in/tonmcg" target="_blank" class="hover:text-gray-300">
<svg class="w-9 h-9" xmlns="http://www.w3.org/2000/svg" fill="#ffffff" viewBox="0 0 24 24">
<path
d="M20.452 20.452H16.9v-4.937c0-1.177-.023-2.691-1.643-2.691-1.644 0-1.896 1.284-1.896 2.61v5.018H9.91V9h3.4v1.561h.049c.476-.9 1.635-1.845 3.362-1.845 3.59 0 4.254 2.362 4.254 5.434v6.302zM5.337 7.433a1.967 1.967 0 1 1 0-3.933 1.967 1.967 0 0 1 0 3.933zM6.937 20.452H3.737V9h3.2v11.452zM22.227 0H1.772C.789 0 0 .784 0 1.748v20.505C0 23.217.79 24 1.772 24h20.455C23.21 24 24 23.217 24 22.253V1.748C24 .784 23.21 0 22.227 0z">
</path>
</svg>
</a>
<a href="https://www.emdata.ai" target="_blank" class="hover:text-gray-300">
<img alt="emdata Logo" src="https://avatars1.githubusercontent.com/u/58564118?s=200&v=4"
class="w-9 h-9" />
</a>
</div>
</header>
<main class="flex flex-col w-full h-full pt-16">
<div class="w-full p-4">
<div class="tooltip" style="position: absolute; z-index: 100; visibility: hidden;"></div>
<!-- Content container -->
<div class="w-full p-4">
<!-- Card -->
<div class="bg-white shadow rounded-lg overflow-hidden" :style="`min-height:${map.height}px`">
<!-- Card Title -->
<div class="p-4 border-b">
<div class="flex justify-between items-center">
<div>
<p class="text-2xl font-bold">
Map of United States Counties, Alaska Legislative Districts, and District of
Columbia Wards
</p>
<!-- subtitle here in smaller font -->
<p class="text-sm text-gray-700">
Hover over and click on the map and table to explore the election results.
</p>
</div>
</div>
</div>
<!-- Card Text -->
<div class="p-4">
<div class="grid grid-cols-12 gap-4">
<div class="col-span-2">
<!-- State Table -->
<div id="state-table" class="overflow-auto border border-gray-300 rounded-lg">
<table class="min-w-full table-auto border-collapse border border-gray-300">
<thead>
<tr class="state-table-header">
<th colspan="2"
class="px-2 py-1 text-center border border-gray-300">
State
</th>
</tr>
</thead>
<tbody>
<tr v-for="(stateRow, rowIndex) in splitStates" :key="rowIndex">
<td v-for="state in stateRow" :key="state.id"
:class="{'bg-blue-300 text-white': state.id === activeStateId,}"
class="state-cell px-2 py-1 text-center cursor-pointer hover:bg-blue-100 border border-gray-300"
@click="(e) => toggleStateFilter(state, e, this)">
{{ state.name }}
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="col-span-6">
<div class="overflow-auto border border-gray-300 rounded-lg"
:style="`position: relative; width: 100%; height: 100%; min-height:${map.height}px`">
<!-- map visualization -->
<svg id="map"></svg>
<div class="radio-buttons-container">
<label class="block text-gray-700 font-medium mb-2 text-lg">Select
map</label>
<div class="flex space-x-4" @change="renderLayer">
<label class="inline-flex items-center">
<input type="radio" name="mapType" value="choropleth"
v-model="selectedMap"
class="form-radio text-blue-600 focus:ring-blue-500 focus:ring-4 cursor-pointer" />
<span class="ml-2 text-gray-700">Choropleth (filled)</span>
</label>
<label class="inline-flex items-center">
<input type="radio" name="mapType" value="dotDensity"
v-model="selectedMap"
class="form-radio text-blue-600 focus:ring-blue-500 focus:ring-4 cursor-pointer" />
<span class="ml-2 text-gray-700">Dot Density</span>
</label>
</div>
</div>
<!-- Material design-styled reset button -->
<div v-show="isZoomed" class="fab" style="opacity: 1;"
@click="(e) => setLayers(null, 'United States', e)">
↺</div>
</div>
</div>
<div class=" col-span-4">
<!-- Details Table -->
<div id="detail-table" class="overflow-auto border border-gray-300 rounded-lg">
<table class="min-w-full table-auto border-collapse border border-gray-300">
<thead>
<tr class="detail-table-header">
<th class="px-4 py-2 text-left border border-gray-300"
style="width: 30%;">Candidate
</th>
<th class="px-4 py-2 text-left border border-gray-300"
style="width: 10%;">Party
</th>
<th class="px-4 py-2 text-right border border-gray-300"
style="width: 15%;">Total Votes
</th>
<th class="px-4 py-2 text-left border border-gray-300"
style="width: 45%;">
Percentage</th>
</tr>
</thead>
<tbody>
<!-- Democrat Row -->
<tr>
<td
class="px-4 py-2 flex items-center gap-4 border border-gray-300">
<img src="https://static01.nyt.com/elections-assets/2024/headshots/AK-G-P-2024-11-05-harris-k-44992.png?size=thumb&auto=webp"
alt="Democrat Candidate"
class="w-10 h-10 rounded-full" />
<span>Kamala R. Harris</span>
</td>
<td class="px-4 py-2 border border-gray-300">Democrat
</td>
<td class="px-4 py-2 text-right border border-gray-300">
{{formatValue(demVotesTweened, "integer")}}</td>
<td class="px-4 py-2 border border-gray-300">
<div class="flex items-center gap-4">
<span>{{formatValue(demShareTweened,
"percent")}}</span>
<svg class="w-32 h-4" viewBox="0 0 101 10"
xmlns="http://www.w3.org/2000/svg">
<g class="bar">
<rect x="0" y="0"
:width="`${demShareTweened * 100}`"
height="10"
:fill="color(demShareTweened)" />
<rect :x="`${demShareTweened * 100}`" y="0"
:width="`${(1 - demShareTweened) * 100}`"
height="10" fill="#E5E7EB" />
</g>
</svg>
</div>
</td>
</tr>
<!-- Republican Row -->
<tr>
<td
class="px-4 py-2 flex items-center gap-4 border border-gray-300">
<img src="https://static01.nyt.com/elections-assets/2024/headshots/NV-R-P-president-2024-02-08-trump-d-18284.png?size=thumb&auto=webp"
alt="Republican Candidate"
class="w-10 h-10 rounded-full" />
<span>Donald J. Trump</span>
</td>
<td class="px-4 py-2 border border-gray-300">Republican
</td>
<td class="px-4 py-2 text-right border border-gray-300">
{{formatValue(gopVotesTweened, "integer")}}</td>
<td class="px-4 py-2 border border-gray-300">
<div class="flex items-center gap-4">
<span>{{formatValue(gopShareTweened,
"percent")}}</span>
<svg class="w-32 h-4" viewBox="0 0 101 10"
xmlns="http://www.w3.org/2000/svg">
<g class="bar">
<rect x="0" y="0"
:width="`${gopShareTweened * 100}`"
height="10"
:fill="color(-gopShareTweened)" />
<rect :x="`${gopShareTweened * 100}`" y="0"
:width="`${(1 - gopShareTweened) * 100}`"
height="10" fill="#E5E7EB" />
</g>
</svg>
</div>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td
class="px-4 py-2 flex items-center gap-4 border border-gray-300">
{{`Total
${activeStateId ? states.filter(s => s.id ===
activeStateId)[0].name : ''} Votes`}}</td>
<td class="px-4 py-2 border border-gray-300"></td>
<td class="px-4 py-2 text-right border border-gray-300">
{{formatValue(gopVotesTweened + demVotesTweened,
"integer")}}</td>
<td class="px-4 py-2 border border-gray-300">
{{formatValue(gopShareTweened - demShareTweened,
"percent")}} percentage point difference</td>
</tr>
</tfoot>
</table>
</div>
<div id="detailBar" class="px-4 py-2">
</div>
<div id="county-table" v-show="activeStateId"
class="overflow-auto border border-gray-300 rounded-lg mt-4"
:style="`max-height: ${map.height - 214 - 86}px; overflow-y: auto;`">
<table class="min-w-full table-auto border-collapse border border-gray-300">
<thead class="sticky top-0 bg-white">
<tr class="detail-table-header">
<th class="px-4 py-2 text-left border border-gray-300 cursor-pointer"
style="width: 35%;">
County
</th>
<th class="px-4 py-2 text-right border border-gray-300 cursor-pointer"
style="width: 20%;">
Total Votes
</th>
<th class="px-4 py-2 text-left border border-gray-300 cursor-pointer"
style="width: 45%;">
Percentage
</th>
</tr>
</thead>
<tbody>
</tbody>
<!-- <tfoot class="sticky bottom-0 bg-white">
</tfoot> -->
</table>
</div>
</div>
</div>
<!-- Card Actions -->
<div class="p-4">
<div class="flex justify-between items-center">
<div class="flex justify-start">
<span>
Sources:
<a href="https://www.foxnews.com/elections/2024/general-results"
class="text-blue-500 underline" target="_blank"><em>Fox
News</em></a>,
<a href="https://electionresults.dcboe.org/election_results/2024-General-Election"
class="text-blue-500 underline" target="_blank"><em>District
of
Columbia Board of
Elections</em></a>, and
<a href="https://www.elections.alaska.gov/enr/"
class="text-blue-500 underline" target="_blank"><em>Alaska
Division of Elections</em></a>.
<br />Data compiled by:
<a href="https://github.com/tonmcg/US_County_Level_Election_Results_08-24/blob/master/2024_US_County_Level_Presidential_Results.csv"
class="text-blue-500 underline" target="_blank">Tony
McGovern</a>.
</span>
</div>
<div class="text-sm flex justify-end">
<span>
Alaska data last updated: {{ alaska.lastupdated }}.
<br />Washington D.C. data last updated: {{ dc.lastupdated }}.
<br />Continental U.S. data last updated: {{
continental.lastupdated
}}.
</span>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Progress indicator -->
<div class="progress fixed inset-0 flex items-center justify-center bg-gray-800 bg-opacity-50"
v-if="!counties.length">
<svg class="animate-spin h-32 w-32 text-blue-500" xmlns="http://www.w3.org/2000/svg" fill="none"
viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="1">
</circle>
<path class="opacity-75" fill="#ffffff" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z">
</path>
</svg>
</div>
</main>
<!-- page footer -->
<footer class="bg-gray-600 text-white absolute bottom-0 w-full">
<div class="flex justify-center items-center py-4">
<span>© {{ new Date().getFullYear() }} — <strong>Tony McGovern</strong></span>
</div>
</footer>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js" type="text/javascript"></script>
<script src="https://cdn.jsdelivr.net/npm/jszip@3.7.1/dist/jszip.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/danfojs@1.1.2/lib/bundle.min.js"></script>
<script src="https://d3js.org/d3.v7.min.js" type="text/javascript"></script>
<script src="https://unpkg.com/topojson@3" type="text/javascript"></script>
<script defer type="text/javascript">
"use strict";
new Vue({
el: "#app",
data: () => ({
domain: [-1, 1], // set the domain for all scales from -1 to 1
tooltip: {
visibility: "hidden",
position: { x: 0, y: 0 },
content: "",
},
gopVotesTweened: 0,
demVotesTweened: 0,
gopShareTweened: 0,
demShareTweened: 0,
selectedMap: "dotDensity",
activeStateId: null, // Tracks the currently active state
districtObj: {},
counties: [],
states: [],
geographies: {
censusYear: 2024, // base year for the county gazetteer files
suzeraintyFips: ["02", "11", "60", "66", "69", "72", "74", "78"], // states or territories that we are not getting election results for
},
alaska: {
lastupdated: ""
},
dc: {
lastupdated: ""
},
continental: {
lastupdated: new Date().toLocaleString(),
},
map: {
width: 0,
height: 0
},
sortOrderColumn: null,
sortOrderAscending: true,
transition: {
duration: 1500,
ease: d3.easeExpInOut // Ease function applied here
},
isZoomed: false,
allNationFeatures: {},
allStateFeatures: {},
allCountyFeatures: {},
}),
watch: {
gopVotes: function (newVal) {
this.animateValue("gopVotesTweened", newVal);
},
demVotes: function (newVal) {
this.animateValue("demVotesTweened", newVal);
},
gopShare: function (newVal) {
this.animateValue("gopShareTweened", newVal);
},
demShare: function (newVal) {
this.animateValue("demShareTweened", newVal);
},
},
computed: {
filteredCounties: function () {
return this.activeStateId ? this.counties.filter((f) => f.startsWith(this.activeStateId)) : this.counties;
},
filteredFeatures: function () { // filter features based on the active state
return this.activeStateId ? this.allCountyFeatures.filter(d => {
return d.id.startsWith(this.activeStateId)
}) : this.allCountyFeatures;
},
gopVotes: function () {
return this.counties.length > 60 ? d3.sum(
this.filteredCounties,
(r) => this.districtObj[r]["GOP"]
) || 0 : 0;
},
demVotes: function () {
return this.counties.length > 60 ? d3.sum(
this.filteredCounties,
(r) => this.districtObj[r]["Dem."]
) || 0 : 0;
},
gopShare: function () {
return this.gopVotes / (this.gopVotes + this.demVotes) || 0;
},
demShare: function () {
return this.demVotes / (this.gopVotes + this.demVotes) || 0;
},
color: function () {
return d3
.scaleSequential()
.interpolator(d3.interpolateRdBu)
.domain(this.domain);
},
wScale: function () {
return d3
.scaleLinear()
.domain(this.domain)
.range([-this.map.width / 3, this.map.width / 3]);
},
path: function () {
// Define path projection
return d3.geoPath().projection(null);
},
center: function () {
const nation = d3.select(".nation");
// Calculate and apply initial center position
const center = [
this.map.width / 2 - this.path.centroid(nation.datum())[0], // Center X
this.map.height / 2 - this.path.centroid(nation.datum())[1], // Center Y
];
return center;
},
countyTableWidth: function () {
const table = document.querySelector('#county-table');
const width = table.offsetWidth || 0;
return width > 810 ? width : window.innerWidth * 15 / 50; // portion of the innerWidth of the window
},
stateTableHeight: function () {
const table = document.querySelector('#state-table');
const height = table.offsetHeight || 0;
return height > 600 ? height : window.innerHeight * 43 / 64; // portion of the innerHeight of the window
},
mapWidth: function () {
const div = document.querySelector('.col-span-6');
const width = div.offsetWidth - 2 || 0;
return width > 300 ? width : window.innerWidth * 24 / 50; // portion of the innerWidth of the window
},
zoom: function () {
return d3.zoom()
.scaleExtent([1, 24])
.on("zoom", this.zoomed);
},
sequentialScale: function () {
return d3
.scaleSequential()
.interpolator(d3.interpolateRdBu)
.domain(this.domain);
},
// Split states into rows with two columns
splitStates: function () {
const sorted_states = this.states.length < 51 ? [] : this.states.sort((a, b) => a.name.localeCompare(b.name));
const split_states = sorted_states.reduce((rows, state, index) => {
if (index % 2 === 0) rows.push([]);
rows[rows.length - 1].push(state);
return rows;
}, []);
return split_states;
},
sortedCounties() {
if (!this.sortOrderColumn) return this.filteredCounties;
const sorted = [...this.filteredCounties].sort((a, b) => {
const col = this.sortOrderColumn === "Percentage" ? "% of Total Vote, GOP" : this.sortOrderColumn;
const districtA = this.districtObj[a];
const districtB = this.districtObj[b];
if (typeof districtA[col] === "string") {
return this.sortOrderAscending
? districtA[col].localeCompare(districtB[col])
: districtB[col].localeCompare(districtA[col]);
} else {
return this.sortOrderAscending ? districtA[col] - districtB[col] : districtB[col] - districtA[col];
}
});
return sorted;
},
},
mounted: async function () {
this.setMapDimensions();
await this.fetchUSGeography();
this.initializeMap();
const censusCounties = await this.getCensusCounties();
const censusStates = await this.getCensusStates();
const censusGeographies = this.mergeCensusGeographies(
censusCounties,
censusStates
);
const dcGeographies = await this.getDCGeographies();
await this.fetchDCResults(dcGeographies);
await this.fetchDCUpdatedDate();
const akGeographies = await this.getAlaskaGeographies();
await this.fetchAlaskaResults(akGeographies);
await this.fetchElectionResults(censusStates, censusGeographies);
this.renderLayer();
this.createBars();
this.bindHover();
if (this.counties.length > 60) { // arbitrarily set threshold
setTimeout(() => {
this.selectedMap = "choropleth";
this.renderLayer();
}, 3000);
}
},
methods: {
animateValue(property, newValue) {
const startValue = this[property];
const interpolator = d3.interpolateNumber(startValue, newValue);
d3.select({})
.transition()
.duration(this.transition.duration)
.ease(this.transition.ease) // Ease function applied here
.tween(property, () => (t) => {
this[property] = interpolator(t);
});
},
async getCensusCounties() {
const that = this;
// Enter base year for the county gazetteer files
const censusYear = this.geographies.censusYear;
// Base URL where all the county gazetteer files live
const gazetteerUrl = `https://us-election-server-2ae36243a2a4.herokuapp.com/census/gazetteer/${censusYear}`;
const censusCounties = async function parseCountyGeographyData(censusGazCounties) {
// Function to fetch and parse a single county file
async function fetchCountyFile(countyFileName) {
const response = await fetch(gazetteerUrl + '/' + countyFileName);
const csvText = await response.text();
const parsedData = d3.dsvFormat('\t').parse(csvText, function (d) {
return {
geoid: d['GEOID'],
c_county_name: d['NAME']
};
});
return parsedData;
}
// Read each county file CSV
const censusCountyFilesPromises = censusGazCounties.map(file => fetchCountyFile(file.county_file_name));
const censusCountyFiles = await Promise.all(censusCountyFilesPromises);
// Combine into a single array
const censusCounties = [].concat(...censusCountyFiles);
// Create state FIPS codes from the 5-digit 'geoid'
censusCounties.forEach(county => {
county.state_fips = county.geoid.slice(0, 2);
});
// Log the result
console.log('Shape:', censusCounties.length);
console.log('Data Types:', {
geoid: typeof censusCounties[0].geoid,
c_county_name: typeof censusCounties[0].c_county_name,
state_fips: typeof censusCounties[0].state_fips
});
console.log('First 100 Entries:', censusCounties.slice(0, 100));
return censusCounties;
}
const censusGazCounties = async function getCountyGazFiles() {
// Make an HTTP request for the page
const response = await fetch(gazetteerUrl, {
method: 'GET',
headers: { "Accept": "application/json" }
});
// Parse the page and return a DOM tree
const pageContent = await response.text();
const parser = new DOMParser();
const doc = parser.parseFromString(pageContent, 'text/html');
// Use XPath to return a list of link texts ('a' elements within the 'table' element) from the DOM
const xpathResult = doc.evaluate('//td/a/text()', doc, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
const gazetteerFiles = [];
for (let i = 0; i < xpathResult.snapshotLength; i++) {
gazetteerFiles.push(xpathResult.snapshotItem(i).nodeValue);
}
// Filter the list to return only county file names
const countyFiles = gazetteerFiles.filter(c => /.*counties.*\.txt/.test(c));
// Convert the list to an array of objects
const countyFilesSeries = countyFiles.map(fileName => ({ county_file_name: fileName }));
// Filter out Alaska and these Suzerainty entities
const censusGazCounties = countyFilesSeries.filter(file => {
const match = file.county_file_name.match(/_(\d{2})\.txt/);
return match && !that.geographies.suzeraintyFips.includes(match[1]);
});
// Log the result
console.log('Shape:', censusGazCounties.length);
console.log('Data Types:', censusGazCounties.map(file => typeof file.county_file_name));
console.log('First 100 Entries:', censusGazCounties.slice(0, 100));
return censusGazCounties;
}
return await censusCounties(await censusGazCounties());
},
async getCensusGeograhpies() {
const censusGeographies = await d3.csv(
"2024_us_census_geographies.csv"
);
return censusGeographies;
},
async getCensusStates() {
// Fetch the JSON data
const url = "https://us-election-server-2ae36243a2a4.herokuapp.com/census/state_data";
const response = await fetch(url, { method: "GET" });
const data = await response.text();
// Parse the CSV data using d3.dsv
const allCensusStates = d3.dsvFormat('|').parse(data, function (d) {
return {
state_fips: d.STATE,
state_abbr: d.STUSAB,
c_state_name: d.STATE_NAME
};
});
// Filter out Alaska and these Suzerainty entities
const censusStates = allCensusStates.filter(state => !this.geographies.suzeraintyFips.includes(state.state_fips));
this.states = censusStates.map(state => ({
id: state.state_fips,
name: state.c_state_name
}));
return censusStates;
},
mergeCensusGeographies(censusCounties, censusStates) {
// Convert the input arrays to DataFrames
const censusCountiesDf = new dfd.DataFrame(censusCounties);
const censusStatesDf = new dfd.DataFrame(censusStates);
// Select the relevant columns from censusStates
const selectedCensusStatesDf = censusStatesDf.loc({
columns: ["state_fips", "c_state_name"]
});
// Perform a left join on 'state_fips'
const countyStateDf = dfd.merge({
left: censusCountiesDf,
right: selectedCensusStatesDf,
on: ["state_fips"],
how: "left"
});
// Drop the 'state_fips' column
const censusGeographies = countyStateDf.drop({ columns: ["state_fips"], axis: 1 });
// Log the shape and data types of the resulting DataFrame
console.log("Shape:", censusGeographies.shape);
console.log("Data Types:", censusGeographies.ctypes);
// Print the first 100 rows of the resulting DataFrame
censusGeographies.head(100).print();
// convert back to JSON and return
return dfd.toJSON(censusGeographies);
},
async getDCGeographies() {
// Download the zip file content into memory
const url = `https://us-election-server-2ae36243a2a4.herokuapp.com/census/gazetteer/${this.geographies.censusYear}/dc_sldu`;
const response = await fetch(url, { method: "GET" });
const arrayBuffer = await response.arrayBuffer();
const nationalGazetteerZip = new Uint8Array(arrayBuffer);
// Open the zip file from the in-memory content
const zip = await JSZip.loadAsync(nationalGazetteerZip);
const unzippedFiles = Object.keys(zip.files);
// Find the tab-delimited text file (assuming it's a .txt file)
let tabDelimitedFile = null;
for (const file of unzippedFiles) {
if (file.endsWith(".txt")) {
tabDelimitedFile = file;
break;
}
}
if (!tabDelimitedFile) {
console.error("No tab-delimited text file found.");
return;
}
// Read the tab-delimited text file content
const fileContent = await zip.file(tabDelimitedFile).async("string");
// Parse the tab-delimited text file using d3
const nationalsldusts = d3.dsvFormat('\t').parse(fileContent, function (d) {