-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1984 lines (1870 loc) · 59.2 KB
/
script.js
File metadata and controls
1984 lines (1870 loc) · 59.2 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
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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
/** @typedef {string} Code */
/** @typedef {string} Semester */
/** @typedef {string} Period */
/** @typedef {string} TitleJp */
/**
* @typedef {Object} Lecture
* @prop {Code} code
* @prop {string} type
* @prop {string} category
* @prop {Semester} semester
* @prop {Period[]} periods
* @prop {string} classroom
* @prop {TitleJp} titleJp
* @prop {string} titleEn
* @prop {string} lecturerJp
* @prop {string} lecturerEn
* @prop {string} ccCode 共通科目コード
* @prop {number} credits
* @prop {string} detail 講義詳細
* @prop {string} schedule 講義計画
* @prop {string} methods 講義方法
* @prop {string} evaluation
* @prop {string} notes 履修上の注意
* @prop {string} class 履修可能クラス(日本語表記)
* @prop {[string[], string[]]} importance 対象科類([必修, 推奨])
* @prop {[string[], string[]]} targetClass 履修可能クラス([1年, 2年])
* @prop {string} guidance
* @prop {string} guidanceDate
* @prop {string} guidancePeriod
* @prop {string} guidancePlace
* @prop {string} shortenedCategory
* @prop {string} shortenedEvaluation
* @prop {string} shortenedClassroom
* @prop {number} time 授業時間
* @prop {string} timeCompensation 授業時間90分の場合の対応
* @prop {HTMLTableRowElement} tableRow
*/
/** DBのバージョン(年, セメスター)を表す文字列 */
const LAST_UPDATED = "2026S";
/**
* 同セメスター内のバージョンを示す整数値.
* DB関連の処理に互換性のない変更がある場合は加算し、セメスターが変わったら1に戻す.
* あまり頻繁に更新するとユーザー体験を損なうので、些細な変更だったらそのままにしておく.
* @type {number}
*/
const MINOR_VERSION = 1;
/**
* ログを出力したい場合は適宜trueにすること.
* テストが終わったらfalseに戻すこと.
*/
const IS_DEVELOPMENT = false;
/** moduleLike: ベンチマーク測定 */
const benchmark = IS_DEVELOPMENT
? {
init() {
console.log("* measure initializing time *");
this.initTime = Date.now();
},
initTime: null,
log(message) {
console.log(message);
console.log(Date.now() - this.initTime);
},
}
: {
init() {},
initTime: null,
log(message) {},
};
benchmark.init();
/**
* defaultdict from Python
* @template K, V
* @extends {Map<K, V>}
*/
class DefaultMap extends Map {
/**
* @param {[K, V][]?} entries
* @param {(() => V)?} defaultfactory
*/
constructor(entries, defaultfactory) {
super(entries);
this.defaultfactory = defaultfactory;
}
/** @param {K} key */
get(key) {
if (!this.has(key) && this.defaultfactory) {
this.set(key, this.defaultfactory());
}
return super.get(key);
}
}
/**
* DefaultMap(titleJp, Map(code, lecture))
* @extends {DefaultMap<TitleJp, Map<Code, Lecture>>}
*/
class LectureCounter extends DefaultMap {
constructor() {
super(null, () => new Map());
}
/**
* 同種の講義かを識別するための講義名を取得する
* @param {Lecture} lecture
* @returns {TitleJp}
*/
getName(lecture) {
return lecture.titleJp.replace("(教員・教室未定)", "");
}
/**
* 任意個数の講義を追加する
* @param {...Lecture} lectures
*/
push(...lectures) {
for (const lecture of lectures) {
this.get(this.getName(lecture)).set(lecture.code, lecture);
}
return this;
}
/**
* 指定の講義を削除する. 返り値は削除に成功したか否か
* @param {Lecture} lecture
*/
delete(lecture) {
benchmark.log("lecture delete start");
const name = this.getName(lecture);
const isSuccess = this.get(name).delete(lecture.code);
if (!this.get(name).size) {
super.delete(name);
}
benchmark.log(`lecture ${name} deleted`);
return isSuccess;
}
/**
* 指定の講義が存在するかを返す
* @param {Lecture} lecture
* @returns {boolean}
*/
hasLecture(lecture) {
return this.get(this.getName(lecture))?.has?.(lecture.code) ?? false;
}
}
/** LectureNameCounterに曜限ごとの管理機能を追加したもの */
class LectureCounterPeriodScope extends LectureCounter {
constructor() {
super();
/** @type {DefaultMap<Period, LectureCounter>} */
this.byPeriod = new DefaultMap(null, () => new LectureCounter());
}
/** 講義の登録状況をリセットする */
clear() {
this.byPeriod.clear();
super.clear();
}
/** @param {...Lecture} lectures */
push(...lectures) {
for (const lecture of lectures) {
for (const period of lecture.periods) {
this.byPeriod.get(period).push(lecture);
}
}
return super.push(...lectures);
}
/** @param {Lecture} lecture */
delete(lecture) {
for (const period of lecture.periods) {
this.byPeriod.get(period).delete(lecture);
}
return super.delete(lecture);
}
/** 登録されている全講義のうち、名前の異なるものの総単位数 */
get credits() {
// 講義名ごとに講義を1つ取り出して単位数を加算していく
let sum = 0;
for (const codeToLecture of this.values()) {
sum += Number([...codeToLecture.values()][0].credits);
}
return sum;
}
}
/** セメスターごとにLectureNameCounterを管理できるようにしたもの */
class LectureCounterSemesterScope {
/** @param {...Semester} semesters */
constructor(...semesters) {
this.counters = new Map(
semesters.map((semester) => [semester, new LectureCounterPeriodScope()])
);
}
/**
* 登録されている全講義とそのコード
* @returns {IterableIterator<[Code, Lecture]>}
*/
*[Symbol.iterator]() {
for (const counterPeriodScope of this.counters.values()) {
for (const codeToLecture of counterPeriodScope.values()) {
yield* codeToLecture;
}
}
}
/**
* 登録されている全講義のコード
* @returns {IterableIterator<Code>}
*/
*keys() {
for (const [key, _] of this) {
yield key;
}
}
/**
* 登録されている全講義
* @returns {IterableIterator<Lecture>}
*/
*values() {
for (const [_, value] of this) {
yield value;
}
}
/** 講義の登録状況をリセットする */
clear() {
for (const counter of this.counters.values()) {
counter.clear();
}
}
/**
* 任意個数の講義を追加する
* @param {...Lecture} lectures
*/
push(...lectures) {
for (const lecture of lectures) {
this.counters.get(lecture.semester[0]).push(lecture);
}
return this;
}
/**
* 指定の講義を削除する. 返り値は削除に成功したか否か
* @param {Lecture} lecture
*/
delete(lecture) {
return this.counters.get(lecture.semester[0]).delete(lecture);
}
/**
* 指定の講義が存在するかを返す
* @param {Lecture} lecture
* @returns {boolean}
*/
has(lecture) {
return [...this.counters.values()].some((counter) =>
counter.hasLecture(lecture)
);
}
/** 登録されている全講義のうち、名前の異なるものの総単位数 */
get credits() {
let sum = 0;
for (const counterPeriodScope of this.counters.values()) {
sum += counterPeriodScope.credits;
}
return sum;
}
/**
* Map(semester, LectureCounter)
* @param {Period} period
* @returns {Map<Semester, LectureCounter>}
*/
periodOf(period) {
return new Map(
[...this.counters].map(([semester, counterPeriodScope]) => [
semester,
counterPeriodScope.byPeriod.get(period),
])
);
}
}
/**
* @typedef {string | Array | Object} savable
* string, Array, Objectから再帰的に構成される型
*/
/**
* moduleLike: localStorage
* - 保存可能なデータ: 上記参照
* - DB類を入れるためにLZStringで圧縮している
*/
const storageAccess = {
/**
* @param {string} key
* @param {savable} value
*/
setItem: (key, value) =>
localStorage.setItem(key, LZString.compressToBase64(JSON.stringify(value))),
/**
* @param {string} key
* @returns {savable?}
*/
getItem: (key) =>
JSON.parse(
LZString.decompressFromBase64(localStorage.getItem(key)) || "null"
),
clear: () => localStorage.clear(),
};
// メジャーバージョンが変わった際はキャッシュを削除しリロードする
if (
!(
storageAccess.getItem("LAST_UPDATED") === LAST_UPDATED &&
storageAccess.getItem("MINOR_VERSION") === MINOR_VERSION
)
) {
storageAccess.clear();
storageAccess.setItem("LAST_UPDATED", LAST_UPDATED);
storageAccess.setItem("MINOR_VERSION", MINOR_VERSION);
location.reload();
}
/** moduleLike: アクティブウィンドウ切り替え */
const innerWindow = {
init() {
const startButton = document.getElementById("start");
startButton.addEventListener("click", () => {
this.changeTo("status");
personal.validateStatus();
});
const openStatusButton = document.getElementById("open-status");
openStatusButton.addEventListener("click", () => this.changeTo("status"));
const settingsButton = document.getElementById("settings");
settingsButton.addEventListener("click", () => this.toggle("settings"));
this.changeTo("load");
},
coveredElements: [
document.getElementById("toggle-mode"),
document.getElementById("scroll-to-search"),
],
coveredBaseElements: [
document.getElementById("global-header"),
document.getElementById("global-footer"),
],
index: new Map([
["load", document.getElementById("loading-message")],
["title", document.getElementById("title-window")],
["main", document.getElementById("main-contents")],
["askiiArt", document.getElementById("aa-window")],
["status", document.getElementById("status-window")],
["settings", document.getElementById("settings-window")],
]),
get activeWindowName() {
for (const [targetWindowName, targetWindow] of this.index) {
if (!targetWindow.hidden) {
return targetWindowName;
}
}
return null;
},
changeTo(/** @type {string} */ windowName) {
for (const [targetWindowName, targetWindow] of this.index) {
const isTarget = windowName === targetWindowName;
targetWindow.hidden = !isTarget;
if (isTarget) {
for (const element of this.coveredElements) {
element.hidden = targetWindow.classList.contains("fullscreen-window");
}
for (const element of this.coveredBaseElements) {
element.hidden = targetWindow.classList.contains(
"over-fullscreen-window"
);
}
}
}
},
toggle(/** @type {string} */ primaryWindowName) {
this.changeTo(
this.activeWindowName !== primaryWindowName ? primaryWindowName : "main"
);
},
};
innerWindow.init();
/** moduleLike: ハッシュ操作関連 */
const hash = {
_get() {
return (
location.hash.match(/^#\/(view|edit)\/(\d*)\/?$/)?.slice?.(1, 3) ?? [
"edit",
null,
]
);
},
_set(mode, code) {
location.hash = `#/${mode ?? this._get()[0]}/${code ?? ""}`;
},
/** @type {"view" | "edit"} */
get mode() {
return this._get()[0];
},
set mode(mode) {
if (this.mode !== mode) {
this._set(mode, null);
if (this.browser === "firefox") {
location.reload();
} else if (mode === "edit") {
window.scrollTo(0, this.scroll);
}
}
},
get code() {
return this._get()[1];
},
set code(code) {
this._set(null, code);
},
remove() {
this._set(null, null);
},
panel: document.getElementById("toggle-mode"),
scroll: 0,
/** @type {"ie" | "edge" | "chrome" | "safari" | "firefox" | "other"} */
browser: (() => {
const userAgent = window.navigator.userAgent.toLowerCase();
if (userAgent.includes("msie") || userAgent.includes("trident")) {
return "ie";
} else if (userAgent.includes("edg")) {
return "edge";
} else if (userAgent.includes("chrome")) {
return "chrome";
} else if (userAgent.includes("safari")) {
return "safari";
} else if (userAgent.includes("firefox")) {
return "firefox";
} else {
return "other";
}
})(),
init() {
document.getElementById(this.mode).checked = true;
this.panel.addEventListener("change", (ev) => {
this.mode = ev.target.id;
});
window.addEventListener("load", () => {
this.scroll = window.scrollY;
});
switch (this.browser) {
case "edge":
case "chrome":
window.addEventListener("scrollend", () => {
if (this.mode === "edit") {
this.scroll = window.scrollY;
}
});
break;
case "safari":
case "ie":
case "other":
window.addEventListener("scroll", () => {
setTimeout(() => {
if (this.mode === "edit") {
this.scroll = window.scrollY;
}
}, 100);
});
break;
case "firefox":
break;
}
},
alert() {
switch (this.browser) {
case "edge":
case "chrome":
break;
case "safari":
case "firefox":
case "other":
window.alert(
"本サイトの閲覧には、ChromeまたはEdgeを推奨しています。\nそれ以外のブラウザでは、モード切り替え時にスクロールが保持されず、ユーザーエクスペリエンスを損なう可能性があります。"
);
break;
case "ie":
window.alert(
"本サイトはInternet Explorerをサポートしていません。\n本サイトの閲覧には、ChromeまたはEdgeを推奨しています。"
);
break;
}
},
};
hash.init();
/** moduleLike: 文字列処理 */
const textUtils = {
/**
* - テキストの全角英数字, 全角スペース, 空文字を除去する
* - 分かりにくいが、3つ目のreplaceの"~"は全角チルダであり、波ダッシュではない
* - 小文字にはしないので検索時は別途toLowerCase()すること
* @param {string} text
*/
normalize: (text) =>
(text ?? "")
.replace(/([^\S\n]| )+/g, " ")
.replace(/[,.]/g, "$& ")
.replace(/[!-~]/g, (s) => String.fromCharCode(s.charCodeAt(0) - 0xfee0))
.replace(/[‐―−ー]/g, "-")
.replaceAll("〜", "~")
.trim(),
/** @param {string} text */
toSearch: (text) =>
(text ?? "")
.toLowerCase()
.replaceAll("ー", "-")
.replaceAll("、", ",")
.replaceAll("。", "."),
};
/**
* moduleLike: データベース
* - callback: lectureTable
*/
const lectureDB = {
async init() {
this.availableCheckbox.addEventListener("click", () =>
lectureTable.update()
);
},
/** @type {Promise<Lecture[]>} */
whole: (async () => {
benchmark.log("* DB init start *");
// キャッシュがあるなら参照する
const loadedLectureList = storageAccess.getItem("lectureDB");
if (loadedLectureList) {
benchmark.log("* load DB from cache *");
return loadedLectureList;
}
benchmark.log("* DB process start *");
/** @type {Lecture[]} */
const allLectureList = await (
await fetch(`./classList/processed${LAST_UPDATED}.json`)
).json();
benchmark.log("* DB init end *");
// setTimeoutしても、結局メインの動作は止まる
storageAccess.setItem("lectureDB", allLectureList);
benchmark.log("* DB cached *");
return allLectureList;
})(),
get reference() {
return this.availableCheckbox.checked ? this.specified : this.whole;
},
/** @type {Lecture[]} */
specified: undefined,
availableCheckbox: document.getElementById("available-only"),
/** @param {(lecture: Lecture) => boolean} filter */
async setSpecificator(filter) {
this.specified = (await this.whole).filter(filter);
},
};
lectureDB.init();
/** moduleLike: 講義詳細 */
const detailViews = {
init() {
const removeDetailButton = document.getElementById("detail-remove");
removeDetailButton.addEventListener("click", () => hash.remove());
this.overlay.addEventListener("click", () => hash.remove());
window.addEventListener("keydown", (ev) => {
if (ev.key === "Escape") {
hash.remove();
}
});
window.addEventListener("hashchange", () => void this.onHashChange());
},
async onHashChange() {
const code = hash.code;
const lecture = code
? (await lectureDB.whole).find((l) => l.code === code)
: null;
if (lecture) {
document.title = `${lecture.titleJp} - シ楽バス`;
this.window.hidden = false;
this.overlay.hidden = false;
this.update(lecture);
} else {
document.title = "シ楽バス - 履修登録支援システム";
this.window.hidden = true;
this.overlay.hidden = true;
}
},
checkbox: document.getElementById("detail-checkbox"),
class: document.getElementById("detail-class"),
classroom: document.getElementById("detail-classroom"),
code: document.getElementById("detail-code"),
detail: document.getElementById("detail-detail"),
evaluation: document.getElementById("detail-evaluation"),
guidance: document.getElementById("detail-guidance"),
label: document.getElementById("detail-label"),
lecturer: document.getElementById("detail-lecturer"),
methods: document.getElementById("detail-methods"),
notes: document.getElementById("detail-notes"),
period: document.getElementById("detail-period"),
schedule: document.getElementById("detail-schedule"),
time: document.getElementById("detail-time"),
title: document.getElementById("detail-title"),
type: document.getElementById("detail-type"),
window: document.getElementById("detail-window"),
content: document.getElementById("detail-content"),
overlay: document.getElementById("overlay"),
/** @param {...string} contents */
join: (...contents) => contents.join(" / "),
/**
* @param {RegExp} regexp
* @returns {(...contents: string[]) => string}
*/
getJoiner: (regexp) => {
/** @type {(text: string) => string} */
const mark =
regexp.source === "(?:)"
? (text) => text
: (text) => text.replace(regexp, "<mark>$&</mark>");
return (...contents) =>
contents
.map((text) =>
text
? mark(text)
.replace(/<(?!\/?mark>)/g, "<")
.replace(/(?<!<\/?mark)>/g, ">")
.replaceAll('"', """)
.replaceAll("\n", "<br>")
: ""
)
.join(" / ")
.replace(/(?: \/ ){1,4}$/, "");
},
/** @param {Lecture} lecture */
update(lecture) {
// テキスト部分
this.class.textContent = lecture.class;
this.period.textContent = this.join(
lecture.semester,
lecture.periods.join("・"),
`${lecture.credits}単位`
);
this.type.textContent = this.join(lecture.type, lecture.category);
// 検索ハイライトを当てる部分
const highlightWords = new RegExp(
search.textInput.keywords[0].join("|"),
"ig"
);
const joinWithHighlight = this.getJoiner(highlightWords);
this.title.innerHTML = joinWithHighlight(lecture.titleJp, lecture.titleEn);
this.lecturer.innerHTML = joinWithHighlight(
lecture.lecturerJp,
lecture.lecturerEn
);
this.detail.innerHTML = joinWithHighlight(lecture.detail);
this.classroom.innerHTML = joinWithHighlight(lecture.classroom);
this.methods.innerHTML = joinWithHighlight(lecture.methods);
this.evaluation.innerHTML = joinWithHighlight(lecture.evaluation);
this.guidance.innerHTML = (() => {
switch (lecture.guidance) {
case "初回":
case "別日":
const text = joinWithHighlight(
...[
lecture.guidance,
[
lecture.guidanceDate
.replace(/[年月]/g, "/")
.replace(/[ 日]/g, ""),
lecture.guidancePeriod &&
`${Number(lecture.guidancePeriod.slice(0, 1)) || "他曜"}限`,
]
.filter((v) => v)
.join(" "),
lecture.guidancePlace,
].filter((v) => v)
);
return text.length === 2 ? `${text}に行う` : text;
case "なし":
return "実施しない";
default:
return "";
}
})();
this.notes.innerHTML = joinWithHighlight(lecture.notes);
this.schedule.innerHTML = joinWithHighlight(lecture.schedule);
this.code.innerHTML = joinWithHighlight(lecture.code, lecture.ccCode);
this.time.innerHTML = joinWithHighlight(
`${lecture.time}分`,
lecture.timeCompensation
);
// ボタン部分
const checkboxId = `checkbox-${lecture.code}`;
this.label.htmlFor = checkboxId;
this.checkbox.checked = document.getElementById(checkboxId).checked;
// スクロール位置
this.content.scrollTo(0, 0);
},
};
detailViews.init();
/** moduleLike: 曜限計算 */
const periodsUtils = {
init() {
for (let time = 1; time <= 6; time++) {
this.headerIdToPeriods.set(`all-${time}`, []);
}
for (const [dayJp, dayEn] of this.dayJpToEn) {
const dayId = `${dayEn}-all`;
this.headerIdToPeriods.set(dayId, []);
for (let time = 1; time <= 6; time++) {
const period = `${dayJp}${time}`;
this.periodToId.set(period, `${dayEn}-${time}`);
this.headerIdToPeriods.get(dayId).push(period);
this.headerIdToPeriods.get(`all-${time}`).push(period);
}
}
this.headerIdToPeriods.set("intensive-all", ["集中"]);
this.periodToId.set("集中", "intensive-0");
},
dayJpToEn: new Map([
["月", "monday"],
["火", "tuesday"],
["水", "wednesday"],
["木", "thursday"],
["金", "friday"],
]),
dayToday: new Intl.DateTimeFormat("en-US", { weekday: "long" })
.format(new Date())
.toLowerCase(),
/** @type {Map<string, Period[]>} */
headerIdToPeriods: new Map(),
/** @type {Map<Period, string>} */
periodToId: new Map(),
};
periodsUtils.init();
/**
* moduleLike: 登録講義
* - 依存先: storageAccess, lectureDB, periodsUtils
* - TODO: 必修か+自クラス対象かの4通りで文字色を変える
*/
const registration = {
/** 単位計算&表示用の名前ごとのカウンタ */
lectureCounter: new LectureCounterSemesterScope("S", "A"),
/**
* 講義が登録されているかを返す
* @param {Lecture} lecture
* @returns {boolean}
*/
has(lecture) {
return this.lectureCounter.has(lecture);
},
/**
* 講義を登録する
* @param {Lecture} lecture
*/
add(lecture) {
this.lectureCounter.push(lecture);
this.save();
},
/**
* 登録リストから講義を削除する
* @param {Lecture} lecture
*/
delete(lecture) {
this.lectureCounter.delete(lecture);
this.save();
},
/** 登録リストを初期化する */
clear() {
// 講義テーブルの登録ボタンの表示を実態に合わせる
for (const lecture of this.lectureCounter.values()) {
const button = lecture.tableRow.lastElementChild.childNodes[0];
if (button) {
// click()にしていないのは再描画の繰り返しを避けるため
button.checked = false;
}
}
this.lectureCounter.clear();
this.save();
},
/**
* 登録ボタン以外から複数講義を登録する
* @param {(lecture: Lecture) => boolean} lectureFilter
* @param {boolean} isSpecified
*/
async setByFilter(lectureFilter, isSpecified) {
const lectureList = (
await lectureDB[isSpecified ? "specified" : "whole"]
).filter(lectureFilter);
for (const lecture of lectureList) {
// 講義テーブルの登録ボタンの表示を実態に合わせる
const button = lecture.tableRow.lastElementChild.childNodes[0];
if (button) {
// click()にしていないのは再描画の繰り返しを避けるため
button.checked = true;
}
}
this.lectureCounter.push(...lectureList);
this.save();
},
save() {
storageAccess.setItem("registeredCodes", [...this.lectureCounter.keys()]);
},
load() {
const registeredCodes = new Set(storageAccess.getItem("registeredCodes"));
if (registeredCodes.size) {
this.setByFilter((lecture) => registeredCodes.has(lecture.code), false);
return true;
}
return false;
},
creditDisplay: document.getElementById("credit-counter"),
/** 単位数を計算し、表示に反映させる */
updateCreditsCount() {
this.creditDisplay.textContent = this.lectureCounter.credits;
},
};
// calendar, search
// 子要素の変更に対応して講義テーブルを更新する
const updateByClick = (ev) => {
const target = ev.target;
switch (target?.tagName) {
case "LABEL":
case "BUTTON":
// 子要素に登録済講義表示ボタンがないことを確認すること
search.showSearchedButton.checked = true;
// clickイベントを検出しているため、setTimeoutの中に入れる(inputのchangeを待つ)必要がある
setTimeout(() => lectureTable.update(), 0);
}
};
/**
* moduleLike: カレンダー
* - 依存先: periodsUtils, registration
* - callback: search, lectureTable
* - 機能: 登録講義の表示, 検索機能の呼び出し, 検索対象の曜限を保持
*/
const calendar = {
init() {
// 空きコマ選択ボタン
const selectBlankButton = document.getElementById("blank-period");
selectBlankButton.addEventListener("click", () => this.selectBlank());
// 曜限リセットボタン
const resetPeriodButton = document.getElementById("all-period");
resetPeriodButton.addEventListener("click", () => this.set([]));
// 各曜日, 各時間帯に検索機能を設定
for (const [id, reference] of periodsUtils.headerIdToPeriods) {
const header = document.getElementById(id);
header.addEventListener("click", () => this.toggle(reference));
if (id.includes(periodsUtils.dayToday)) {
this.todayHeader = header;
}
}
},
/** @type {HTMLElement?} */
todayHeader: null,
// TODO: HTML構成部分切り出し?
/** @type {Map<Period, HTMLElement>} */
periodToElement: (() => {
// 子要素の変更に対応して講義テーブルを更新する
const calendarContainer = document.getElementById("calendar-container");
calendarContainer.addEventListener("click", updateByClick);
// ここで要素を構成する
const createTh = (dayEn, time, text) => {
const th = document.createElement("th");
const button = document.createElement("button");
button.id = `${dayEn}-${time}`;
button.textContent = text;
th.append(button);
if (dayEn === periodsUtils.dayToday) {
button.className = "today-button";
}
return th;
};
const createTd = (dayEn, time) => {
const id = `${dayEn}-${time}`;
const cid = `c-${id}`;
const td = document.createElement("td");
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.id = cid;
checkbox.hidden = true;
const label = document.createElement("label");
label.htmlFor = cid;
label.id = id;
if (dayEn === periodsUtils.dayToday) {
label.className = "today-label";
}
td.append(checkbox, label);
return td;
};
// 外側
const timeTable = document.createElement("table");
timeTable.id = "time-table";
calendarContainer.append(timeTable);
const timeTableHead = document.createElement("thead");
const timeTableBody = document.createElement("tbody");
timeTable.append(timeTableHead, timeTableBody);
const timeTableHeadRow = document.createElement("tr");
timeTableHead.append(timeTableHeadRow);
// 曜日行
timeTableHeadRow.append(document.createElement("th"));
for (const [dayJp, dayEn] of periodsUtils.dayJpToEn) {
timeTableHeadRow.append(createTh(dayEn, "all", dayJp));
}
// 1~6限
for (const time of [1, 2, 3, 4, 5, 6]) {
const tr = document.createElement("tr");
timeTableBody.append(tr);
tr.append(createTh("all", time, time));
for (const dayEn of periodsUtils.dayJpToEn.values()) {
tr.append(createTd(dayEn, time));
}
}
// 集中
const tr = document.createElement("tr");
timeTableBody.append(tr);
tr.append(createTh("intensive", "all", "集"));
const td = createTd("intensive", 0);
td.colSpan = 5;
tr.append(td);
const periodToElement = new Map(
[...periodsUtils.periodToId].map(([period, id]) => [
period,
document.getElementById(id),
])
);
// 基礎生命科学実験αが"集中6"なのでその対応
periodToElement.set("集中6", periodToElement.get("集中"));
return periodToElement;
})(),
// 以下、registrationの表示機能
/**
* カレンダーの指定曜限の表示を更新する(単位数も)
* @param {Period[]} periods
*/
update(periods) {
benchmark.log("calendar update start");
registration.updateCreditsCount();
benchmark.log("credit displayed");
const { stream } = personal.get();
for (const period of periods ?? this.periodToElement.keys()) {
const element = this.periodToElement.get(period);
element.textContent = "";
for (const [semester, counter] of registration.lectureCounter.periodOf(
period
)) {
for (const [name, codeToLecture] of counter) {
const num = codeToLecture.size;
const code = [...codeToLecture.keys()][0];
const lectureBox = document.createElement("button");
lectureBox.className = "lecture-box";
lectureBox.textContent = `${name}${num === 1 ? "" : ` (${num})`}`;
lectureBox.tabIndex = -1;
lectureBox.addEventListener("click", () => {
if (num !== 1) {
window.alert(
"複数の同名講義が登録されているため、その1つを表示します"
);
}
hash.code = code;
});