-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
422 lines (342 loc) · 10.9 KB
/
Copy pathscript.js
File metadata and controls
422 lines (342 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
const YEAR = new Date().getFullYear();
const METRICS = [
{
id: "posts",
title: "Posts",
get: u => Number(u.posts || 0),
line: v => `You posted ${fmt(v)} times this year.`
},
{
id: "likes",
title: "Likes",
get: u => Number(u.likes || 0),
line: v => `You received ${fmt(v)} likes.`
},
{
id: "views",
title: "Views",
get: u => Number(u.views || 0),
line: v => `You got ${fmt(v)} views.`
},
{
id: "retweets_plus_comments",
title: "RT + Comments",
get: u => Number(u.retweets_plus_comments || 0),
line: v => `${fmt(v)} retweets and comments — nice.`
}
];
const $ = (id) => document.getElementById(id);
// screens
const screenInput = $("screenInput");
const screenRecap = $("screenRecap");
// input
const twInput = $("twInput");
const startBtn = $("startBtn");
const err = $("err");
// header
$("yearLabel").textContent = YEAR;
const userSub = $("userSub");
const pill = $("pill");
const changeUserBtn = $("changeUserBtn");
// identity
const pfp = $("pfp");
const nameEl = $("name");
const twEl = $("tw");
const dcEl = $("dc");
// modes
const slideMode = $("slideMode");
const finalMode = $("finalMode");
// slide elements
const metricTitle = $("metricTitle");
const metricValue = $("metricValue");
const metricLine = $("metricLine");
const ringFg = $("ringFg");
const topLabel = $("topLabel");
const betterLabel = $("betterLabel");
const boxDesc = $("boxDesc");
const rankEl = $("rank");
const bestEl = $("best");
const avgEl = $("avg");
const smallLine = $("smallLine");
// final elements
const finalSubtitle = $("finalSubtitle");
const sumPosts = $("sumPosts");
const sumLikes = $("sumLikes");
const sumViews = $("sumViews");
const sumRTC = $("sumRTC");
const sumPostsTop = $("sumPostsTop");
const sumLikesTop = $("sumLikesTop");
const sumViewsTop = $("sumViewsTop");
const sumRTCTop = $("sumRTCTop");
const finalLine = $("finalLine");
const sum_posts = $("sum_posts");
const sum_likes = $("sum_likes");
const sum_views = $("sum_views");
const sum_rtc = $("sum_rtc");
// under-card buttons
const prevBtn = $("prevBtn");
const nextBtn = $("nextBtn");
// state
let users = [];
let selected = null;
let slideIdx = 0;
let inFinal = false;
// used to cancel in-flight animations when user clicks prev/next
let runId = 0;
// helpers
function normNick(s){ return String(s||"").trim().replace(/^@/,"").toLowerCase(); }
function fmt(n){ return Number(n||0).toLocaleString("en-US"); }
function mean(arr){ return arr.length ? arr.reduce((a,b)=>a+b,0)/arr.length : 0; }
function upgradeTwitterPfp(url){
const u = String(url || "");
if (!u) return u;
if (u.includes("_normal.")) return u.replace("_normal.", "_400x400.");
if (u.includes("_normal")) return u.replace("_normal", "_400x400");
return u;
}
function calcPlacement(values, v){
const N = values.length || 1;
const higher = values.filter(x => x > v).length;
const lower = values.filter(x => x < v).length;
const rank = higher + 1;
const betterThan = Math.floor((lower / N) * 100);
const topPercent = Math.max(1, 100 - betterThan);
const best = Math.max(...values, 0);
const avg = mean(values);
return {N, rank, betterThan, topPercent, best, avg};
}
function setRingByTop(topPercent){
const circ = 302;
const fill = Math.max(0, Math.min(100, 100 - topPercent));
const offset = circ * (1 - fill/100);
ringFg.style.strokeDasharray = circ;
ringFg.style.strokeDashoffset = offset;
}
function showInput(){
screenInput.classList.add("active");
screenRecap.classList.remove("active");
}
function showRecap(){
screenRecap.classList.add("active");
screenInput.classList.remove("active");
}
function setNextEnabled(enabled){
nextBtn.disabled = !enabled;
}
function showSlideMode(){
inFinal = false;
slideMode.classList.add("mode--active");
finalMode.classList.remove("mode--active");
pill.textContent = "RECAP";
setNextEnabled(true);
}
function showFinalMode(){
inFinal = true;
finalMode.classList.add("mode--active");
slideMode.classList.remove("mode--active");
pill.textContent = "FINAL";
setNextEnabled(false);
}
function resetSlideUI(){
metricValue.textContent = "0";
metricLine.textContent = "—";
topLabel.textContent = "TOP —%";
betterLabel.textContent = "better than —%";
topLabel.classList.remove("show");
betterLabel.classList.remove("show");
ringFg.style.strokeDashoffset = 302;
boxDesc.textContent = "—";
rankEl.textContent = "#—";
bestEl.textContent = "—";
avgEl.textContent = "—";
}
function animateCountCancellable(el, to, duration, myRunId){
const from = Number(String(el.textContent).replace(/[^0-9.-]/g,"")) || 0;
const start = performance.now();
const target = Number(to||0);
return new Promise(resolve => {
function tick(now){
if (myRunId !== runId) return resolve(false); // cancelled
const t = Math.min(1, (now-start)/duration);
const eased = 1 - Math.pow(1-t, 3);
const value = from + (target-from)*eased;
el.textContent = fmt(Math.round(value));
if(t<1) requestAnimationFrame(tick);
else resolve(true);
}
requestAnimationFrame(tick);
});
}
function waitCancellable(ms, myRunId){
return new Promise(resolve => {
const t = setTimeout(() => resolve(true), ms);
const check = () => {
if (myRunId !== runId) {
clearTimeout(t);
return resolve(false);
}
requestAnimationFrame(check);
};
requestAnimationFrame(check);
});
}
function metricValues(metric){ return users.map(u => metric.get(u)); }
function fillUser(u){
const dc = String(u.discord_nickname || "—");
const name = dc.includes("#") ? dc.split("#")[0] : dc;
userSub.textContent = `@${u.twitter_nickname} • ${YEAR}`;
nameEl.textContent = name;
twEl.textContent = "@"+(u.twitter_nickname || "—");
dcEl.textContent = dc;
// upgraded pfp
pfp.src = upgradeTwitterPfp(u.pfp);
pfp.onerror = () => {
// fallback: if 400x400 fails, try stripping "_normal"
const raw = String(u.pfp || "");
if (raw.includes("_normal")) pfp.src = raw.replace("_normal", "");
};
smallLine.textContent = `user: @${u.twitter_nickname} • slides: ${METRICS.length}`;
}
async function playSlide(i){
if(!selected) return;
runId++;
const myRunId = runId;
showSlideMode();
slideIdx = Math.max(0, Math.min(METRICS.length-1, i));
const metric = METRICS[slideIdx];
metricTitle.textContent = metric.title;
resetSlideUI();
const v = metric.get(selected);
const values = metricValues(metric);
const place = calcPlacement(values, v);
const ok1 = await animateCountCancellable(metricValue, v, 950, myRunId);
if(!ok1) return;
const ok2 = await waitCancellable(200, myRunId);
if(!ok2) return;
metricLine.textContent = metric.line(v);
const ok3 = await waitCancellable(220, myRunId);
if(!ok3) return;
topLabel.textContent = `TOP ${place.topPercent}%`;
betterLabel.textContent = `better than ${place.betterThan}%`;
topLabel.classList.add("show");
betterLabel.classList.add("show");
const ok4 = await waitCancellable(160, myRunId);
if(!ok4) return;
setRingByTop(place.topPercent);
const ok5 = await waitCancellable(220, myRunId);
if(!ok5) return;
rankEl.textContent = "#"+place.rank;
bestEl.textContent = fmt(Math.round(place.best));
avgEl.textContent = fmt(Math.round(place.avg));
boxDesc.textContent = `You are in the top ${place.topPercent}% for “${metric.title}” out of ${place.N} users.`;
}
function clearBestHighlights(){
[sum_posts, sum_likes, sum_views, sum_rtc].forEach(el => el.classList.remove("best"));
}
function showFinal(){
if(!selected) return;
runId++;
showFinalMode();
clearBestHighlights();
const placements = {};
for (const m of METRICS) {
const v = m.get(selected);
const values = metricValues(m);
placements[m.id] = { v, ...calcPlacement(values, v) };
}
sumPosts.textContent = fmt(placements.posts.v);
sumLikes.textContent = fmt(placements.likes.v);
sumViews.textContent = fmt(placements.views.v);
sumRTC.textContent = fmt(placements.retweets_plus_comments.v);
sumPostsTop.textContent = `TOP ${placements.posts.topPercent}%`;
sumLikesTop.textContent = `TOP ${placements.likes.topPercent}%`;
sumViewsTop.textContent = `TOP ${placements.views.topPercent}%`;
sumRTCTop.textContent = `TOP ${placements.retweets_plus_comments.topPercent}%`;
finalSubtitle.textContent = `All metrics for ${YEAR}`;
const best = Object.entries(placements)
.map(([id, p]) => ({ id, top: p.topPercent }))
.sort((a,b)=> a.top - b.top)[0];
const titleMap = {
posts: "Posts",
likes: "Likes",
views: "Views",
retweets_plus_comments: "RT + Comments"
};
const cardMap = {
posts: sum_posts,
likes: sum_likes,
views: sum_views,
retweets_plus_comments: sum_rtc
};
cardMap[best.id]?.classList.add("best");
finalLine.textContent = `Best metric: ${titleMap[best.id]} — TOP ${best.top}%`;
}
function goNext(){
if(!selected) return;
if(inFinal){
return;
}
if(slideIdx < METRICS.length - 1){
playSlide(slideIdx + 1);
} else {
showFinal();
}
}
function goPrev(){
if(!selected) return;
if(inFinal){
playSlide(METRICS.length - 1);
return;
}
if(slideIdx > 0){
playSlide(slideIdx - 1);
}
}
fetch("./users_stats.json")
.then(r => r.json())
.then(data => {
users = Array.isArray(data) ? data : (data.users_stats || []);
if(!users.length){
err.textContent = "users_stats.json is empty or not an array";
return;
}
twInput.focus();
})
.catch(() => {
err.textContent = "Failed to load users_stats.json (use a local server / correct path)";
});
function findUser(nick){
const n = normNick(nick);
return users.find(u => normNick(u.twitter_nickname) === n) || null;
}
function startRecap(){
err.textContent = "";
const u = findUser(twInput.value);
if(!u){
err.textContent = "User not found in users_stats.json";
return;
}
selected = u;
slideIdx = 0;
inFinal = false;
setNextEnabled(true);
fillUser(u);
showRecap();
playSlide(0);
}
startBtn.addEventListener("click", startRecap);
twInput.addEventListener("keydown", (e) => { if(e.key === "Enter") startRecap(); });
changeUserBtn.addEventListener("click", () => {
selected = null;
inFinal = false;
runId++;
showInput();
twInput.focus();
});
prevBtn.addEventListener("click", goPrev);
nextBtn.addEventListener("click", goNext);
document.addEventListener("keydown", (e) => {
if(!screenRecap.classList.contains("active")) return;
if(e.key === "ArrowRight") goNext();
if(e.key === "ArrowLeft") goPrev();
});