-
-
Notifications
You must be signed in to change notification settings - Fork 5.7k
/
Copy pathsidebar.js
106 lines (90 loc) · 2.37 KB
/
sidebar.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
/* eslint-disable no-unused-vars */
import { isMobile } from '../util/env';
import * as dom from '../util/dom';
const title = dom.$.title;
/**
* Toggle button
* @param {Element} el Button to be toggled
* @void
*/
export function btn(el) {
const toggle = _ => dom.body.classList.toggle('close');
el = dom.getNode(el);
if (el === null || el === undefined) {
return;
}
dom.on(el, 'click', e => {
e.stopPropagation();
toggle();
});
isMobile &&
dom.on(
dom.body,
'click',
_ => dom.body.classList.contains('close') && toggle()
);
}
export function collapse(el) {
el = dom.getNode(el);
if (el === null || el === undefined) {
return;
}
dom.on(el, 'click', ({ target }) => {
if (
target.nodeName === 'A' &&
target.nextSibling &&
target.nextSibling.classList &&
target.nextSibling.classList.contains('app-sub-sidebar')
) {
dom.toggleClass(target.parentNode, 'collapse');
}
});
}
export function sticky() {
const cover = dom.getNode('section.cover');
if (!cover) {
return;
}
const coverHeight = cover.getBoundingClientRect().height;
if (window.pageYOffset >= coverHeight || cover.classList.contains('hidden')) {
dom.toggleClass(dom.body, 'add', 'sticky');
} else {
dom.toggleClass(dom.body, 'remove', 'sticky');
}
}
/**
* Get and active link
* @param {Object} router Router
* @param {String|Element} el Target element
* @param {Boolean} isParent Active parent
* @param {Boolean} autoTitle Automatically set title
* @return {Element} Active element
*/
export function getAndActive(router, el, isParent, autoTitle) {
el = dom.getNode(el);
let links = [];
if (el !== null && el !== undefined) {
links = dom.findAll(el, 'a');
}
const hash = decodeURI(router.toURL(router.getCurrentPath()));
let target;
links
.sort((a, b) => b.href.length - a.href.length)
.forEach(a => {
const href = decodeURI(a.getAttribute('href'));
const node = isParent ? a.parentNode : a;
a.title = a.title || a.innerText;
if (hash.indexOf(href) === 0 && !target) {
target = a;
dom.toggleClass(node, 'add', 'active');
} else {
dom.toggleClass(node, 'remove', 'active');
}
});
if (autoTitle) {
dom.$.title = target
? target.title || `${target.innerText} - ${title}`
: title;
}
return target;
}