This repository has been archived by the owner on Jul 20, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathscript.ts
623 lines (555 loc) · 17.6 KB
/
script.ts
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
//Warning make sure you are editing the ts file and not the js file
var legalAge = 18;
let siteName = "Is Your Waifu Legal?";
//units
let millisecond : number = 1;
let second : number = 1000 * millisecond;
let minute : number = 60 * second;
let hour : number = 60 * minute;
let day : number = 24 * hour;
var countdown : number = -1;
let months : Array<string> = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
];
function hasValue(data: JSON, key: string) : boolean {
try {
return data.hasOwnProperty(key) && <any>data[key] !== null;
} catch (error) {
return false;
}
}
function hasYear(waifu : JSON) : boolean {
return hasValue(waifu, "year");
}
function hasMonth(waifu : JSON) : boolean {
return hasValue(waifu, "month");
}
function hasDay(waifu : JSON) : boolean {
return hasValue(waifu, "day-of-month");
}
function getCountdownHTML(countdownTime : number) : string {
//sanity check
if (countdownTime === undefined) {
return "";
}
let currentDate : Date = new Date();
let currentTime : number = currentDate.getTime();
let difference : number = countdownTime - currentTime;
let seconds : number = Math.floor((difference % minute) / second);
let minutes : number = Math.floor((difference % hour) / minute);
let hours : number = Math.floor((difference % day) / hour);
let days : number = Math.floor(difference / day);
//To do calculate years, take into account leap years.
let html : string = "Countdown to 18th birthday: "
html += days + " days ";
html += hours + " hours ";
html += minutes + " minutes ";
html += seconds + " seconds<br>\n";
return html;
}
function getAgeHTML(waifu : JSON) : string {
let html : string = "";
if (hasYear(waifu)) {
let currentDate : Date = new Date();
let age : number = currentDate.getFullYear() - waifu["year"];
//take into count the month
if (hasMonth(waifu)) {
let month : number = waifu["month"];
let currentMonth : number = currentDate.getMonth() + 1;
if (
(
currentMonth < month
) || (
//take into count the day
currentMonth === month &&
waifu.hasOwnProperty("day-of-month") &&
waifu["day-of-month"] !== null &&
currentDate.getDay() < waifu["day-of-month"]
)
) {
--age;
}
}
html += "age: ";
html += age.toString();
html += " years old<br>\n"
if (legalAge <= age) {
html += "Looks legal to me.<br>\n"
//stop timer
if (countdown !== -1) {
clearInterval(countdown);
//congrats, your waifu is now of legal age
}
} else {
html += "Not legal<br>\n" +
"Wait ";
html += legalAge - age;
html += " more years.<br>\n"
//We need to start the timer before we can display it
if (countdown === -1) {
countdown = window.setInterval(function() {
let countdownElement : HTMLElement | null = document.getElementById("dynamic-data");
if (countdownElement !== null) {
countdownElement.innerHTML = getDynamicDataHTML(waifu);
}
}, 1 * second);
}
html += getCountdownHTML(getBirthDate(waifu, legalAge).getTime());
}
} else {
html += "Year of birth is unknown. Sorry.<br>\n"
}
return html;
}
function getBirthDate(waifu : JSON, yearsOffset : number = 0) : Date {
if (!hasYear(waifu)) {
return new Date();
}
let year : number = waifu["year"] + yearsOffset;
if (!hasMonth(waifu)) {
return new Date(year);
} else if (!hasDay(waifu)) {
return new Date(year, waifu["month"] - 1);
} else {
return new Date(year, waifu["month"], waifu["day-of-month"]);
}
}
function getDynamicDataHTML(waifu : JSON) : string {
return getAgeHTML(waifu);
}
function sanitizeInput(input:string) : string {
return input.replace(/&/g, '&').replace(/</g, '<').replace(/"/g, '"');
}
function getCurrentURL() : string {
return location.protocol + '//' + location.host + location.pathname;
}
function getWaifuNameHTML(englishName : string, CSSClass : string) : string {
let HTML : string = "";
HTML += "<h1 class=\"";
HTML += CSSClass;
HTML += "\">";
HTML += englishName;
HTML += "</h1>\n";
return HTML;
}
function getMarginMobile() : string {
return "<div class=\"flex-margins-mobile\"></div>";
}
function displayWaifuStats(name : string) : void {
let input : string = sanitizeInput(name);
let foundOutput : HTMLElement | null = document.getElementById("output");
let output : HTMLElement;
if (foundOutput === null) return;
else output = foundOutput;
output.innerHTML = "";
if (input === "") {
return;
}
//add search to history
let parms : URLSearchParams | null = new URLSearchParams(window.location.search);
let search : string | null = parms.get("q");
let historyState : any = {"q":input};
let query : string = "?q=" + input;
if (search === null || search !== input) {
history.pushState(historyState, "", query);
} else {
history.replaceState(historyState, "", query)
}
let request : XMLHttpRequest = new XMLHttpRequest();
request.open("GET", getCurrentURL() + "waifus/" + input.toLowerCase() + ".json");
request.responseType = "json";
request.onerror = function(event) {
console.log(event);
output.innerHTML = "Something went wrong. Look at console for more info";
};
request.onload = function() {
let newHTML : string = "";
switch(this.status) {
case 200: //OK
break;
case 404:
newHTML +=
"Could not find this person. Sorry.<br>\n" +
"Maybe you spelled her name wrong.<br>\n" +
"Maybe you forgot to enter her full name.<br>\n" +
"If you know her age, " +
"<a href=\"https://github.com/yourWaifu/is-your-waifu-legal#How-to-add-a-waifu-to-the-list\">" +
"please add her" +
"</a>.";
default:
let error : string = "Error " + this.status.toString()
output.innerHTML = error + "<br>\n" + newHTML;
document.title = error + " - " + siteName;
return;
}
//clear values before starting
if (countdown !== -1) {
clearInterval(countdown);
countdown = -1;
}
if (this.response === null) {
output.innerHTML = "<h1>ERROR:</h1><br>Response from server was null";
return;
}
let data : JSON = this.response;
newHTML += "<div class=\"waifu-body\">\n"
let englishName : string = data.hasOwnProperty("english-name") ? data["english-name"] : "";
document.title = englishName + " - " + siteName;
//display waifu image
if (data.hasOwnProperty("image") && data["image"] !== null && data["image"] !== "") {
newHTML += "<div class=\"waifu-image-parent\">\n"
newHTML += "<img class=\"waifu-image\" src=\"";
newHTML += data["image"];
newHTML += "\" alt=\""
newHTML += englishName;
newHTML += "\">\n"
newHTML += "</div>\n";
}
newHTML += "<div class=\"flex-margins-mobile-container\">\n"
newHTML += getMarginMobile();
newHTML += "<div class=\"waifu-stats\">\n";
newHTML += getWaifuNameHTML(englishName, "waifu-name");
if (hasValue(data, "definitely-legal") && data["definitely-legal"] === true)
newHTML += "Definitely Legal<br><br>\n"
//display birthday
newHTML += "Based on birthday:\n"
let hasAnyBirthDayInfo : boolean = false;
if (hasMonth(data)) {
newHTML += months[Number(data["month"]) - 1] + " ";
hasAnyBirthDayInfo = true;
}
if (hasDay(data)) {
newHTML += data["day-of-month"].toString();
hasAnyBirthDayInfo = true;
}
if (hasYear(data)) {
if (hasAnyBirthDayInfo) {
newHTML += ", ";
}
newHTML += data["year"].toString();
hasAnyBirthDayInfo = true;
}
if (hasAnyBirthDayInfo)
newHTML += "<br>\n"
// Calculate data
newHTML += "<div id=\"dynamic-data\">\n"
newHTML += getDynamicDataHTML(data);
newHTML += "</div>\n"
//based on appearance
let appearanceDataHTML = "";
let appearanceAnswer = "";
if (hasValue(data, "age-group-by-appearance")) {
appearanceDataHTML += "looks like a(n) ";
appearanceDataHTML += data["age-group-by-appearance"];
appearanceDataHTML += "\n";
switch (data["age-group-by-appearance"]) {
case "child":
appearanceAnswer = "Doesn't look legal";
break;
case "teenager":
appearanceAnswer = "Looks like they might be too young to be legal. Maybe?";
break;
default:
appearanceAnswer = "looks legal";
break;
}
}
if (hasValue(data, "age-range-by-appearance") && data["age-range-by-appearance"][0] !== undefined) {
if (appearanceDataHTML !== "")
appearanceDataHTML += "<br>\n"
let startAge : number = data["age-range-by-appearance"][0];
appearanceDataHTML += "looks about ";
appearanceDataHTML += startAge;
let endAge : number | undefined = data["age-range-by-appearance"][1];
if (endAge !== undefined && startAge !== endAge) {
appearanceDataHTML += " to ";
appearanceDataHTML += endAge;
}
appearanceDataHTML += " years old\n"
if (appearanceAnswer !== "") {
//to do, looks like there's repeated code here
appearanceAnswer =
startAge < legalAge ?
"Doesn't look legal"
: startAge <= legalAge + 1 ?
"Looks barely legal"
:
"Looks legal";
}
}
if(appearanceDataHTML !== "") {
newHTML += "<br>\nBased on appearance:\n<br>\n";
newHTML += appearanceDataHTML;
newHTML += "<br>\n";
newHTML += appearanceAnswer;
newHTML += "<br>\n";
}
//in the story
let storyAgeHTML : string = "";
if (hasValue(data, "age-in-show")) {
let storyAge : number = data["age-in-show"];
storyAgeHTML += "Age in story: "
storyAgeHTML += storyAge.toString();
storyAgeHTML += "\n<br>\n";
storyAgeHTML += storyAge < legalAge ? "Not legal" : "Legal";
storyAgeHTML += "\n";
}
if (hasValue(data, "finally-legal-in-show")) {
if (storyAgeHTML !== "")
storyAgeHTML += "<br>\n";
storyAgeHTML += "When they became legal: ";
storyAgeHTML += data["finally-legal-in-show"];
storyAgeHTML += "\n";
}
if (storyAgeHTML !== "") {
newHTML += "<br>\nBased on story:\n<br>\n";
newHTML += storyAgeHTML;
newHTML += "<br>\n";
}
//list notes and sources
function createListHtml(jsonKey:string, displayName:string) {
let html : string = "";
if (!data.hasOwnProperty(jsonKey) || data[jsonKey] === null || data[jsonKey].length === 0) {
return html;
}
html += "<br>"
html += displayName;
html += ":<br>\n<ul>\n";
let values : Array<string> = data[jsonKey];
values.forEach(function(value : string) {
html += "<li>"
//https://stackoverflow.com/a/1500501
let urlRegex : RegExp = /(https?:\/\/[^\s]+)/g;
html += value.replace(urlRegex, function(url) {
return '<a href="' + url + '">' + url + '</a>';
});
html += "</li>\n";
});
html += "</ul>\n";
return html;
}
newHTML += createListHtml("notes", "Notes");
newHTML += createListHtml("sources", "Sources");
newHTML += "</div>\n"
newHTML += getMarginMobile();
newHTML += "</div>\n"
newHTML += "</div>\n";
output.innerHTML = newHTML;
}
request.send();
}
function onWaifuSearch() : void {
let searchBar : HTMLElement | null = document.getElementById("waifu-search");
if (searchBar !== null && (<HTMLInputElement>searchBar).value !== "")
displayWaifuStats((<HTMLInputElement>searchBar).value);
}
//Search prediction
let searchTree : JSON | undefined = undefined;
function predictWaifu(input:string) : Array<string> {
if (
searchTree === undefined ||
searchTree["root"] === undefined ||
searchTree["root"][/*children*/"c"] === undefined ||
searchTree["allKeys"] === undefined
)
return [];
let position : JSON = searchTree["root"];
let filteredInput = input.toLowerCase();
for (let i : number = 0; i < input.length; ++i) {
let letter: string = filteredInput[i];
let branches : JSON = position[/*children*/"c"];
if (branches[letter] === undefined || branches[letter] === null)
return [];
position = branches[letter];
}
if (position[/*value*/"v"] === undefined)
return [];
let topPrediction : number = position[/*value*/"v"];
let topPredictions : Array<string> = [];
for (let i : number = 0; i < 5; ++i) {
let prediction: string | undefined = searchTree["allKeys"][topPrediction + i];
if (prediction === undefined)
break;
topPredictions.push(prediction);
}
return topPredictions;
}
function displayWaifuPredictions() {
let element : any = document.getElementById("waifu-predictions");
if (element === null)
return;
let output : HTMLElement = element;
let newHTML : string = "";
let input : string = (<HTMLInputElement>document.getElementById("waifu-search")).value;
input = sanitizeInput(input);
if (input === "") {
output.innerHTML =
"Search predictions will show up here<br>\n";
return;
}
let predictions : Array<string> = predictWaifu(input);
for (let i : number = 0; i < predictions.length; ++i) {
let prediction : string = predictions[i];
newHTML += "<a href=\"?q=";
newHTML += prediction;
newHTML += "\">"
newHTML += prediction;
newHTML += "</a><br>\n"
}
if (newHTML === "") {
newHTML +=
"Sorry, no results.<br>\n" +
"Maybe you misspelled her name.<br>\n" +
"She might not be in the database. " +
"<a href=\"https://github.com/yourWaifu/is-your-waifu-legal#How-to-add-a-waifu-to-the-list\">" +
"If so, please add her." +
"</a><br>\n";
}
output.innerHTML = newHTML;
}
function onWaifuPrediction() {
if (searchTree === undefined) {
let request : XMLHttpRequest = new XMLHttpRequest();
request.open("GET", "search-tree.json");
request.responseType = "json";
request.onerror = function () {
}
request.onload = function() {
searchTree = this.response;
displayWaifuPredictions();
}
request.send();
} else {
displayWaifuPredictions();
}
}
let inputHistory : Array<string> = [];
let inputHistoryIndex : number = 0;
let maxInputHistorySize : number = 128;
function onWaifuPredictionAutoComplete() {
if (searchTree === undefined)
return;
let inputElement = <HTMLInputElement>document.getElementById("waifu-search");
let input : string = inputElement.value;
input = sanitizeInput(input);
let predictions : Array<string> = predictWaifu(input);
if (predictions.length === 0)
return;
if (inputElement.value === predictions[0] && 1 < predictions.length) {
inputElement.value = predictions[1];
} else {
inputElement.value = predictions[0];
}
if (inputElement.value == input) //don't save input if it hasn't changed
return;
if (inputHistoryIndex < inputHistory.length) {
let removedElements = inputHistory.splice(inputHistoryIndex, inputHistory.length - inputHistoryIndex);
}
if (maxInputHistorySize <= inputHistory.length)
inputHistory.shift(); //keeps memory usage low
inputHistory.push(input);
inputHistoryIndex = inputHistory.length;
}
function getLastWaifuPredictionAutoComplete() {
if (inputHistory.length <= 0 || inputHistoryIndex <= 0)
return;
let inputElement = <HTMLInputElement>document.getElementById("waifu-search");
--inputHistoryIndex;
inputElement.value = inputHistory[inputHistoryIndex];
}
//read me
function displayReadMe() : void {
let request : XMLHttpRequest = new XMLHttpRequest();
request.open("GET", getCurrentURL() + "/README.html");
request.responseType = "document";
request.onload = function() {
switch(this.status) {
case 200: break; //OK
default: return;
}
let data : Document | null = this.responseXML;
if (data === null) return;
let output : HTMLElement | null = document.getElementById("output");
if (output === null) return;
output.innerHTML = "";
output.appendChild(data.documentElement);
//Detect firefox mobile
let frontScreen : HTMLElement | null = document.getElementById("front-screen");
if (frontScreen === null) return;
let frontScreenHeight = frontScreen.clientHeight;
let frontScreenText : HTMLElement | null = document.getElementById("front-screen-text");
if (frontScreenText === null) return;
let frontScreenTextHeight : number = frontScreenText.clientHeight;
if (frontScreenHeight <= frontScreenTextHeight)
frontScreen.className = "front-screen-firefox";
};
request.send();
//auto set focus on search bar
let element : HTMLElement | null = document.getElementById("waifu-search");
if (element === null)
return;
let searchBar : HTMLElement = element;
searchBar.focus();
}
function displaySiteContent(q: string | null | undefined) : void {
if (q === undefined || q === null)
displayReadMe();
else
displayWaifuStats(q);
}
//read query string values
window.onload = function () : void {
let parms : URLSearchParams = new URLSearchParams(window.location.search);
let search : string | null = parms.get("q");
displaySiteContent(search);
}
window.onpopstate = function(event) : void {
let search : string | null =
hasValue(event.state, "q") ? event.state["q"] : null;
displaySiteContent(search);
};
// Some UI stuff
function onClickWaifuPrediction(elementID:string) {
//using on foucs and on blur causes clicking on
//predictions to close instead of going to the predicted
//link
//Doing this fixes this issue
let showElements : Set<string> = new Set();
showElements.add("waifu-search");
showElements.add("waifu-predictions");
showElements.add("mobile-waifu-search-button");
let show : boolean =
showElements.has(elementID) ||
(document.activeElement !== null && document.activeElement.id === "waifu-search");
let menu : any = document.getElementById("waifu-predictions");
menu.style.display = show ? "unset" : "none";
//hide search button on mobile
let mobileSearchButton : HTMLElement | null =
document.getElementById("mobile-waifu-search-button");
if (mobileSearchButton === null)
return;
mobileSearchButton.className = show ?
"mobile-search-button-during-search" : "mobile-search-button"
}
let uiOnClickCallbacks : Array<Function> = new Array<Function>();
uiOnClickCallbacks.push(onClickWaifuPrediction);
window.onclick = function(mouse: MouseEvent) {
let element : Element | null = document.elementFromPoint(mouse.clientX, mouse.clientY);
if (element === null)
return;
let clickedElement : Element = element;
uiOnClickCallbacks.forEach(function (f:Function){
f(clickedElement.id);
});
}