forked from bit-docs/bit-docs-html-toc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
prev-next.js
63 lines (53 loc) · 1.74 KB
/
prev-next.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
class BitPrevNext extends HTMLElement {
connectedCallback() {
this.setPreviousNext();
if (this.hasPrevious()) {
this.appendChild(this.getAnchorElement(this.previous, true));
}
if (this.hasNext()) {
this.appendChild(this.getAnchorElement(this.next));
}
}
hasNext() {
return this.next.element != null;
}
hasPrevious() {
return this.previous.element != null;
}
get listSelector() {
return this.getAttribute('list-selector');
}
setPreviousNext() {
const list = document.querySelectorAll(this.listSelector)[0];
const currentElement = this.getCurrentElement(list);
const previousElement = currentElement ? currentElement.parentElement.previousElementSibling : null;
const nextElement = currentElement ? currentElement.parentElement.nextElementSibling : null;
const previousNext = function(element) {
if (element) {
return {
element: element,
title: element.firstElementChild.innerText,
href: element.firstElementChild.href,
};
}
return {};
};
this.previous = previousNext(previousElement);
this.next = previousNext(nextElement);
}
getCurrentElement(list) {
return Array.from(
list.querySelectorAll('a')
).find(
(val) => val.href.split('#')[0].split('?')[0] === location.href.split('#')[0].split('?')[0]
);
}
getAnchorElement(previousNextObj, isPrevious) {
const anchor = document.createElement('a');
anchor.setAttribute('href', previousNextObj.href);
anchor.innerText = `${isPrevious ? 'Previous' : 'Next'} Lesson: ${previousNextObj.title}`;
anchor.title = previousNextObj.title;
return anchor;
}
}
module.exports = customElements.define('bit-prev-next', BitPrevNext);