stacks/homelab/www/index.mjs

95 lines
2.4 KiB
JavaScript

let frames = {}
function activate(event, element) {
if (element.target) {
return
}
event.preventDefault()
let parent = element.parentElement
for (let e of parent.getElementsByClassName("active")) {
e.classList.remove("active")
}
element.classList.add("active")
let href = element.href
let app = document.querySelector("#app")
let frame = frames[href]
if (frame) {
frame.dispatchEvent(new Event("load"))
} else {
frame = app.appendChild(document.createElement("iframe"))
frame.addEventListener("load", e => frameLoaded(frame))
frame.src = href
frames[href] = frame
}
for (let fhref in frames) {
let f = frames[fhref]
if (fhref == href) {
f.classList.remove("hidden")
} else {
f.classList.add("hidden")
}
}
}
function frameLoaded(frame) {
let doc = frame.contentDocument
if (doc.title.length > 0) {
document.title = doc.title
}
let icon = document.querySelector("link[rel~='icon']")
let dicon = doc.querySelector("link[rel~='icon']")
if (dicon) {
icon.href = dicon.href
} else {
icon.href = defaultIcon
}
}
let defaultIcon = null
function init() {
let doc = document.querySelector("iframe").contentDocument
defaultIcon = document.querySelector("link[rel~='icon']").href
for (let l of document.head.querySelectorAll("style")) {
doc.head.appendChild(l.cloneNode(true))
}
for (let l of document.head.querySelectorAll("link[rel='stylesheet']")) {
doc.head.appendChild(l.cloneNode())
}
for (let f of document.querySelectorAll("#app iframe")) {
frames[f.src] = f
}
let icons = doc.body.appendChild(doc.createElement("section"))
icons.classList.add("icons")
for (let link of document.querySelectorAll("nav a")) {
let dlink = icons.appendChild(link.cloneNode(true))
dlink.textContent = ""
if (link.dataset.icon) {
let icon = dlink.appendChild(doc.createElement("img"))
icon.src = link.dataset.icon
icon.style.objectFit = "cover"
} else {
let text = dlink.appendChild(doc.createElement("div"))
text.textContent = link.textContent
}
// Make both of them update the selected tab
link.addEventListener("click", event => activate(event, link))
dlink.addEventListener("click", event => activate(event, link))
}
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", init)
} else {
init()
}