-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathtoc.js
444 lines (361 loc) · 11.5 KB
/
toc.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
/*
* Tistory TOC (Table Of Contents)
* dev by wbluke (https://wbluke.tistory.com)
* last update 2022.09.28
* version 0.1.9
*/
const CLASS_OF_MAIN_CONTENTS = '.area_view';
const CONSTANTS = (function () {
const KEY_OF_H1 = 1;
const KEY_OF_H2 = 2;
const KEY_OF_H3 = 3;
const KEY_OF_H4 = 4;
const KEY_OF_H5 = 5;
const KEY_OF_H6 = 6;
const LEVEL_1 = 1;
const LEVEL_2 = 2;
const LEVEL_3 = 3;
const LEVEL_4 = 4;
const LEVEL_5 = 5;
const LEVEL_6 = 6;
/* 최상위 태그에 따른 레벨 Map */
const levelsByH1 = function () {
return new Map([
[KEY_OF_H1, LEVEL_1],
[KEY_OF_H2, LEVEL_2],
[KEY_OF_H3, LEVEL_3],
[KEY_OF_H4, LEVEL_4],
[KEY_OF_H5, LEVEL_5],
[KEY_OF_H6, LEVEL_6],
]);
};
const levelsByH2 = function () {
return new Map([
[KEY_OF_H2, LEVEL_1],
[KEY_OF_H3, LEVEL_2],
[KEY_OF_H4, LEVEL_3],
[KEY_OF_H5, LEVEL_4],
[KEY_OF_H6, LEVEL_5],
]);
};
const levelsByH3 = function () {
return new Map([
[KEY_OF_H3, LEVEL_1],
[KEY_OF_H4, LEVEL_2],
[KEY_OF_H5, LEVEL_3],
[KEY_OF_H6, LEVEL_4],
]);
};
const levelsByH4 = function () {
return new Map([
[KEY_OF_H4, LEVEL_1],
[KEY_OF_H5, LEVEL_2],
[KEY_OF_H6, LEVEL_3],
]);
};
const levelsByH5 = function () {
return new Map([
[KEY_OF_H5, LEVEL_1],
[KEY_OF_H6, LEVEL_2],
]);
};
const levelsByH6 = function () {
return new Map([[KEY_OF_H6, LEVEL_1]]);
};
return {
indexOfH1: KEY_OF_H1,
indexOfH2: KEY_OF_H2,
indexOfH3: KEY_OF_H3,
indexOfH4: KEY_OF_H4,
indexOfH5: KEY_OF_H5,
indexOfH6: KEY_OF_H6,
levelsByH1: levelsByH1(),
levelsByH2: levelsByH2(),
levelsByH3: levelsByH3(),
levelsByH4: levelsByH4(),
levelsByH5: levelsByH5(),
levelsByH6: levelsByH6(),
};
})();
const TOC_CARD = (function () {
const TocCardController = function () {
const tocCardService = new TocCardService();
const initTocElementsCard = function () {
tocCardService.initTocElementsCard();
};
const giveIdToHTags = function () {
tocCardService.giveIdToHTags();
};
const registerHTagsOnTocCard = function () {
const levelMap = tocCardService.getLevelsByHighestTag();
tocCardService.registerTagsOnToc(levelMap);
};
const init = function () {
const existsHTags = tocCardService.checkExistenceOfHTags();
if (existsHTags) {
initTocElementsCard();
giveIdToHTags();
registerHTagsOnTocCard();
}
};
const onscroll = function () {
const tocTag = tocCardService.findCurrentHTag();
if (tocTag) {
tocCardService.markCurrentHTag(tocTag);
tocCardService.scrollToMainTocTag(tocTag);
tocCardService.detectTocCardPosition();
}
};
return {
init,
onscroll,
};
};
const TocCardService = function () {
const tocElementsCard = document.querySelector('#toc-elements');
const mainContents = document.querySelector(CLASS_OF_MAIN_CONTENTS);
const hTags = (function () {
const foundHTags = mainContents
? mainContents.querySelectorAll('h1, h2, h3, h4, h5, h6')
: [];
/* 글 내용 밑에 있는 [...카테고리의 다른 글] h4 제거 */
return [...foundHTags].filter(
hTag => !hTag.parentElement.classList.contains('another_category')
);
})();
/* h1, h2, h3, h4, h5, h6 태그가 있는지 확인한다 */
const checkExistenceOfHTags = function () {
return hTags.length !== 0;
};
const initTocElementsCard = function () {
tocElementsCard.classList.add('toc-app-common', 'items', 'toc-app-basic');
};
/** 최상위 태그에 따른 레벨 Map 받아오기
*
* h1 ~ h6 태그 중 가장 높은 태그를 찾아서 그에 맞게 Level을 설정한다.
* 예를 들어, h1 태그가 없고 h2, h3 태그만 있는 경우
* h2가 가장 높은 태그이며, 해당 태그 h2에 LEVEL_1을 부여하고 그 다음 태그인 h3에는 LEVEL_2를 부여한다.
*
* 부여된 Level에 따라 적용되는 CSS가 달라진다.
* */
const getLevelsByHighestTag = function () {
const levelMapByHighestTag = {
H1: CONSTANTS.levelsByH1,
H2: CONSTANTS.levelsByH2,
H3: CONSTANTS.levelsByH3,
H4: CONSTANTS.levelsByH4,
H5: CONSTANTS.levelsByH5,
};
return (
levelMapByHighestTag[findHighestHTag().tagName] || CONSTANTS.levelsByH6
);
};
/* 최상위 태그 판별 작업 */
const findHighestHTag = function () {
return [...hTags].reduce((pre, cur) => {
const tagNumOfPre = parseInt(pre.tagName[1]);
const tagNumOfCur = parseInt(cur.tagName[1]);
return tagNumOfPre < tagNumOfCur ? pre : cur;
});
};
/* TOC에 태그 삽입 */
const registerTagsOnToc = function (levelMap) {
hTags.forEach((hTag, indexOfHTag) => {
let hTagItem;
levelMap.forEach((level, key) => {
if (hTag.matches(`h${key}`)) {
hTagItem = createTagItemByLevel(level, hTag, indexOfHTag);
}
});
tocElementsCard.appendChild(hTagItem);
});
};
const createTagItemByLevel = function (
level = CONSTANTS.NUM_OF_H1,
hTag,
indexOfHTag
) {
const basicItem = createBasicItemBy(hTag, indexOfHTag);
appendScrollEventsOn(basicItem, indexOfHTag);
basicItem.classList.add(`toc-level-${level}`);
return basicItem;
};
const createBasicItemBy = function (hTag, indexOfHTag) {
const basicItem = document.createElement('a');
let hTagInnerText = hTag.innerText;
/* H tag 내용에 부등호 괄호가 포함되어 있을 때, 이를 html 특수문자 코드로 변경 */
if (hTag.innerText.includes('<')) {
hTagInnerText = hTagInnerText.replace(/</g, '&lt;');
hTagInnerText = hTagInnerText.replace(/</g, '<');
}
if (hTag.innerText.includes('>')) {
hTagInnerText = hTagInnerText.replace(/>/g, '&gt;');
hTagInnerText = hTagInnerText.replace(/>/g, '>');
}
basicItem.innerHTML += hTagInnerText;
basicItem.id = `toc-${indexOfHTag}`;
basicItem.classList = 'toc-common';
return basicItem;
};
const generateIdOfHTag = function (indexOfHTag) {
return 'h-tag-' + indexOfHTag;
};
const appendScrollEventsOn = function (basicItem, indexOfHTag) {
const target = document.querySelector(
'#' + generateIdOfHTag(indexOfHTag)
);
basicItem.addEventListener('click', () =>
window.scrollTo({
top: target.offsetTop - 10,
behavior: 'smooth',
})
);
};
const giveIdToHTags = function () {
hTags.forEach((hTag, indexOfHTag) => {
hTag.id = generateIdOfHTag(indexOfHTag);
});
};
const findCurrentHTag = function () {
if (hTags.length == 0) {
return undefined;
}
const currentHTag = findCurrentMainHTag();
return findTocTagCorrespondingToHTag(currentHTag);
};
const findCurrentMainHTag = function () {
const headArea = document.querySelector('.area_head');
let headAreaHeight = 0;
if (headArea) {
headAreaHeight = headArea.offsetHeight;
}
const middleHeight =
window.scrollY + window.innerHeight / 2 - headAreaHeight;
return [...hTags].reduce((pre, cur) => {
if (middleHeight < pre.offsetTop && middleHeight < cur.offsetTop) {
return pre;
}
if (pre.offsetTop < middleHeight && middleHeight <= cur.offsetTop) {
return pre;
}
return cur;
});
};
const findTocTagCorrespondingToHTag = function (currentHTag) {
const indexOfHTag = parseIndexOfTag(currentHTag);
return document.querySelector(`#toc-${indexOfHTag}`);
};
const parseIndexOfTag = function (hTag) {
const tokens = hTag.id.split('-');
return parseInt(tokens[tokens.length - 1]);
};
const markCurrentHTag = function (tocTag) {
removeAllClassOnTocTags('toc-active');
tocTag.classList.add('toc-active');
markParentHTagOf(tocTag);
};
const removeAllClassOnTocTags = function (className) {
Array.prototype.slice.call(tocElementsCard.children).forEach(child => {
child.classList.remove(className);
});
};
const markParentHTagOf = function (tocTag) {
const indexOfTocTag = parseIndexOfTag(tocTag);
const levelOfBaseTocTag = findLevelOfTocTag(tocTag);
removeAllClassOnTocTags('toc-parent-active');
compareLevelAndMark(levelOfBaseTocTag, indexOfTocTag);
};
/**
* 현재 active 태그의 부모 레벨 태그를 표시
* 기준 태그(active 태그)애서 하나씩 위로 올라가면서 부모 태그를 탐색 (재귀)
* */
const compareLevelAndMark = function (
levelOfBaseTocTag,
indexOfCurrentTocTag
) {
if (levelOfBaseTocTag <= 1 || indexOfCurrentTocTag < 0) {
return;
}
const currentTocTag = document.querySelector(
`#toc-${indexOfCurrentTocTag}`
);
const levelOfCurrentTocTag = findLevelOfTocTag(currentTocTag);
if (levelOfBaseTocTag <= levelOfCurrentTocTag) {
return compareLevelAndMark(levelOfBaseTocTag, indexOfCurrentTocTag - 1);
}
currentTocTag.classList.add('toc-parent-active');
compareLevelAndMark(levelOfBaseTocTag - 1, indexOfCurrentTocTag - 1);
};
const findLevelOfTocTag = function (tocTag) {
const classes = tocTag.classList;
if (classes.contains('toc-level-5')) {
return 5;
}
if (classes.contains('toc-level-4')) {
return 4;
}
if (classes.contains('toc-level-3')) {
return 3;
}
if (classes.contains('toc-level-2')) {
return 2;
}
return 1;
};
/**
* TOC 항목이 너무 많아 TOC Card에 스크롤이 생길 경우,
* 스크롤 이벤트에 따라 활성화된 TOC 태그가 보이도록 TOC Card의 스크롤도 함께 이동한다.
*/
const scrollToMainTocTag = function (tocTag) {
tocElementsCard.scroll({
top: tocTag.offsetTop - tocTag.offsetParent.offsetHeight * 0.3,
behavior: 'smooth',
});
};
const detectTocCardPosition = function () {
const currentScrollTop = document.documentElement.scrollTop;
const footer = document.querySelector('#mEtc');
let footerTop = Number.MAX_SAFE_INTEGER;
if (footer) {
footerTop = footer.offsetTop;
}
const elementsCardBottom =
currentScrollTop + tocElementsCard.offsetHeight;
tocElementsCard.classList.remove('toc-app-basic', 'toc-app-bottom');
if (elementsCardBottom >= footerTop) {
tocElementsCard.classList.add('toc-app-bottom');
return;
}
tocElementsCard.classList.add('toc-app-basic');
};
return {
checkExistenceOfHTags,
initTocElementsCard,
getLevelsByHighestTag,
registerTagsOnToc,
giveIdToHTags,
findCurrentHTag,
markCurrentHTag,
scrollToMainTocTag,
detectTocCardPosition,
};
};
const tocCardController = new TocCardController();
const init = function () {
tocCardController.init();
};
const onscroll = function () {
tocCardController.onscroll();
};
return {
init,
onscroll,
};
})();
TOC_CARD.init();
/**
* scroll 시 현재 내용의 위치를 스크롤 이벤트를 통해 TOC에 표시해주기
*/
window.onscroll = function () {
TOC_CARD.onscroll();
};