-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
517 lines (469 loc) · 16.4 KB
/
index.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
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
'use strict';
import {
a,
br,
button,
checkbox,
div,
doomHelperDebug,
footer,
form,
h1,
h2,
h3,
img,
input,
li,
mountableStylesheet,
nav,
p,
QueryRouter,
RouterLazyLoad,
ShowIf,
Signal,
span,
svg,
text,
TextState,
ul
} from './res/minjs_v000/domHelper.min.js';
import {metaSet, metaType} from './res/lib/metaTag.js';
import {fetchApi, isLocalNetwork, isMobile} from './res/lib/lib.js';
import {UserGuideTool} from './res/userGuide.js';
import PopupWindow from './res/popupWindow.js';
window.askForLoginAlert = () => window.messageAlert.addInfo('需要登入來使用此頁面', '右上角登入按鈕登入', 3000);
window.loadingElement = svg('<circle class="path" cx="25" cy="25" r="20" fill="none" stroke-width="5" stroke-linecap="square"/>', '0 0 50 50', 'loaderCircle');
window.pageLoading = new Signal(false);
/**
* @typedef {Object} LoginData
* @property {boolean} login
* @property {string} name
* @property {string} studentID
* @property {int} year
* @property {int} semester
*/
// Main function
(function main() {
console.log('index.js Init');
window.messageAlert = new MessageAlert();
window.requestState = new RequestStateObject();
const font = mountableStylesheet('https://fonts.googleapis.com/css2?family=Noto+Sans+TC&display=swap');
if (document.requestStorageAccess)
document.requestStorageAccess().then(
() => console.log("StorageAccess granted"),
() => console.log("StorageAccess denied")
);
// debug
const debugModeEnable = isLocalNetwork || window.localStorage && !!localStorage.getItem('debug');
let debugWindow = null;
if (debugModeEnable) {
console.log('Debug enabled');
doomHelperDebug();
function pad(i) {
return i.toString().padStart(2, '0');
}
function offset(i) {
return i > 0 ? '-' + pad(i / 60 | 0) + ':' + pad(i % 60) : '+' + pad(-i / 60 | 0) + ':' + pad(-i % 60);
}
const date = new Date();
console.log(`${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}${offset(date.getTimezoneOffset())}`);
// Memory usage (for chrome)
if (window.performance && window.performance.memory) {
const memoryUpdate = new Signal(window.performance.memory);
setInterval(() => memoryUpdate.set(window.performance.memory), 1000);
debugWindow = span(
TextState(memoryUpdate, state => (state.usedJSHeapSize / 1000 / 1000).toFixed(2) + 'MB'),
null,
{style: 'position: absolute; top: 0; z-index: 100; background: black; font-size: 10px; opacity: 0.5;'});
}
} else
console.log('Debug disable');
// main code
const loginDeclarationWindow = new PopupWindow({small: true, padding: false});
const userGuideTool = new UserGuideTool();
const pageIdName = {
Home: '成功大學課程資訊及選課系統',
CourseSearch: '課程查詢',
Schedule: '我的課表',
GradeInquiry: '成績查詢',
CourseSelectionPreference: '志願排序',
UsefulWebsite: '實用網站',
Profile: '使用者資料',
};
const navBarBtnPageId = ['CourseSearch', 'Schedule', 'GradeInquiry', 'CourseSelectionPreference', 'UsefulWebsite'];
const defaultPage = 'Home';
const userLoginData = new Signal();
const showLoginWindow = new Signal(false);
const queryRouter = new QueryRouter('NCKU++', pageIdName, defaultPage,
{
Home: new RouterLazyLoad('./res/minjs_v000/home.min.js'),
CourseSearch: new RouterLazyLoad('./res/pages/courseSearch.js', userLoginData, userGuideTool),
Schedule: new RouterLazyLoad('./res/pages/courseSchedule.js', userLoginData),
GradeInquiry: new RouterLazyLoad('./res/pages/stuIdSysGrades.js', userLoginData),
CourseSelectionPreference: new RouterLazyLoad('./res/pages/preferenceAdjust.js', userLoginData),
UsefulWebsite: new RouterLazyLoad('./res/pages/usefulWebsite.js', userLoginData),
Profile: new RouterLazyLoad('./res/pages/profile.js', userLoginData),
},
footer(
div('borderLine'),
div('source',
h2('資料來源'),
a(null, 'https://course.ncku.edu.tw/', 'noSelect', null, {target: '_blank'},
img('res/assets/NCKU_course_system_logo.png', '國立成功大學課程資訊及選課系統', 'noDrag')
),
a(null, 'https://nckuhub.com/', 'noSelect', null, {target: '_blank'},
img('res/assets/nckuHub_logo.svg', 'NCKUHub', 'noDrag')
),
a(null, 'https://urschool.org/', 'noSelect', null, {target: '_blank'},
img('res/assets/UrSchool_logo.png', 'UrSchool', 'noDrag')
),
div('splitLine'),
),
h3('By WavJaby'),
h3('Email: WavJaby@gmail.com'),
a(null, 'https://github.com/WavJaby/NCKUpp', 'openRepo noSelect', null, {target: '_blank'},
img('./res/assets/github_icon.svg', 'GitHub icon', 'githubIcon noDrag'),
span('GitHub repo'),
),
)
);
userGuideTool.setRouter(queryRouter);
enableGoogleAnalytics(debugModeEnable);
const pageButtons = {};
for (const pageId of navBarBtnPageId) {
pageButtons[pageId] = li(null, a(pageIdName[pageId], './?page=' + pageId, null, pageButtonClick, {pageId: pageId}));
}
queryRouter.onPageOpen = function (lastPageId, pageId) {
// check login
if (pageId === 'GradeInquiry' || lastPageId === 'GradeInquiry' || !userLoginData.state)
fetchApi('/login?mode=' + getLoginMode(pageId), 'Check login').then(onLoginStateChange);
const lastPageButton = pageButtons[lastPageId];
if (lastPageId && lastPageButton)
lastPageButton.classList.remove('opened');
const nextPageButton = pageButtons[pageId];
if (nextPageButton)
nextPageButton.classList.add('opened');
metaSet(metaType.TITLE, document.title);
}
const navbarMobileBackground = div('navBarMobileBG', {onclick: navMenuClose});
const navbarLinks = ul('links',
Object.values(pageButtons),
li(null, NavSelectList('arrow', text('0w0'), [
['嗨嗨', null],
['🥰', null],
])),
);
const navbar = nav('navbar noSelect',
// NavSelectList('loginBtn',
// span(TextState(userLoginData, /**@param{LoginData}state*/state =>
// state && state.login ? state.studentID : '登入'
// )),
// [
// ['Profile', () => queryRouter.openPage('Profile')],
// ['Logout', () => fetchApi('/logout').then(onLoginStateChange)],
// ],
// false,
// () => {
// navMenuClose();
// // Is login
// if (userLoginData.state && userLoginData.state.login)
// return true; // Open select list
// // Not login, open login window
// showLoginWindow.set(!showLoginWindow.state);
// return false; // Not open select list
// }
// ),
button('hamburgerMenu', null, navMenuToggle,
img('./res/assets/burger_menu_icon.svg', 'mobile menu button', 'noDrag noSelect'),
),
a(null, './?page=Home', 'homePage', pageButtonClick, {pageId: 'Home'},
img('./res/assets/page_home/logo_text.svg', 'NCKU'), img('./res/assets/page_home/logo_plusplus_text.svg', '++')
),
navbarMobileBackground,
navbarLinks,
button('loginBtn', null, () => {
navMenuClose();
// Is login
if (userLoginData.state && userLoginData.state.login) {
fetchApi('/logout').then(onLoginStateChange);
return true; // Open select list
}
// Not login, open login window
showLoginWindow.set(!showLoginWindow.state);
return false; // Not open select list
},
img('./res/assets/login_icon.svg', ''),
span(TextState(userLoginData, /**@param{LoginData}state*/state => state && state.login ? state.studentID : '登入')),
),
);
window.navMenuClose = navMenuClose;
function navMenuClose() {
navbarMobileBackground.classList.remove('open');
navbarLinks.classList.remove('open');
}
function navMenuToggle() {
navbarMobileBackground.classList.toggle('open');
navbarLinks.classList.toggle('open');
}
queryRouter.element.addEventListener('scroll', () => {
if (queryRouter.element.scrollTop === 0)
navbar.classList.remove('scroll');
else
navbar.classList.add('scroll');
});
const root = div('root',
// Navbar menu
navbar,
// Page router
queryRouter.element,
// Guide tutorial tool
userGuideTool.element,
// Login window
ShowIf(showLoginWindow, LoginWindow(onLoginStateChange, showLoginWindow)),
// Page loading circle
ShowIf(window.pageLoading, div('loading', window.loadingElement.cloneNode(true))),
window.messageAlert.element,
window.requestState.element,
debugWindow,
);
window.onload = () => {
console.log('Window onload');
font.mount();
while (document.body.firstChild) document.body.removeChild(document.body.firstChild);
document.body.appendChild(root);
queryRouter.initFirstPage();
if (isMobile())
window.messageAlert.addInfo('可使用電腦來獲得最佳體驗', '手機版具完整功能,但介面正在調整中,請見諒', 10000);
};
// functions
function pageButtonClick(e) {
e.preventDefault();
const pageId = this.pageId;
queryRouter.openPage(pageId);
navMenuClose();
return false;
}
function onLoginStateChange(response) {
if (!response) {
window.messageAlert.addError('Network error', 'Try again later', 3000);
return;
}
/**@type LoginData*/
const loginData = response.data;
if (!loginData) {
window.messageAlert.addError('Unknown login error', 'Try again later', 3000);
return;
}
// Check if login error
if (!loginData.login && response.msg) {
window.messageAlert.addError('Login failed', response.msg, 5000);
return;
}
// Success, set login data
userLoginData.set(loginData);
if (loginData.login)
showLoginWindow.set(false);
}
/**
* @param {string} classname
* @param {Text|Element|Element[]} title
* @param {[string, function()][]} items
* @param {boolean} [enableHover]
* @param {function(): boolean} [onOpen]
* @return {HTMLUListElement}
*/
function NavSelectList(classname, title, items, enableHover, onOpen) {
const itemsElement = ul(null);
const list = ul(
classname ? 'list ' + classname : 'list',
enableHover ? {onmouseleave: closeSelectList, onmouseenter: openSelectList} : null,
// Element
li('items', itemsElement),
li('title', title, {onclick: toggleSelectList}),
);
for (const item of items) {
const onItemClick = item[1];
itemsElement.appendChild(
li(null, text(item[0]), {
onItemClick: onItemClick,
onclick: closeSelectList
})
);
}
function openSelectList() {
list.style.height = (list.firstElementChild.offsetHeight + list.lastElementChild.offsetHeight) + 'px';
window.addEventListener('pointerup', checkOutFocus);
}
function closeSelectList() {
if (this && this.onItemClick)
this.onItemClick();
list.style.height = null;
window.removeEventListener('pointerup', checkOutFocus);
}
function toggleSelectList() {
if (onOpen && !onOpen() && !list.style.height) return;
if (list.style.height)
closeSelectList();
else
openSelectList();
}
function checkOutFocus(e) {
let parent = e.target;
do {
if (parent === list)
return;
} while ((parent = parent.parentElement) !== document.body);
closeSelectList();
}
return list;
}
/**
* @constructor
*/
function MessageAlert() {
const messageBoxRoot = div('messageBox');
this.element = messageBoxRoot;
this.addInfo = function (title, description, removeTimeout) {
createMessageBox('info', title, description, null, removeTimeout);
}
this.addError = function (title, description, removeTimeout) {
createMessageBox('error', title, description, null, removeTimeout);
}
this.addErrorElement = function (title, htmlElement, removeTimeout) {
createMessageBox('error', title, null, htmlElement, removeTimeout);
}
this.addSuccess = function (title, description, removeTimeout) {
createMessageBox('success', title, description, null, removeTimeout);
}
this.addSuccessElement = function (title, htmlElement, removeTimeout) {
createMessageBox('success', title, null, htmlElement, removeTimeout);
}
function onMessageBoxTap() {
removeMessageBox(this);
}
function createMessageBox(classname, title, description, htmlElement, removeTimeout) {
const messageBox = div(classname, {onclick: onMessageBoxTap},
span(title, 'title'),
span(description, 'description', htmlElement),
div('closeButton')
);
if (removeTimeout !== undefined)
messageBox.removeTimeout = setTimeout(() => removeMessageBox(messageBox), removeTimeout);
if (messageBoxRoot.childElementCount > 0)
messageBoxRoot.insertBefore(messageBox, messageBoxRoot.firstElementChild);
else
messageBoxRoot.appendChild(messageBox);
messageBox.style.marginTop = -messageBox.offsetHeight + 'px';
// Slide in
setTimeout(() => {
messageBox.classList.add('animation');
messageBox.style.marginTop = '0';
}, 10);
}
function removeMessageBox(messageBox) {
if (messageBox.removeAnimationTimeout)
return;
clearTimeout(messageBox.removeTimeout);
messageBox.style.opacity = '0';
messageBox.style.marginTop = (-messageBox.offsetHeight - 10) + 'px';
messageBox.removeAnimationTimeout = setTimeout(() => {
messageBoxRoot.removeChild(messageBox);
}, 500);
}
}
function RequestStateObject() {
const stateBox = this.element = div('stateBox noSelect');
this.addState = function (title) {
return stateBox.appendChild(div(null,
window.loadingElement.cloneNode(true),
h1(title, 'title')
));
};
this.removeState = function (stateElement) {
stateBox.removeChild(stateElement);
};
}
function LoginWindow(onLoginStateChange, showLoginWindow) {
const username = input('loginField', '學號', null, {type: 'text', autocomplete: 'username'});
username.value = localStorage.getItem('studentId') || '';
const password = input('loginField', '密碼', null, {type: 'password', autocomplete: 'current-password'});
const loginDeclarationCheck = checkbox('loginDeclaration', localStorage.getItem('loginDeclaration') === 'true',
function () {
localStorage.setItem('loginDeclaration', this.checked)
},
span('我已閱讀'), button(null, '登入聲明', loginDeclaration, {type: 'button'}),
);
let loading = false;
const loginWindow = form('loginWindow', login, {
onRender: () => {
window.addEventListener('click', checkIfClickOut);
username.focus();
}, onDestroy: () => window.removeEventListener('click', checkIfClickOut)
},
h2('登入'),
username,
password,
span('帳密與成功入口相同', 'description'),
div('bottomRow',
loginDeclarationCheck,
button('loginField', '登入', null, {type: 'submit'}),
),
);
return loginWindow;
function login(e) {
e.preventDefault();
if (!loading) {
if (!loginDeclarationCheck.input.checked) {
messageAlert.addError('請先閱讀登入聲明', '', 2000);
return;
}
loading = true;
window.pageLoading.set(true);
const usr = username.value.endsWith('@ncku.edu.tw') ? username : username.value + '@ncku.edu.tw';
fetchApi('/login?mode=' + getLoginMode(queryRouter.getCurrentPage()), 'login', {
method: 'POST',
body: JSON.stringify({username: usr, password: password.value}),
timeout: 10000,
}).then(i => {
loading = false;
window.pageLoading.set(false);
if (i.success && i.data.login)
localStorage.setItem('studentId', username.value);
onLoginStateChange(i);
});
}
}
function loginDeclaration() {
if (loginDeclarationWindow.isEmpty()) {
loginDeclarationWindow.windowSet(div('loginDeclarationWindow',
h1('聲明'),
p(null, 'declaration',
span('本網站不會將密碼以任何形式暫存或儲存', 'red'), text(',登入功能僅代替使用者將資料轉至成功入口,並回傳登入狀態(Session Cookie)。\n'),
span('本網站僅儲存學號以及登入狀態(Session Cookie),提供附加功能之登入驗證使用', 'red'),
text('。\n\n成功大學並未公開驗證系統的api,將來會嘗試爭取成功入口驗證系統作為本網站之登入方式。\n' +
'如果還會擔心請在使用完畢後登出,且不需登入也可以使用查詢功能。\n' +
'本網站開源,如對以上聲明有疑慮,請自行將專案下載後執行。')
),
));
}
loginDeclarationWindow.windowOpen();
}
function checkIfClickOut(e) {
let element = e.target;
while (element.parentElement) {
if (element === loginWindow ||
element === window.messageAlert.element ||
element.className === 'loginBtn' ||
element.className.startsWith('popupWindow'))
return;
else if (element === document.body)
break;
element = element.parentElement;
}
showLoginWindow.set(false);
}
}
function getLoginMode(pageName) {
return pageName === 'GradeInquiry' ? 'stuId' : 'course';
}
})();