Repository navigation
Expand file tree
/
Copy pathscript-experimental.js
More file actions
399 lines (347 loc) · 13.7 KB
/
Copy pathscript-experimental.js
File metadata and controls
399 lines (347 loc) · 13.7 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
// --- Added sanitization helper function ---
function escapeHTML(str) {
// String(string) is still a string.
return String(str)
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
// #region Scrollbar
// Helper function to convert a hex color to RGB
function hexToRgb(hex) {
return {
r: parseInt(hex.substring(1, 3), 16),
g: parseInt(hex.substring(3, 5), 16),
b: parseInt(hex.substring(5, 7), 16)
};
}
// Helper function to convert RGB values to a hex color
function rgbToHex(r, g, b ) {
return `#${((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)}`;
}
// Main function to interpolate between two colors
function interpolate(color1, color2, percent) {
const rgb1 = hexToRgb(color1);
const rgb2 = hexToRgb(color2);
const interpolateValue = (start, end) =>
Math.round(start + (end - start) * percent);
const interpolatedColor = {
r: interpolateValue(rgb1.r, rgb2.r),
g: interpolateValue(rgb1.g, rgb2.g),
b: interpolateValue(rgb1.b, rgb2.b)
};
return rgbToHex(
interpolateValue(rgb1.r, rgb2.r),
interpolateValue(rgb1.g, rgb2.g),
interpolateValue(rgb1.b, rgb2.b)
);
}
const debounce = (fn) => {
let frame;
return (...params) => {
if (frame) {
cancelAnimationFrame(frame);
}
frame = requestAnimationFrame(() => {
fn(...params);
});
}
};
var searchResults;
var subjectSelect;
var searchText;
var autocomplete;
runOnDocumentLoad(function() {
searchResults = document.getElementById('search-results');
subjectSelect = document.getElementById('subject-select');
searchText = document.getElementById('search-text');
autocomplete = document.getElementById('autocomplete');
});
runOnWindowLoad(function () {
searchResults.addEventListener('scroll', function(e) {
var scrollamount = searchResults.scrollTop / searchResults.scrollHeight;
// `scrollamount ? scrollamount : 0` --> If `scrollamount` is `NaN`, we just return the beginning value (0).
searchResults.style.setProperty("--scroll-amount", interpolate("#4287f5","#460c85", scrollamount ? scrollamount : 0));
}, { passive: true });
//searchResults.style.setProperty("--scroll-amount", "#4287f5", 0);
});
// #endregion
// #region Search Prep
// Searching
let idx;
let fullData;
let subjectList = [];
let relevant_subject_list = [];
fetch("./subjects.json")
.then((res) => res.json())
.then((data)=>{
subjectList = data;
relevant_subject_list = data;
var template = document.getElementById("template-subject-selector");
for (let index = 0; index < subjectList.length; index++) {
const subject = subjectList[index];
var button = template.cloneNode(true).content;
button.querySelector("button").onclick = function() { search(subject); };
button.querySelector("p").textContent = subject;
subjectSelect.appendChild(button);
}
});
fetch("./searchIndex.json")
.then((res) => res.json())
.then((data) => {
// Hopefully, by offsetting this, we avoid "lunr is not defined" but we also
// get the benefits of fetching literally as soon as the line of code is
// run.
runOnWindowLoad(function() {
idx = lunr(function () {
this.ref('id');
this.field('title');
this.field('subject');
this.field('number');
this.field('credits');
data.forEach(function (doc) {
this.add(doc)
}, this)
})
fullData = data;
});
});
// #endregion
// #region Searching Logic
// This is everything everywhere all at once made into code.
// It's going to take a while to fix, even every time I add to it,
// I end up just monkeypatching instead.
// Texts in input field
//const searchText = document.querySelector("#search-text");
// Use textContent when simply displaying text to avoid HTML injection.
//const autocomplete = document.querySelector("#autocomplete");
const minCredits = 0
const default_searchtext = "Enter standard number or subject name";
let previous_search_length = 0;
// 37 lines of gross...
function setAutoCompleteText() {
// Use textContent instead of innerHTML for user-supplied text.
const text = searchText.value;
if (text.length < previous_search_length || text.length < 2) {
relevant_subject_list = subjectList;
}
console.log(relevant_subject_list);
if (text.length == 0) {
// Set a safe default text message
autocomplete.textContent = default_searchtext;
// This would never be visible without refreshing the page otherwise!!
selectScreen(screen.welcome);
previous_search = "";
previous_search_length = 0;
return;
}
let delete_list = [];
let matches_list = [];
for (let i = 0; i < relevant_subject_list.length; i++) {
const subject = relevant_subject_list[i];
if (subject.toLowerCase().substr(0, text.length) == text.toLowerCase()) {
matches_list.push(subject);
}
else delete_list.push(subject);
}
relevant_subject_list = matches_list;
matches_list.push(text);
autocomplete_item = matches_list[0];
autocomplete.textContent = autocomplete_item;
// How TF did we even introduce a need for this ".replace", anyway?
// .textContent should make this completely irrelevant.
searchText.value = autocomplete_item.substr(0, text.length).replace("&", "&");
}
function addFilter(filter) {
// Strings are truthy/falsy; returns true if string has no content, is null, etc..
if (searchText.value !== "") {
// Add space if there's already text in the bar
searchText.value += " ";
}
searchText.value += filter;
autocomplete.textContent = "";
searchText.focus();
}
function extractSearchData(search) {
// Credit Selector
// Matchs mincredits: then a number, and the i at the end means it's case insensitive
const creditsRegex = /mincredits:(\d+)/i;
const creditsMatch = search.match(creditsRegex);
const minCredits = creditsMatch ? parseInt(creditsMatch[1], 10) : null;
search = search.replace(creditsRegex, '').trim();
// Level selector
// Matchs level: then a number or S, and the i at the end means it's case insensitive
const levelRegex = /level:(\d+|S)/i;
const levelMatch = search.match(levelRegex);
const level = levelMatch ? levelMatch[1] : null;
search = search.replace(levelRegex, '').trim();
// Search query sanitization
// Adds a plus before each word so that lunr matches it properly
const sanitizationRegex = /(?<![+-])\b([A-Z][^+\s]+)\b/g;
search = search.replace(sanitizationRegex, "+$1");
return ({
search,
minCredits,
level
});
}
// TODO: Investigate performance of loading results on pageload, then making
// them visible or invisible depending on if they meet the search criteria.
function showSearchResults() {
selectScreen(screen.rswheel);
// Remove current search results
searchResults.innerHTML = "";
new Promise(
(resolve, reject) => {
// To anyone testing on Firefox: setTimeout just breaks after a while.
// IDFK why, but it does. You simply have to create a new tab altogether.
// Please refrain from changing this timeout of going on a code rampage in
// order to find the source of this bug. It's not fun.
// Trust me, even when looking at 3am, you won't realise what's going on
// until you try it in another browser and it works fine.
// Don't make my mistake. The setTimeout is fine. Open a new tab and close
// the old one.
//
// Curious why there's a setTimeout to begin with? See below the promise,
// about 64 lines down.
setTimeout(() => {
const { search, minCredits, level } = extractSearchData(searchText.value);
let subjectExams = idx.search(search);
// Filtering
if (minCredits) {
subjectExams = subjectExams.filter((result) => fullData[result.ref]['credits'] >= minCredits );
}
if (level) {
subjectExams = subjectExams.filter((result) => fullData[result.ref]['level'] == level || fullData[result.ref]['level'] == "All");
}
// If there are no exams for that subject, show the error screen (why face emoji)
if (subjectExams.length < 1) {
selectScreen(screen.snfound);
return;
}
var template = document.getElementById("template-search-card");
var cards = [];
// Add the exam card buttons for each exam there are for that subject
console.log(fullData);
subjectExams.forEach((result) => {
// No sanitization needed; textContent literally just changes the text, no HTML parsing involved. It's like it sanitizes for us!
// TBF these *could* probably be inlined.
// It saves a few LoC => shorter load speed,
// but isn't too necessary (and is a *little* unergonomic).
//const examNumber = fullData[result.ref]["number"]; // Inline
const startYear = fullData[result.ref]["start-year"]; // Not inline
const endYear = fullData[result.ref]["end-year"]; // Not inline
//const examTitle = fullData[result.ref]["title"]; // Inline
const creditsText = fullData[result.ref]["credits"]; // Not inline
const examLevel = fullData[result.ref]["level"]; // Not inline
// We *do*, however, need to make sure the URL works like we want it so.
// Wcich is why, for URL parts, we use encodeURIComponent.
const examNumberURL = encodeURIComponent(fullData[result.ref]["number"]);
var card = template.cloneNode(true).content;
var headings = card.querySelectorAll("h2");
var details = card.querySelectorAll("b");
headings[0].textContent = fullData[result.ref]["number"];
// "- Credits" is not very nice to see.
if (creditsText === "-") details[0].textContent = "Scholarship";
else details[0].textContent = `${creditsText} Credits`;
details[1].textContent = `${startYear}~${endYear}`;
card.querySelector("p").textContent = fullData[result.ref]["title"];
//if (examLevel !== "S") headings[1].textContent = examLevel;
headings[1].textContent = examLevel;
card.querySelector("a").setAttribute("href", `https://raw.githubusercontent.com/JelyMe/NCEAPapers/main/zipped/${examNumberURL}.zip`);
cards.push(card);
//searchResults.appendChild(card);
});
for (var i = 0; i < cards.length; i++) {
searchResults.appendChild(cards[i]);
}
resolve();
}, 0);
/*
We added a 5 millisecond delay because of a behaviour in JavaScript
Seems like "tasks" in JavaScript will be blocking, until a certain task is done,
JavaScript will move onto the next task. Thus, adding a 5 millisecond delay to this will allow the loading
wheel to show
*/
/* To explain: in JavaScript - which, note, is a single-threaded language
* by default - setTimeout adds the function to a queue that isn't bound
* to the function it was called in - this allows us to get funky with it
* because it's no longer part of the rest of the code - and thus, it does
* not block, because it leaves the blocking function through setTimeout.
*
* I also changed this delay to 0, because 5ms is still 5ms more than we
* need.
*/
}
).then(
() => {
// It's also fine to do `selectScreen(searchResults);` but it's a bit less
// decoupled and gives the suggestion that screen select is tied to searching,
// somehow.
// Once exams are found show the search results
selectScreen(screen.results);
}
);
}
const tabKeyCode = 9;
const enterKeyCode = 13;
let previous_search = "";
//Stupid tab button, it has to be done on the keydown event because when keyup, the focus will have been shifted
// WTF dude tab button isn't stupid, it's stunning.
// Thanks to the tab button I don't need to use my mouse on this site anymore
// (big win)!
runOnWindowLoad(function() {
searchText.addEventListener('keydown', (event) => {
/*
Why we use autocomplete.textContent instead of innerHTML:
This is because Earth & Space Science has an ampersand, which is displayed
as & in HTML. If we use autocomplete.innerHTML, then we are comparing
searchText.value (which is plain) text, with HTML markup. This leads to
errors such as when autocompleting for Earth & Space Science, the
searchText will be displayed as "Earth & Space Science".
> Unfun fact!
> This even happens in Steam, somehow. Ever listened to "Giant's Deep"
> by Andrew Prahlow? To avoid this we have to use the raw plain text of
> autocomplete. Hence, we use textContent.
*/
// Also, imo, `.textContent` is literally just goated.
// Did I mention it basically auto-eradicates our XSS problems for us?
// Awesome!!!
// Keycode 9 is the tab key
// Keycode 13 is the enter key
if (event.keyCode != 9 && event.keyCode != 13 || autocomplete.textContent == default_searchtext) {
// Keycode 8 is backspace;
// We do this incase of an error; the search is empty but the user uses it to "go to home".
if(event.keyCode == 8 && searchText.value == "") {
selectScreen(screen.welcome);
setAutoCompleteText();
}
return;
}
searchText.value = autocomplete.textContent;
if (previous_search != searchText.value) {
showSearchResults();
previous_search = searchText.value;
return;
}
// If the current input text is not equal to autoComplete's text, will
// auto complete.
searchText.value = autocomplete.textContent;
// I have a rather lengthy argument, as to why the following code is
// commented, but in short: we don't need it. Users like me are unable to use
// the site **PROPERLY** otherwise.
//event.preventDefault();
});
searchText.addEventListener('input', (event) => {
setAutoCompleteText();
}, { passive: true });
});
// Searching for subject exams from clicking the subject buttons
function search(term){
autocomplete.textContent = term;
searchText.value = term;
showSearchResults();
}
// #endregion