mylloon.fr/static/js/cours.js
Mylloon fcc146842c
Some checks are pending
ci/woodpecker/push/publish Pipeline is pending
clickable filetree
2023-11-01 13:28:19 +01:00

56 lines
1.5 KiB
JavaScript

/**
* Build the filetree
* @param {HTMLElement} parent Root element of the filetree
* @param {{name: string, is_dir: boolean, children: any[]}} data FileNode
* @param {string} location Current location, used for links creation
*/
const buildFileTree = (parent, data, location) => {
const ul = document.createElement("ul");
data.forEach((item) => {
const li = document.createElement("li");
li.classList.add(item.is_dir ? "directory" : "file");
if (item.is_dir) {
// Directory
li.textContent = item.name;
li.classList.add("collapsed");
li.addEventListener("click", function (e) {
if (e.target === li) {
li.classList.toggle("collapsed");
}
});
} else {
// File
const url = window.location.href.split("?")[0];
const a = document.createElement("a");
a.text = item.name;
a.href = `${url}?q=${location}${item.name}`;
li.appendChild(a);
}
ul.appendChild(li);
if (item.children && item.children.length > 0) {
buildFileTree(
li,
item.children,
item.is_dir ? location + `${item.name}/` : location
);
}
});
parent.appendChild(ul);
};
window.addEventListener("load", () => {
const fileTreeElement = document.getElementsByTagName("aside")[0];
const dataElement = fileTreeElement.getElementsByTagName("span")[0];
buildFileTree(
fileTreeElement,
JSON.parse(dataElement.getAttribute("data-json")).children,
""
);
dataElement.remove();
});