summaryrefslogtreecommitdiff
path: root/script.js
blob: 6c745390fa8e165b2be97f497e162bb51b9f5b1a (plain)
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
(function () {
"use strict";

// as of 2018, LW does not use CDM, but leave it in just in case
const FACS = new Set(["AP", "ED", "ES", "FA", "GL", "GS", "HH", "LE", "LW", "SB", "SC"]);
const SUBJS = {
    "ACTG": ["SB"],
    "ADMB": ["AP"],
    "ADMS": ["AP"],
    "ANTH": ["AP", "GS"],
    "ARB":  ["AP"],
    "ARTH": ["FA", "GS"],
    "ARTM": ["SB"],
    "ASL":  ["AP"],
    "AUCO": ["ED"],
    "BBED": ["ED"],
    "BC":   ["SC"],
    "BCHM": ["SC"],
    "BIOL": ["SC", "GL", "GS", "ED"],
    "BLIS": ["GS"],
    "BPHS": ["SC"],
    "BSUS": ["SB"],
    "BUEC": ["GL"],
    "CAT":  ["GL"],
    "CCY":  ["AP"],
    "CDIS": ["GS"],
    "CDNS": ["AP", "GL"],
    "CGTA": ["GS"],
    "CH":   ["AP"],
    "CHEM": ["SC", "GS", "ED"],
    "CIVL": ["LE", "GS"],
    "CLST": ["AP"],
    "CLTR": ["AP"],
    "CMCT": ["GS"],
    "COGS": ["AP"],
    "COMN": ["AP"],
    "COMS": ["GL"],
    "COOP": ["LE", "SC"],
    "CRIM": ["AP"],
    "CSLA": ["GL"],
    "DANC": ["FA", "GS", "ED"],
    "DATT": ["FA"],
    "DCAD": ["SB"],
    "DEMS": ["AP", "GS"],
    "DESN": ["FA"],
    "DEST": ["ED"],
    "DIGM": ["GS"],
    "DLLL": ["AP"],
    "DRAA": ["ED"],
    "DRST": ["GL"],
    "DVST": ["GS"],
    "ECON": ["AP", "GL", "SB", "GS", "ED"],
    "EDFE": ["ED"],
    "EDFR": ["ED"],
    "EDIN": ["ED"],
    "EDIS": ["ED"],
    "EDJI": ["ED"],
    "EDPJ": ["ED"],
    "EDPR": ["ED"],
    "EDST": ["ED"],
    "EDUC": ["ED", "GS"],
    "EECS": ["LE", "GS"],
    "EIL":  ["GS"],
    "EMBA": ["SB"],
    "EN":   ["AP", "GL", "GS", "ED"],
    "ENG":  ["LE", "GS"],
    "ENSL": ["GL"],
    "ENTR": ["SB"],
    "ENVB": ["SC"],
    "ENVS": ["GS", "ED"],
    "ESL":  ["AP"],
    "ESS":  ["GS"],
    "ESSE": ["LE"],
    "EXCH": ["SB"],
    "FACC": ["GS"],
    "FACS": ["FA"],
    "FAST": ["ED"],
    "FILM": ["FA", "GS"],
    "FINE": ["SB"],
    "FND":  ["AP"],
    "FNEN": ["SB"],
    "FNSV": ["SB"],
    "FR":   ["AP"],
    "FRAN": ["GL"],
    "FREN": ["ED", "GS"],
    "FSL":  ["GL"],
    "GCIN": ["AP"],
    "GEOG": ["AP", "SC", "GS", "ED"],
    "GER":  ["AP"],
    "GFWS": ["GS"],
    "GK":   ["AP"],
    "GKM":  ["AP"],
    "GWST": ["AP", "GL"],
    "HEB":  ["AP", "ED"],
    "HIMP": ["SB"],
    "HIST": ["AP", "GL", "GS", "ED"],
    "HLST": ["HH"],
    "HLTH": ["GS"],
    "HREQ": ["AP"],
    "HRM":  ["AP", "GS"],
    "HUMA": ["AP", "GL", "GS"],
    "IBUS": ["SB"],
    "IHST": ["HH"],
    "ILST": ["GL"],
    "INDG": ["AP"],
    "INDS": ["ED"],
    "INDV": ["AP", "FA"],
    "INST": ["GS"],
    "INTE": ["GS"],
    "INTL": ["SB"],
    "ISCI": ["SC"],
    "IT":   ["AP"],
    "ITEC": ["AP", "GL", "GS"],
    "JC":   ["AP"],
    "JP":   ["AP"],
    "KAHS": ["GS"],
    "KINE": ["HH"],
    "KOR":  ["AP"],
    "LA":   ["AP"],
    "LAL":  ["GS"],
    "LASO": ["AP"],
    "LAW":  ["ED", "GS", "LW"],
    "LIN":  ["GL"],
    "LING": ["AP"],
    "LLDV": ["ED"],
    "LLS":  ["AP"],
    "LREL": ["GS"],
    "LYON": ["GL"],
    "MACC": ["SB"],
    "MATH": ["SC", "GL", "ED", "GS"],
    "MBA":  ["SB"],
    "MBAN": ["SB"],
    "MDES": ["GS"],
    "MECH": ["GS"],
    "MFIN": ["SB"],
    "MGMT": ["SB"],
    "MINE": ["SB"],
    "MIST": ["AP"],
    "MKTG": ["SB"],
    "MODR": ["AP", "GL"],
    "MSTM": ["SB"],
    "MUSI": ["FA", "GS", "ED"],
    "NATS": ["SC", "GL"],
    "NURS": ["HH", "GS"],
    "OMIS": ["SB"],
    "ORCO": ["ED"],
    "ORGS": ["SB"],
    "OVGS": ["SB", "GS"],
    "PACC": ["GS"],
    "PANF": ["FA"],
    "PERS": ["AP"],
    "PHED": ["ED"],
    "PHIL": ["AP", "GL", "GS", "ED"],
    "PHYS": ["SC", "GL", "GS", "ED"],
    "PIA":  ["GS"],
    "PKIN": ["HH"],
    "PLCY": ["SB"],
    "POLS": ["AP", "GL", "GS", "ED"],
    "POR":  ["AP"],
    "PPAL": ["GS"],
    "PPAS": ["AP"],
    "PRAC": ["ED"],
    "PROP": ["SB"],
    "PRWR": ["AP"],
    "PSYC": ["GS", "GL"],
    "PUBL": ["SB"],
    "RU":   ["AP"],
    "SCIE": ["ED"],
    "SENE": ["SC"],
    "SGMT": ["SB"],
    "SLGS": ["ED"],
    "SLST": ["GS"],
    "SOCI": ["AP", "GL", "GS"],
    "SOSC": ["AP", "GL", "ED"],
    "SOWK": ["AP", "GS"],
    "SP":   ["AP", "GL"],
    "SPTH": ["GS"],
    "STS":  ["GS"],
    "SWAH": ["AP"],
    "SXST": ["AP", "GL"],
    "TECH": ["ED"],
    "TESL": ["AP"],
    "THEA": ["FA", "GS"],
    "THST": ["GS"],
    "TLSE": ["ED"],
    "TRAN": ["GL", "GS"],
    "TRAS": ["GS"],
    "TXLW": ["GS"],
    "TYP":  ["AP"],
    "VISA": ["FA", "GS"],
    "WKLS": ["AP"]
}

const TOKEN_DELIM_RE = /[^A-Za-z0-9.=]/;
const CRSN_RE = /^[0-9]{4}$/;
const DEPTCRSN_RE = /^([A-Z]{2,4})([0-9]{4})$/;
const CRED_RE = /^(?:Cr=([0-9]{1,2}(?:\.[0-9]{0,2})?)|([0-9]{1,2}\.[0-9]{0,2}))$/;
const MAYBE_CRED_RE = /^[0-9]{1,2}$/;
const MAYBE_DEPT_RE = /^[A-Z]{2,4}$/;
const IGNORE_RE = /^[A-Za-z]$/; // note: this has to be lowercase, otherwise "ignored search terms" will incorrectly uppercase the input

function parse_ycq_s(str) {
    let ycq_s = JSON.parse(str || "{}");
    ycq_s.course_creds = ycq_s.course_creds || {};
    ycq_s.course_subjs = ycq_s.course_subjs || {};
    ycq_s.course_facs = ycq_s.course_facs || {};
    ycq_s.subj_facs = ycq_s.subj_facs || {};
    ycq_s.default_facs = ycq_s.default_facs || [];
    return ycq_s;
}
var cached_ycq_s = parse_ycq_s(localStorage.ycq);

let now = new Date();
let month = now.getMonth();
// change to next summer on new year
// begin next FW on July 1
let fw_year, s_year;
if (month >= 6) {
    fw_year = now.getFullYear();
} else {
    fw_year = now.getFullYear() - 1;
}
s_year = now.getFullYear();
let fw_sess = document.createElement("option");
let fw_sess_val = "FW " + fw_year;
fw_sess.value = fw_sess_val;
fw_sess.textContent = `Fall/Winter ${fw_year}-${fw_year+1}`;
let s_sess = document.createElement("option");
let s_sess_val = "SU " + (s_year - 1);
s_sess.value = s_sess_val;
s_sess.textContent = `Summer ${s_year}`;
switch (cached_ycq_s.sess) {
    case fw_sess_val: fw_sess.selected = true; break;
    case s_sess_val: s_sess.selected = true; break;
    default:
        /* assume enrolling for summer courses between March and May inclusive */
        if (month >= 2 && month <= 4)
            s_sess.selected = true;
        else
            fw_sess.selected = true;
}

let ENGLISH_TYPES = {"fac": "faculty", "subj": "subject", "crsn": "course number", "cred": "credit number"};

function ready() {
    let ywhAd = document.getElementById("ywh-ad");
    if (location.protocol != "http:" && location.protocol != "https:" && location.protocol != "file:") {
        ywhAd.style.display = "none";
    }

    let sessions = document.querySelector("#sessions");
    sessions.appendChild(fw_sess);
    sessions.appendChild(s_sess);

    let input = document.getElementById("input");
    let link = document.getElementById("link");
    let linkContainer = document.getElementById("link-container");

    let state;

    let apply_list = function (n, l) {
        if (l.length) {
            document.getElementById(n).style.display = "block";
            document.getElementById(n + "-list").innerHTML = l.map(s => `<li>${s}</li>`).join('');
        } else {
            document.getElementById(n).style.display = "none";
        }
    };

    let apply = function () {
        state = {subj: "", fac: "", crsn: "", cred: ""};
        let multiple = new Set();
        let warn = [], error = [];

        let got = function (type, token) {
            if (state[type])
                multiple.add(ENGLISH_TYPES[type]);
            state[type] = token;
        };

        let ignored_tokens = [];

        let tryParse = function (token) {
            let subjcrsn, cred;
            if (SUBJS.hasOwnProperty(token)) {
                got("subj", token);
            } else if (FACS.has(token)) {
                got("fac", token);
            } else if ((subjcrsn = DEPTCRSN_RE.exec(token))) {
                got("subj", subjcrsn[1]);
                got("crsn", subjcrsn[2]);
            } else if ((cred = CRED_RE.exec(token))) {
                got("cred", parseFloat(cred[1] || cred[2]).toFixed(2));
            } else if (CRSN_RE.test(token)) {
                got("crsn", token);
            } else if (MAYBE_CRED_RE.test(token)) {
                got("cred", parseFloat(token).toFixed(2));
                warn.push(`assuming ${token} is the number of credits`);
            } else if (MAYBE_DEPT_RE.test(token)) {
                state["maybeSubj"] = token;
            } else if (IGNORE_RE.test(token)) {
                ignored_tokens.push(token);
            } else {
                return false;
            }
            return true;
        };

        let unk_tokens = [];
        input.value.split(TOKEN_DELIM_RE).forEach(function (token) {
            if (!token || tryParse(token) || tryParse(token.toUpperCase()))
                return;
            unk_tokens.push(token);
        });
        if (unk_tokens.length) {
            let dont_understand = unk_tokens.map(t => `"${t}"`).join(', ');
            warn.push(`don't understand search terms: ${dont_understand}.`);
        }

        if (ignored_tokens.length) {
            let ignored_terms = ignored_tokens.map(t => `"${t}"`).join(', ');
            warn.push(`ignored search terms: ${ignored_terms}.`);
        }

        if (!state["subj"] && state["maybeSubj"]) {
            state["subj"] = state["maybeSubj"];
            warn.push(`guessing subject is "${state["maybeSubj"]}".`);
        }

        if (!state["subj"] && state["crsn"] && cached_ycq_s.course_subjs[state["crsn"]]) {
            state["subj"] = cached_ycq_s.course_subjs[state["crsn"]];
            warn.push(`assuming ${state["crsn"]} means ${state["subj"]} ${state["crsn"]}, because you last used ${state["subj"]} for ${state["crsn"]}.`);
        }

        if (!state["subj"] && cached_ycq_s.default_subj) {
            state["subj"] = cached_ycq_s.default_subj;
            warn.push(`using ${state["subj"]}, because that was your most recently searched subject.`);
        }

        if (!state["fac"] && state["subj"]) {
            // if no faculty, try:
            // 1. most recent faculty for this course
            // 2. most recent faculty for this subject
            // 3. most recent compatible faculty
            // 4. first compatible faculty
            let compat_facs = SUBJS[state["subj"]];

            // needs to be a function so it can remove the current selection
            let other_options = function () {
                if (compat_facs) {
                    let other_facs = compat_facs
                        .filter(f => f != state["fac"])
                        .map(f => `<a href="#" class="prepend-query">${f}</a>`)
                        .join(", ");
                    if (other_facs.length)
                        return "other options: " + other_facs;
                }
                return "";
            }

            // 1. most recent faculty for this course
            if (state["crsn"] && cached_ycq_s.course_facs[state["subj"] + state["crsn"]]) {
                state["fac"] = cached_ycq_s.course_facs[state["subj"] + state["crsn"]];
                warn.push(`assuming ${state["subj"]} ${state["crsn"]} is ${state["fac"]}/${state["subj"]}, because you last used ${state["fac"]} for ${state["subj"]} ${state["crsn"]}. ${other_options()}`);
            } else if (cached_ycq_s.subj_facs[state["subj"]]) {
                // 2. most recent faculty for this subject
                state["fac"] = cached_ycq_s.subj_facs[state["subj"]];
                warn.push(`assuming ${state["subj"]} means ${state["fac"]}/${state["subj"]}, because you last used ${state["fac"]} for ${state["subj"]}. ${other_options()}`);
            } else if (compat_facs) {
                // 3. most recent compatible faculty
                if (cached_ycq_s.default_facs)
                    for (let i = cached_ycq_s.default_facs.length - 1; i >= 0; i--)
                        if (compat_facs.indexOf(cached_ycq_s.default_facs[i]) > -1)
                            state["fac"] = cached_ycq_s.default_facs[i];

                if (state["fac"]) {
                    warn.push(`assuming ${state["subj"]} means ${state["fac"]} ${state["subj"]}, because you recently used ${state["fac"]}. ${other_options()}`);
                } else {
                    // 4. first compatible faculty
                    state["fac"] = compat_facs[0];
                    warn.push(`assuming ${state["subj"]} means ${state["fac"]} ${state["subj"]}, because ${state["fac"]} is the default for ${state["subj"]}. ${other_options()}`);
                }
            } else {
                error.push("no faculty provided and unknown subject");
            }
        }

        if (state["subj"] && state["crsn"] && !state["cred"]) {
            if (cached_ycq_s.course_creds[state["subj"] + state["crsn"]]) {
                state["cred"] = cached_ycq_s.course_creds[state["subj"] + state["crsn"]];
                warn.push(`assuming ${state["subj"]} ${state["crsn"]} is ${state["cred"]} credits, because you last used ${state["cred"]} for ${state["subj"]} ${state["crsn"]}.`);
            } else {
                state["cred"] = "3.00";
                warn.push("assuming the number of credits is 3.00, because that's the most common number.");
            }
        }

        let sess = document.getElementById("sessions").value.split(" ");
        state["sess"] = sess[0];
        state["year"] = parseInt(sess[1], 10);

        if (state["fac"] && state["subj"] && state["crsn"] && state["cred"] && state["year"] && state["sess"]) {
            link.href = `https://w2prod.sis.yorku.ca/Apps/WebObjects/cdm.woa/wa/crsq?fa=${state["fac"]}&sj=${state["subj"]}&cn=${state["crsn"]}&cr=${state["cred"]}&ay=${state["year"]}&ss=${state["sess"]}`;
            link.textContent = `${state["fac"]}/${state["subj"]} ${state["crsn"]} ${state["cred"]} (${sessions.selectedOptions[0].textContent}) | York University`;
            linkContainer.style.display = "block";
        } else if (state["fac"] && state["subj"] && state["sess"]) {
            link.href = `https://w2prod.sis.yorku.ca/Apps/WebObjects/cdm.woa/wa/crsq1?faculty=${state["fac"]}&subject=${state["subj"]}&academicyear=${state["year"]}&studysession=${state["sess"]}`;
            link.textContent = `${state["fac"]}/${state["subj"]} Courses (${sessions.selectedOptions[0].textContent}) | York University`;
            linkContainer.style.display = "block";
        } else {
            linkContainer.style.display = "none";
            error.push("need at least subject. see examples above");
        }

        if (multiple.size)
            warn.push("multiple terms for " + Array.from(multiple.values()).join(", ") + ", using last occurrence for each");

        apply_list("warning", warn);
        apply_list("error", error);
    };
    input.addEventListener("input", apply);
    sessions.addEventListener("change", apply);

    document.body.addEventListener("click", function (e) {
        if (e.target.closest(".sample-query")) {
            e.preventDefault();
            input.select();
            // doesn't work in Firefox, oh well
            if (!document.execCommand || !document.execCommand("insertText", false, e.target.textContent))
                input.value = e.target.textContent;
            apply();
            input.focus();
        } else if (e.target.closest(".prepend-query")) {
            e.preventDefault();
            let r = false;
            if (document.execCommand) {
                input.setSelectionRange(0, 0);
                r = document.execCommand("insertText", false, e.target.textContent + " ");
            }
            if (!r)
                input.value = e.target.textContent + " " + input.value;
            apply();
        }
    });

    let save_defaults = function () {
        let old_ycq_s_s = localStorage.ycq;
        let new_ycq_s = parse_ycq_s(old_ycq_s_s);

        if (state["fac"]) {
            let default_facs = new Set(new_ycq_s.default_facs);
            default_facs.delete(state["fac"]);
            default_facs.add(state["fac"]);
            let new_facs = Array.from(default_facs);
            if (new_facs.length != new_ycq_s.default_facs.length ||
                new_facs.some((v, i) => v !== new_ycq_s.default_facs[i])) {
                new_ycq_s.default_facs = new_facs;
            }
        }

        if (state["subj"]) {
            if (state["fac"]) {
                if (state["crsn"])
                    new_ycq_s.course_facs[state["subj"] + state["crsn"]] = state["fac"];

                new_ycq_s.subj_facs[state["subj"]] = state["fac"];
            }

            if (state["crsn"]) {
                if (state["cred"])
                    new_ycq_s.course_creds[state["subj"] + state["crsn"]] = state["cred"];

                new_ycq_s.course_subjs[state["crsn"]] = state["subj"];
            }

            new_ycq_s.default_subj = state["subj"];
        }

        new_ycq_s.sess = document.getElementById("sessions").value;

        let new_ycq_s_s = JSON.stringify(new_ycq_s);
        if (new_ycq_s_s != old_ycq_s_s) {
            cached_ycq_s = new_ycq_s;
            localStorage.ycq = new_ycq_s_s;
        }
    };
    link.addEventListener("click", save_defaults);
    document.forms[0].addEventListener("submit", function (e) {
        e.preventDefault();
        if (linkContainer.style.display == "block")
            link.click();
    });
    input.addEventListener("blur", save_defaults);
    input.addEventListener("keydown", function (e) {
        if (e.key == "Enter") {
            e.preventDefault();
            if (linkContainer.style.display == "block") {
                // firefox silently ignores simulated link events with modifiers
                // use [\/] to fix syntax highlighting
                if (/(?:Firefox|Gecko)[\/]/.test(navigator.userAgent) && (e.ctrlKey || e.shiftKey || e.altKey || e.metaKey)) {
                    if (e.ctrlKey) {
                        link.target = "_blank";
                        link.click();
                        link.target = "";
                    } else if (e.shiftKey) {
                        // only need save here because other methods already trigger the link click event
                        // for efficiency, don't save twice
                        save_defaults();
                        window.open(link.href, "_blank",
                            "noopener,width=625,resizable,menubar,toolbar,location,personalbar,status,scrollbars");
                    } else {
                        link.click();
                    }
                } else {
                    link.dispatchEvent(new MouseEvent("click", e));
                }
            }
        }
    });
    apply();
}

if (document.readyState === "interactive" || document.readyState === "complete") {
    ready();
} else {
    document.addEventListener("DOMContentLoaded", ready);
}
}());