forked from hryanjones/guess-my-word
-
Notifications
You must be signed in to change notification settings - Fork 0
/
board.js
451 lines (401 loc) · 13.8 KB
/
board.js
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
/* global
Vue,
getTimezonelessLocalDate,
UNKNOWN_LEADERBOARD_ERROR,
makeLeaderboardRequest,
getFormattedTime,
urlParams,
IS_LOCAL_STORAGE_AVAILABLE,
getSavedGameByDifficulty,
isToday,
now,
getStoredUserNames,
WordCloud,
*/
const LEADER_HEADER_FIELDS_BY_TYPE = {
normal: [
{ text: 'name', key: 'name' },
{ text: '# guesses', key: 'numberOfGuesses' },
{ text: 'time', key: 'time', formatter: getFormattedTime },
{ text: 'awards', key: 'awards' },
{ text: 'guesses', key: 'guesses' },
],
allTime: [
{ text: 'name', key: 'name' },
{ text: 'weekly play rate', key: 'weeklyPlayRate', formatter: getTwoDecimalPlaces },
{ text: '# plays', key: 'playCount' },
{ text: 'best time', key: 'bestTime', formatter: getFormattedTime },
{ text: 'median time', key: 'timeMedian', formatter: getFormattedTime },
{ text: 'best # guesses', key: 'bestNumberOfGuesses' },
{ text: 'median # guesses', key: 'numberOfGuessesMedian' },
{ text: 'first play date', key: 'firstSubmitDate', formatter: removeTimeFromISOString },
{ text: 'awards', key: 'awards' },
],
};
const allHeaderFields = LEADER_HEADER_FIELDS_BY_TYPE.normal
.concat(LEADER_HEADER_FIELDS_BY_TYPE.allTime);
// add default pass-through formatter
allHeaderFields.forEach((field) => {
field.formatter = field.formatter || passThrough;
});
const EMPTY_LEADER = {}; // the empty leader is required for the virtualized board to render
allHeaderFields.map(field => field.key).forEach((key) => {
EMPTY_LEADER[key] = '';
});
const DEFAULT_SORT_CONFIG_BY_LEADER_TYPE = {
normal: {
key: 'numberOfGuesses',
direction: 'ascending',
},
allTime: {
key: 'weeklyPlayRate',
direction: 'descending',
},
};
const difficultyFromURL = urlParams.get('difficulty');
const searchFromURL = urlParams.get('search');
const app = new Vue({ // eslint-disable-line no-unused-vars
el: '#leaderboard-container',
data: {
leadersType: 'normal',
leaders: [EMPTY_LEADER],
difficulty: difficultyFromURL || 'normal',
message: '',
error: '',
sortConfig: DEFAULT_SORT_CONFIG_BY_LEADER_TYPE.normal,
leaderSearch: searchFromURL || '',
filteredLeaders: null,
hasPlayedThisBoardToday: null, // determined in getLeaders
usedNames: getStoredUserNames(),
leaderHeaderFields: null, // determined in getLeaders
wordCloudData: null,
wordCloudCanvas: null,
},
created() {
this.getLeaders();
},
methods: {
getLeaders,
setDifficulty(e) {
const newDifficulty = e.target.value;
this.difficulty = newDifficulty;
this.getLeaders();
},
changeLeaderSort,
toggleLeaderType() {
this.leadersType = this.leadersType === 'normal' ? 'allTime' : 'normal';
this.sortConfig = DEFAULT_SORT_CONFIG_BY_LEADER_TYPE[this.leadersType];
this.getLeaders();
},
updateLeaderSearch(e) {
this.leaderSearch = e.target.value;
},
onSearch(e) {
const searchTerm = this.leaderSearch.trim().toLowerCase();
if (!searchTerm) {
this.filteredLeaders = null;
} else {
this.filteredLeaders = this.leaders.filter(leader => (
leader.name.toLowerCase().includes(searchTerm)
));
}
return !e; // return false if it's from submit
},
clearSearch() {
this.leaderSearch = '';
this.onSearch();
},
areLeadersLoaded() {
return this.leaders[0] !== EMPTY_LEADER;
},
toggleWordCloud() {
const wordCloudContainer = document.getElementById('word-cloud-container');
if (this.wordCloudCanvas) {
wordCloudContainer.innerHTML = '';
this.wordCloudCanvas = null;
return;
}
this.wordCloudCanvas = document.createElement('div');
this.wordCloudCanvas.id = 'word-cloud-canvas';
wordCloudContainer.append(this.wordCloudCanvas);
let i = 0;
WordCloud(
this.wordCloudCanvas,
{
list: this.wordCloudData,
fontFamily: 'sans-serif',
color: stripedColorsBlackToGray, // 'random-dark',
minRotation: 0,
maxRotation: 0,
drawOutOfBound: false,
shrinkToFit: true,
gridSize: 10,
minSize: 8,
}
);
function stripedColorsBlackToGray() {
let n = i * 2;
if (i % 2 !== 0) {
n += 120;
}
i += 1;
n = Math.min(200, n);
return `rgb(${n}, ${n}, ${n})`;
}
},
},
});
function hackToReRenderList(leaders) {
// HACK ALERT: modify leaders to get the list to re-render
leaders.push(EMPTY_LEADER);
leaders.pop();
}
function noop() { }
const throttledHandleScroll = throttle(handleScroll, 100);
document.addEventListener('scroll', throttledHandleScroll, true);
function handleScroll() {
const header = document.getElementById('leaderboard-header');
if (!header) return;
const headerTop = document.getElementById('leaderboard-header-top');
const headerTopPosition = headerTop && headerTop.getBoundingClientRect();
const top = (headerTopPosition && headerTopPosition.top) || 0;
if (top < 0) {
if (header.style.position !== 'fixed') header.style.position = 'fixed';
header.style.left = `${headerTopPosition.left}px`;
return;
}
if (header.style.position !== 'static') header.style.position = 'static';
}
function getLeaders() {
let date;
const type = this.leadersType;
if (type === 'allTime') {
date = 'ALL';
} else {
date = getTimezonelessLocalDate(new Date());
}
this.hasPlayedThisBoardToday = determineIfPlayedThisBoardToday(this.difficulty, type);
this.leaderHeaderFields = LEADER_HEADER_FIELDS_BY_TYPE[type];
if (!this.hasPlayedThisBoardToday && type === 'normal') {
// remove guesses column if we won't have the data
this.leaderHeaderFields = LEADER_HEADER_FIELDS_BY_TYPE.normal.filter(h => h.key !== 'guesses');
}
const onSuccess = (json) => {
const { key, direction } = this.sortConfig;
try {
this.leaders = sortLeaders(
normalizeLeadersAndAddAwards(json),
key,
direction,
);
} catch (e) {
console.error(e);
this.message = '';
this.error = 'Sorry, having trouble dealing with the response from the leaderboard. Please let @guessmyword1 know.';
return;
}
this.error = '';
if (this.leaders.length === 0) {
this.message = 'nobody has guessed the word for today';
this.leaders = [EMPTY_LEADER];
} else {
this.onSearch();
this.message = '';
this.wordCloudData = getWordCloudData(this.leaders);
}
};
const onFailure = () => {
this.leaders = [EMPTY_LEADER];
this.message = '';
this.error = UNKNOWN_LEADERBOARD_ERROR;
};
this.message = 'loading...';
this.leaders = [EMPTY_LEADER];
this.wordCloudData = null;
this.wordCloudCanvas = null;
const queryString = getQueryStringForIncludingGuesses(this.hasPlayedThisBoardToday, this.difficulty);
makeLeaderboardRequest(date, this.difficulty, onSuccess, onFailure, null, queryString);
}
function determineIfPlayedThisBoardToday(difficulty, type) {
// return true // GUESSES TEST
if (type === 'allTime') return false; // can't report on all time board
const savedGame = getSavedGameByDifficulty(difficulty);
return Boolean(savedGame && savedGame.submitTime && isToday(savedGame.submitTime));
}
function getQueryStringForIncludingGuesses(hasPlayed, difficulty) {
// return '?name=miguelpotts&key=pop' // GUESSES TEST
const savedGame = getSavedGameByDifficulty(difficulty);
if (!hasPlayed || !savedGame) return '';
const { username, guesses } = savedGame;
const [firstGuess] = guesses;
return `?name=${encodeURIComponent(username)}&key=${firstGuess}`;
}
const OPPOSITE_SORT_DIRECTION = {
ascending: 'descending',
descending: 'ascending',
};
function changeLeaderSort(newKey) {
let { direction, key } = this.sortConfig;
if (newKey === this.sortConfig.key) {
direction = OPPOSITE_SORT_DIRECTION[direction];
} else {
key = newKey;
}
this.sortConfig = { direction, key };
this.leaders = sortLeaders(this.leaders, key, direction);
this.onSearch();
}
const SECONDARY_SORT_KEY_BY_PRIMARY_SORT_KEY = {
name: null, // don't need a secondary sort key as name should be unique
numberOfGuesses: 'time',
time: 'numberOfGuesses',
};
function sortLeaders(leaders, sortKey, direction) {
return sortArrayByKey(leaders, sortKey, direction);
}
function sortArrayByKey(array, key, direction) {
const sorter = direction === 'descending' ? sortByKeyDesc : sortByKeyAsc;
const arrayCopy = array.slice(0);
const secondaryKey = SECONDARY_SORT_KEY_BY_PRIMARY_SORT_KEY[key];
const bareSorted = arrayCopy.sort((first, second) => sorter(first, second, key, secondaryKey));
return putLuckyBuggersAtTheBottom(bareSorted);
}
function sortByKeyAsc(first, second, key, secondaryKey) {
// always do caseinsensitive sorting
const firstValue = lowercase(first[key]);
const secondValue = lowercase(second[key]);
if (firstValue > secondValue) {
return 1;
}
if (firstValue < secondValue) {
return -1;
}
if (secondaryKey) {
return sortByKeyAsc(first, second, secondaryKey);
}
return 0;
}
function lowercase(value) {
return (value && value.toLowerCase && value.toLowerCase()) || value;
}
function sortByKeyDesc(first, second, key, secondaryKey) {
return -1 * sortByKeyAsc(first, second, key, secondaryKey);
}
const LUCKY_AWARD = '🍀 lucky?';
function putLuckyBuggersAtTheBottom(array) {
if (array.length <= 1) {
return array;
}
const luckyBuggers = [];
const goodPeople = [];
array.forEach((record) => {
if (isLuckyRecord(record)) {
luckyBuggers.push(record);
} else {
goodPeople.push(record);
}
});
return goodPeople.concat(luckyBuggers);
}
function isLuckyRecord(record) {
return record.awards.includes(LUCKY_AWARD);
}
function normalizeLeadersAndAddAwards(leadersData) {
return leadersData.map((leader) => {
leader.awards = leader.awards || ''; // normalize awards
if (leader.firstSubmitDate) {
leader.firstSubmitDate = leader.firstSubmitDate.replace(/T.*/, ''); // remove time portion
}
if (leader.guesses) {
leader.guesses = joinWithSpaces(leader.guesses);
} else {
leader.guesses = '';
}
return leader;
});
}
function passThrough(input) {
return input;
}
function removeTimeFromISOString(dateString) {
return dateString && dateString.replace(/T.*/, '');
}
function getTwoDecimalPlaces(number) {
return number && number.toFixed(2);
}
function joinWithSpaces(array) {
return array && array.join && array.join(' ');
}
function getWordCloudData(leaders) {
let maxWordFrequency = 0;
const wordFrequency = {};
leaders.forEach(({ guesses }) => {
guesses = (guesses && guesses.split(' ')) || ['word'];
guesses.pop(); // last word is the word, remove it
guesses.forEach((guess) => {
if (!wordFrequency[guess]) {
wordFrequency[guess] = 0;
}
wordFrequency[guess] += 1;
if (wordFrequency[guess] > maxWordFrequency) {
maxWordFrequency = wordFrequency[guess];
}
});
});
// remove words only used once
// Object.keys(wordFrequency).forEach((word) => {
// if (wordFrequency[word] === 1) {
// delete wordFrequency[word];
// }
// });
if (maxWordFrequency < 10 || Object.keys(wordFrequency) < 5) {
return null;
}
return toWordCloud2List(wordFrequency);
}
function toWordCloud2List(wordFrequency) {
const list = [];
Object.keys(wordFrequency).forEach((word) => {
list.push([word, wordFrequency[word]]);
});
list.sort(([, aFrequency], [, bFrequency]) => bFrequency - aFrequency);
return list;
}
function randomColor() {
const randomUpTo200 = Math.round(Math.random() * 200);
return `rgb(${randomUpTo200}, ${randomUpTo200}, ${randomUpTo200})`;
}
/* eslint-disable */
// stolen and modified from
// https://stackoverflow.com/questions/27078285/simple-throttle-in-js
// FIXME fix the linting in this thing
function throttle(func, wait) {
var context, args, result;
var timeout = null;
var previous = 0;
var later = function () {
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null;
};
const trailing = true;
return function () {
var now = Date.now();
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
previous = now;
result = func.apply(context, args);
if (!timeout) context = args = null;
} else if (!timeout && trailing) {
timeout = setTimeout(later, remaining);
}
return result;
};
};
/* eslint-enable */