forked from defunkt/toes
60 lines
1.6 KiB
TypeScript
60 lines
1.6 KiB
TypeScript
import { setCurrentView, setDashboardTab, setSelectedApp, setSelectedTab } from './state'
|
|
|
|
let _render: () => void
|
|
|
|
export function navigate(href: string) {
|
|
history.pushState(null, '', href)
|
|
route()
|
|
}
|
|
|
|
export function initRouter(render: () => void) {
|
|
_render = render
|
|
|
|
// Intercept link clicks
|
|
document.addEventListener('click', e => {
|
|
const a = (e.target as Element).closest('a')
|
|
if (!a || !a.href || a.origin !== location.origin || a.target === '_blank') return
|
|
if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return
|
|
e.preventDefault()
|
|
history.pushState(null, '', a.href)
|
|
route()
|
|
})
|
|
|
|
// Handle back/forward
|
|
window.addEventListener('popstate', route)
|
|
|
|
// Initial route from URL
|
|
route()
|
|
}
|
|
|
|
function route() {
|
|
const path = location.pathname
|
|
|
|
if (path.startsWith('/app/')) {
|
|
const rest = decodeURIComponent(path.slice(5))
|
|
const slashIdx = rest.indexOf('/')
|
|
const name = slashIdx === -1 ? rest : rest.slice(0, slashIdx)
|
|
const tab = slashIdx === -1 ? 'overview' : rest.slice(slashIdx + 1)
|
|
setSelectedApp(name)
|
|
setSelectedTab(name, tab)
|
|
setCurrentView('dashboard')
|
|
} else if (path === '/settings') {
|
|
setSelectedApp(null)
|
|
setCurrentView('settings')
|
|
} else if (path === '/logs') {
|
|
setSelectedApp(null)
|
|
setDashboardTab('logs')
|
|
setCurrentView('dashboard')
|
|
} else if (path === '/metrics') {
|
|
setSelectedApp(null)
|
|
setDashboardTab('metrics')
|
|
setCurrentView('dashboard')
|
|
} else {
|
|
setSelectedApp(null)
|
|
setDashboardTab('urls')
|
|
setCurrentView('dashboard')
|
|
}
|
|
|
|
_render()
|
|
}
|