koel/resources/assets/js/router.ts

74 lines
2.4 KiB
TypeScript
Raw Normal View History

2022-08-01 11:40:52 +00:00
import { eventBus, loadMainView, use } from '@/utils'
import { playlistStore, userStore } from '@/stores'
2022-04-15 14:24:30 +00:00
2022-05-14 23:37:16 +00:00
class Router {
routes: Record<string, Closure>
2022-04-15 14:24:30 +00:00
2022-05-14 23:37:16 +00:00
constructor () {
this.routes = {
'/home': () => loadMainView('Home'),
'/queue': () => loadMainView('Queue'),
'/songs': () => loadMainView('Songs'),
'/albums': () => loadMainView('Albums'),
'/artists': () => loadMainView('Artists'),
'/favorites': () => loadMainView('Favorites'),
'/recently-played': () => loadMainView('RecentlyPlayed'),
'/search': () => loadMainView('Search.Excerpt'),
'/search/songs/(.+)': (q: string) => loadMainView('Search.Songs', q),
'/upload': () => userStore.current.is_admin && loadMainView('Upload'),
'/settings': () => userStore.current.is_admin && loadMainView('Settings'),
'/users': () => userStore.current.is_admin && loadMainView('Users'),
'/youtube': () => loadMainView('YouTube'),
'/visualizer': () => loadMainView('Visualizer'),
'/profile': () => loadMainView('Profile'),
2022-08-02 06:22:08 +00:00
'/album/(\\d+)': (id: string) => loadMainView('Album', parseInt(id)),
'/artist/(\\d+)': (id: string) => loadMainView('Artist', parseInt(id)),
2022-05-14 23:37:16 +00:00
'/playlist/(\\d+)': (id: number) => use(playlistStore.byId(~~id), playlist => loadMainView('Playlist', playlist)),
2022-08-01 11:40:52 +00:00
'/song/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})': (id: string) => {
eventBus.emit('SONG_QUEUED_FROM_ROUTE', id)
loadMainView('Queue')
2022-06-10 10:47:46 +00:00
}
2022-05-14 23:37:16 +00:00
}
2022-04-15 14:24:30 +00:00
2022-05-14 23:37:16 +00:00
window.addEventListener('popstate', () => this.resolveRoute(), true)
}
public resolveRoute () {
2022-04-15 14:24:30 +00:00
if (!window.location.hash) {
return this.go('home')
}
2022-04-15 17:00:08 +00:00
Object.keys(this.routes).forEach(route => {
2022-04-15 14:24:30 +00:00
const matches = window.location.hash.match(new RegExp(`^#!${route}$`))
if (matches) {
const [, ...params] = matches
this.routes[route](...params)
}
})
2022-05-14 23:37:16 +00:00
}
2022-04-15 14:24:30 +00:00
/**
* Navigate to a (relative, hash-bang'ed) path.
*/
2022-05-14 23:37:16 +00:00
public go (path: string | number) {
2022-04-15 14:24:30 +00:00
if (typeof path === 'number') {
window.history.go(path)
return
}
2022-05-14 18:49:45 +00:00
if (!path.startsWith('/')) {
2022-04-15 14:24:30 +00:00
path = `/${path}`
}
2022-05-14 18:49:45 +00:00
if (!path.startsWith('/#!')) {
2022-04-15 14:24:30 +00:00
path = `/#!${path}`
}
path = path.substring(1, path.length)
document.location.href = `${document.location.origin}${document.location.pathname}${path}`
}
}
2022-05-14 23:37:16 +00:00
export default new Router()