aboutsummaryrefslogtreecommitdiff
path: root/server/src/routes/ui/style/transition.js
blob: 193f5a2896e56ea5aa9d8f936bf8d7a10b8e05b4 (plain)
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
/// <reference lib="dom" />

const duration = 0.2
globalThis.addEventListener("load", () => {
    patch_page()
})

function patch_page() {
    document.querySelectorAll("a").forEach(el => {
        el.addEventListener("click", async ev => {
            ev.preventDefault()
            const trigger_load = prepare_load(el.href)
            await fade(false)
            trigger_load()
        })
    })
}

function prepare_load(href) {
    const r_promise = fetch(href)
    return async () => {
        const r = await r_promise
        const rt = await r.text()
        const [head, body] = rt.split("<head>")[1].split("</body>")[0].split("</head><body>")
        document.head.innerHTML = head
        document.body.innerHTML = body
        fade(true)
        window.history.pushState({}, "", href)
        patch_page()
    }
}

function fade(dir) {
    const overlay = document.createElement("div")
    overlay.style.position = "absolute"
    overlay.style.left = "0px"
    overlay.style.top = "0px"
    overlay.style.width = "100vw"
    overlay.style.height = "100vh"
    overlay.style.backgroundColor = dir ? "black" : "transparent"
    overlay.style.transition = `background-color ${duration}s`
    overlay.style.zIndex = 99999;
    setTimeout(() => {
        overlay.style.backgroundColor = dir ? "transparent" : "black"
    }, 0)
    document.body.appendChild(overlay)
    return new Promise(res => {
        setTimeout(() => {
            document.body.removeChild(overlay)
            res()
        }, duration * 1000)
    })
}