summaryrefslogtreecommitdiff
path: root/static/src/pages.js
blob: e2199a4af19442e5e4efe615ff2f8e7e7a01c966 (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
54
const menu = document.querySelector("#menu")

export default class Page {
	static pages = {}
	static currentPage = null

	static pathnameCallback() {
		const path = window.location.pathname.replace(/\/$/, "")
		const page = Page.pages[path]

		if (!page)
			throw new Error(`Path '${path}' does not exist`)

		if (Page.currentPage)
			Page.currentPage.setVisible(false)

		page.setVisible(true)
		Page.currentPage = page
	}

	static softRedirect(path) {
		window.history.pushState({}, "", path)
		Page.pathnameCallback()
	}

	constructor(pageContainer, endpoints, f_initialize) {
		for (const endpoint of endpoints)
			Page.pages[endpoint] = this

		this.pageContainer = pageContainer
		this.endpoints = endpoints
		this.initialize = f_initialize
		this.visible = false
		this.initialized = false
	}

	async setVisible(visible) {
		this.pageContainer.classList.toggle("hidden!", !visible)
		this.visible = visible
		if (this.visible) {
			/* initialize page */
			if (!this.initialized && this.initialize)
				this.initialized = await this.initialize(this.pageContainer)

			/* set selected attribute on the link */
			for (const a of menu.querySelectorAll("a")) {
				if (this.endpoints.includes(a.getAttribute("href")))
					a.dataset.selected = "1"
				else
					delete a.dataset.selected
			}
		}
	}
}