forked from alex/nyt-2020-election-scraper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbattleground-state-changes.html.tmpl
371 lines (320 loc) · 13.8 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
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
<!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;
}
thead td {
background-color: #e9ecef;
line-height: 1.2rem;
}
thead .text-left {
font-weight: normal;
}
thead span.statename {
font-weight: bold;
/* If changing these, update "thead tr:nth-child(2) th" too */
font-size: 1.2rem;
line-height: 1.2rem;
}
thead tr:nth-child(1) td {
position: sticky;
top: -1px;
border-bottom: none;
}
thead tr:nth-child(2) th {
position: sticky;
/* Padding, first line, second line, padding */
top: calc(.25rem + 1.2rem + 1.2rem + .25rem);
border-right: none;
border-left: none;
border-top: none;
}
.has-tip:after{
content: "\2139\fe0f";
margin-left: 5px;
}
.flag-bg {
background-position: fixed;
background-repeat: no-repeat;
background-size: auto 100%;
background-position: 100%;
}
.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, .table .thead-light td {
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>
<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 type="text/javascript">
dayjs.extend(dayjs_plugin_relativeTime)
dayjs.extend(dayjs_plugin_utc)
const prettyTime = timestamp => dayjs.utc(timestamp.replace(" UTC", ""), 'YYYY-MM-DD HH:MM:SS').fromNow()
const handleNode = node => {
if (node.classList && node.classList.contains('timestamp')) {
let timestamp;
if (node.hasAttribute('data-timestamp')) {
timestamp = node.getAttribute('data-timestamp');
} else {
timestamp = node.innerHTML;
node.setAttribute('data-timestamp', timestamp);
}
node.innerHTML = `<abbr class='pretty-timestamp' title='${timestamp}'>${prettyTime(timestamp)}</abbr>`;
}
};
new MutationObserver(mutations => {
for (let i = 0, len = mutations.length; i < len; i++) {
let added = mutations[i].addedNodes;
for (let j = 0, node; (node = added[j]); j++) {
if (node.tagName === 'td' || node.tagName === 'span') {
handleNode(node);
} else if (node.firstElementChild) {
for (const child of node.querySelectorAll('td,span')) {
handleNode(child);
}
}
}
}
}).observe(document, {
childList: true,
subtree: true,
});
setInterval(() => {
$(".pretty-timestamp").map((_, tselem) => {
tselem.innerText = prettyTime(tselem.title);
});
}, 60 * 1000);
</script>
</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>
<div id="template-hash" style="display: none;">{% TEMPLATE_HASH %}</div>
<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://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">
const loadTooltips = () => {
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
};
loadTooltips();
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 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]; // oh well, default to latest
};
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,
};
};
const isDeveloperEnvironment = () => {
return location.protocol === 'file:' || location.hostname === 'localhost' || location.hostname === '127.0.0.1';
};
const updateCheck = async (currentCommit, notify) => {
let latestCommit = await fetchLatestCommit();
console.log("latest commit", latestCommit);
if (currentCommit['sha'] !== latestCommit['sha']) {
console.log("updating to", latestCommit);
let latestContent = await fetchLatestContent(latestCommit['sha']);
console.log("latest content", latestContent.updates);
if (notify && latestContent.updates.states_updated.length) {
if (Notification.permission === "granted") {
new Notification(`New ballots were counted in: ${latestContent.updates.states_updated.join(", ")}!`);
}
}
let newHash = latestContent.dom.getElementById("template-hash")?.innerText;
let currentHash = document.getElementById("template-hash").innerText;
if (newHash && newHash !== currentHash && !isDeveloperEnvironment()) {
location.reload(true);
} else {
const elementsToUpdate = [
...Array.from(document.getElementsByTagName("table")),
document.getElementById("timestamps"),
];
elementsToUpdate.forEach(oldElement => {
let newElement = latestContent.dom.getElementById(oldElement.id);
oldElement.parentNode.replaceChild(newElement, oldElement);
});
loadTooltips();
refreshFeature(shrinkTablesFeature);
}
}
return latestCommit;
};
// do an initial update
if (!isDeveloperEnvironment()) {
updateCheck({}, false);
}
const startLiveUpdates = async () => {
let currentCommit = await fetchLatestCommit();
console.log("current commit", currentCommit);
const nextCheck = () => {
const ONE_MINUTE = 1 * 60 * 1000;
const FIVE_MINUTES = 5 * ONE_MINUTE;
const now = new Date();
const lastUpdate = new Date(currentCommit.commit.author.date);
// check at most every minute
return Math.max(ONE_MINUTE, FIVE_MINUTES - (now - lastUpdate));
};
const runner = async () => {
if (!isFeatureEnabled(liveUpdatesFeature)) return;
currentCommit = await updateCheck(currentCommit, true);
console.log("new current commit", currentCommit);
setTimeout(runner, nextCheck());
};
setTimeout(runner, nextCheck());
};
const liveUpdatesFeature = 'live-updates';
feature(liveUpdatesFeature, '#live_update_button', button => {
button.html('Disable Live Updates');
if ('Notification' in window && Notification.permission !== 'granted') {
Notification.requestPermission();
}
startLiveUpdates();
}, button => {
button.html('Enable Live Updates');
});
</script>
</body>