-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmenusio.js
55 lines (41 loc) · 1.87 KB
/
menusio.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
const menusio = (() => {
const build = (arg) => {
const { article, existingIds = false, selectorLink = true, classesNotInMenu = [], selectors, ordered, minItems = 0 } = arg;
// Typo fix
if (!arg.selectorBeforeMenu && arg.selectorBeforMenu) {
console.error('Menusio: Don\'t use selectorBeforMenu. Use selectorBeforeMenu instead');
}
const main = document.querySelector(article);
if (!main) return;
const listType = ordered ? "ol" : "ul";
let selectorBeforeMenu = document.querySelector(arg.selectorBeforeMenu || arg.selectorBeforMenu) || main.querySelector("h1");
const list = main.querySelectorAll(selectors);
const items = [];
for (let i = 0; i < list.length; i++) {
if (classesNotInMenu.some(className => list[i].classList.contains(className))) continue;
items.push(list[i]);
}
if (items.length < minItems) {
return;
}
const menuList = document.createElement(listType);
menuList.setAttribute("id", "js-menusio");
selectorBeforeMenu.parentNode.insertBefore(menuList, selectorBeforeMenu.nextSibling);
for (let i = 0; i < items.length; i++) {
const link = document.createElement("a");
const li = document.createElement("li");
const id = items[i].textContent.normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/[^a-zA-Z0-9]/g, "-").toLowerCase();
if (!items[i].id || !existingIds) {
items[i].id = id;
}
link.setAttribute("href", `#${items[i].id}`);
link.textContent = items[i].textContent;
if (selectorLink) {
items[i].innerHTML = link.outerHTML;
}
li.appendChild(link);
menuList.appendChild(li);
}
}
return { build };
})();