From e869b8a10441ab8ef668a0402471723fd8c99da4 Mon Sep 17 00:00:00 2001 From: hippoz Date: Sun, 25 Oct 2020 16:20:23 +0200 Subject: [PATCH] add routing --- res/index.js | 99 +++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 74 insertions(+), 25 deletions(-) diff --git a/res/index.js b/res/index.js index e5218c3..9ffe0b9 100644 --- a/res/index.js +++ b/res/index.js @@ -6,39 +6,88 @@ const changeSelected = (buttonId) => { selectedButtonId = buttonId; }; +const stripTrailingSlash = (str) => { + return str.endsWith('/') ? str.slice(0, -1) : str; +}; + +const peformRouteAction = (pathname) => { + const route = stripTrailingSlash(pathname); + + switch (route) { + case '/': { + A('#content-container').load('/pages/home.html'); + break; + } + case '/upload': { + A('#content-container').load('/pages/upload.html'); + break; + } + case '/git': { + window.location.href = 'https://git.hippoz.xyz/'; + break; + } + case '/about': { + A('#content-container').load('/pages/about.html'); + break; + } + case '/contact': { + A('#content-container').load('/pages/contact.html'); + break; + } + case '/404': {} + default: { + A('#content-container').html('

page not found

i think

'); + break; + } + } +}; + +const buttonMap = { + 'button-home': '/', + 'button-file-server': '/upload', + 'button-git-server': '/git', + 'button-about-me': '/about', + 'button-contact-me': '/contact', + '__NOT_FOUND': '/404' +} + const onButtonClick = (buttonId) => { if (selectedButtonId === buttonId) { return; } changeSelected(buttonId); - switch (buttonId) { - case 'button-home': { - A('#content-container').load('/pages/home.html'); + + let route = buttonMap[buttonId]; + if (!route) { + route = buttonMap['__NOT_FOUND']; + } + + peformRouteAction(route); + + history.pushState({ route }, '', route); +}; + +const getButtonFromPathname = (pathname) => { + let button = 'button-home'; + for (const [k, v] of buttonMap) { + if (v === pathname) { + button = k; break; } - case 'button-file-server': { - A('#content-container').load('/pages/upload.html'); - break; - } - case 'button-git-server': { - window.location.href = 'https://git.hippoz.xyz/'; - break; - } - case 'button-about-me': { - A('#content-container').load('/pages/about.html'); - break; - } - case 'button-contact-me': { - A('#content-container').load('/pages/contact.html'); - break; - } - default: { - console.error('Page not found. Invalid button ID.'); - A('#content-container').html('

page not found

i think

'); - return; - } } -}; + return button; +} + +const updateFromCurrentPathname = () => { + let pathname = window.location.pathname; + if (!pathname || pathname === '' || pathname === ' ') { + pathname = '/'; + } + + const buttonId = getButtonFromPathname(pathname); + changeSelected(buttonId); + peformRouteAction(route); +} A(() => { A('#content-container').load('/pages/home.html');