forked from alex/nyt-2020-election-scraper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
battleground-state-changes.html.tmpl
289 lines (250 loc) · 11.1 KB
/
battleground-state-changes.html.tmpl
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
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="twitter:card" content="summary" />
<meta name="twitter:title" content="ANN Election Data" />
<meta name="twitter:description" content="Battleground state changes, updated every five minutes using NYT data." />
<meta name="twitter:url" content="https://alex.github.io/nyt-2020-election-scraper/battleground-state-changes.html" />
<meta property="og:title" content="ANN Election Data" />
<meta property="og:description" content="Battleground state changes, updated every five minutes using NYT data." />
<meta property="og:image" content="https://avatars3.githubusercontent.com/u/772?s=400&u=7c00c7c8ac3691da556d7686e16ff08b797d4a38&v=4" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=yes">
<link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>🗳️</text></svg>">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<style>
body {
margin: 1rem;
}
.table td, .table th {
padding: .25rem .5rem;
}
.table th.text-left {
font-weight: normal;
}
.table th span.statename {
font-weight: bold;
font-size: 14pt;
}
thead tr:nth-child(1) th {
position: sticky;
top: -1px;
}
thead tr:nth-child(2) th {
position: sticky;
top: calc(.25rem + 1.5rem + 2px);
border-right: none;
border-left: none;
}
.has-tip:after{
content: "\2139\fe0f";
margin-left: 5px;
}
.Biden{
background-color: #84C4EE
}
.Trump{
background-color: #ED98A9;
}
@media (prefers-color-scheme: dark) {
body {
color: #ffffff;
background-color: #202020;
}
.table {
color: #dedad6;
background-color: #202020;
}
.table .thead-light th {
background-color: #495057;
color: #e9ecef;
}
.table .thead-light th, .table td {
border-color: #211d19;
}
.Biden {
background-color: #05456F;
}
.Trump {
background-color: #6E192A;
}
}
</style>
<title>Election 2020 Results</title>
</head>
<body>
<p style="font-size: 1.4rem;">
All data below is sourced from an unofficial API powering the New York Times’ election site.
<strong>The estimated votes remaining values might be off</strong>.
Consult state websites and officials for the most accurate and up-to-date figures.
This website is <a href="https://github.com/alex/nyt-2020-election-scraper">open source</a> and was written by <a href="https://github.com/alex/nyt-2020-election-scraper/graphs/contributors">these people</a>.
</p>
<p class="float-left" id="timestamps">Last scrape: <span class="timestamp">{% SCRAPE_TIME %}</span> | Last batch: <span class="timestamp">{% BATCH_TIME %}</span></p>
<p class="float-right">
<button type='button' id='live_update_button' class='btn btn-secondary'>Enable Live Updates</button>
<button type='button' id='shrink_button' class='btn btn-secondary'>Shrink Tables</button>
</p>
{% TABLES %}
<script src="https://unpkg.com/[email protected]/dayjs.min.js"
integrity="sha384-cuApTuVdn64P5ZOzyf+qTgNxGwhvW/ZmdAbNMcl7Q3TkMKJ7/bERQ1cFDmZy7QvZ"
crossorigin="anonymous"></script>
<script src="https://unpkg.com/[email protected]/plugin/utc.js"
integrity="sha384-r1JLNIu5SkAfQejSOJPjndnEZkxex5ChJOTaiQeN91L012sA1pyw0A/543Xq97wb"
crossorigin="anonymous"></script>
<script src="https://unpkg.com/[email protected]/plugin/relativeTime.js"
integrity="sha384-ojZWhTxW4vjtUz9IjuxEgcPAQQkFj7jlcOnGFp8IyTUTQpFisDT5u8zFh2d0GrSM"
crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx"
crossorigin="anonymous"></script>
<script type="text/javascript">
const features = {};
const isFeatureEnabled = key => localStorage.getItem(key) === 'true';
const feature = (key, buttonId, onEnable, onDisable) => {
const button = $(buttonId);
button.on('click', function() {
if (isFeatureEnabled(key)) {
localStorage.removeItem(key);
onDisable(button);
} else {
localStorage.setItem(key, 'true');
onEnable(button);
}
});
if (isFeatureEnabled(key)) {
onEnable(button);
}
features[key] = {
buttonId,
onEnable,
onDisable
};
};
const refreshFeature = key => {
if (isFeatureEnabled(key)) {
features[key].onEnable($(features[key].buttonId));
} else {
features[key].onDisable($(features[key].buttonId));
}
};
</script>
<script type="text/javascript">
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
dayjs.extend(dayjs_plugin_relativeTime)
dayjs.extend(dayjs_plugin_utc)
const prettyTimestamps = () => {
$(".timestamp").map(function (idx, tselem) {
tselem.innerHTML = "<abbr class='pretty-timestamp' title='" + tselem.innerHTML + "'>" + dayjs.utc(tselem.innerHTML.replace(" UTC", ""), 'YYYY-MM-DD HH:MM:SS').fromNow() + "</abbr>"
})
};
prettyTimestamps();
const updateTimestamps = () => {
$(".pretty-timestamp").map(function (idx, tselem) {
tselem.innerText = dayjs.utc(tselem.title.replace(" UTC", ""), 'YYYY-MM-DD HH:MM:SS').fromNow()
})
};
setInterval(updateTimestamps, 60 * 1000);
const shrinkTablesFeature = 'shrunk';
feature(shrinkTablesFeature, '#shrink_button', button => {
button.html('Expand Tables');
$('.table').each(function(){
var countOfNonHiddenBlock = 0;
var lastCount = -1;
$(this).find('tbody tr').each(function() {
var value = parseInt(($(this).find('td:nth(4)').text()));
if (countOfNonHiddenBlock >= 3 || (value === 0 && lastCount === 0)) {
$(this).hide();
} else {
countOfNonHiddenBlock++;
}
lastCount = value;
});
});
}, button => {
button.html('Shrink Tables');
$('.table').each(function() { $(this).find('tbody tr').show(); });
});
</script>
<script type="text/javascript">
const liveUpdatesFeature = 'live-updates';
feature(liveUpdatesFeature, '#live_update_button', button => {
button.html('Disable Live Updates');
if (!('Notification' in window)) {
return;
}
if (Notification.permission !== "denied") {
Notification.requestPermission();
}
}, button => {
button.html('Enable Live Updates');
});
(async function() {
const fetchLatestCommit = async () => {
const response = await fetch("https://api.github.com/repos/alex/nyt-2020-election-scraper/commits?per_page=10", {
cache: 'no-cache',
headers: {
accept: 'application/vnd.github.v3+json',
},
});
const body = await response.json();
for (var i = 0; i < body.length; i++) {
if (body[i]['commit']['author']['email'] === '[email protected]' &&
body[i]['commit']['message'] === 'Regenerate battleground-state-changes.txt/html') {
return body[i];
}
}
return body[0]; // ???
};
const fetchLatestContent = async (sha) => {
const contentResponse = await fetch(`https://raw.githubusercontent.com/alex/nyt-2020-election-scraper/${sha}/battleground-state-changes.html`, {
cache: 'no-cache',
});
const contentBody = await contentResponse.text();
const contentDom = new DOMParser().parseFromString(contentBody, 'text/html');
const updatesResponse = await fetch(`https://raw.githubusercontent.com/alex/nyt-2020-election-scraper/${sha}/notification-updates.json`, {
cache: 'no-cache',
});
const updatesBody = await updatesResponse.json();
return {
updates: updatesBody,
dom: contentDom,
};
};
let currentCommit = await fetchLatestCommit();
console.log("current commit", currentCommit);
// live updates
setInterval(async function() {
if (!isFeatureEnabled(liveUpdatesFeature)) return;
let latestCommit = await fetchLatestCommit();
console.log("latest commit", latestCommit);
if (currentCommit['sha'] !== latestCommit['sha']) {
let latestContent = await fetchLatestContent(latestCommit['sha']);
console.log("latest content", latestContent.updates);
if (latestContent.updates.states_updated.length) {
Array.from(document.getElementsByTagName("table")).forEach(table => {
let newTable = latestContent.dom.getElementById(table.id);
table.parentNode.replaceChild(newTable, table);
});
let newTimestamps = latestContent.dom.getElementById("timestamps");
let currTimestamps = document.getElementById("timestamps");
currTimestamps.parentNode.replaceChild(newTimestamps, currTimestamps);
prettyTimestamps();
refreshFeature(shrinkTablesFeature);
currentCommit = latestCommit;
if (Notifcation.permission === "granted") {
new Notification(`New ballots were counted in: ${latestContent.updates.states_updated.join(", ")}!`);
}
}
}
}, 5 * 60 * 1000);
})();
</script>
</body>