miaopanel
1import { ref } from 'vue'
2import { canLeave, hasUnsaved } from './guard'
3
4export type View =
5 | 'dashboard'
6 | 'apps'
7 | 'plugins'
8 | 'sites'
9 | 'docker'
10 | 'database'
11 | 'waf'
12 | 'files'
13 | 'terminal'
14 | 'ai'
15 | 'security'
16 | 'settings'
17
18const views: View[] = [
19 'dashboard',
20 'apps',
21 'plugins',
22 'sites',
23 'docker',
24 'database',
25 'waf',
26 'files',
27 'terminal',
28 'ai',
29 'security',
30 'settings',
31]
32
33export interface RouteState {
34 view: View
35 /** Detail id carried by the hash, e.g. #/sites/12/logs */
36 id?: number
37 tab?: string
38 query: URLSearchParams
39}
40
41function parseHash(hash: string): RouteState {
42 const raw = hash.replace(/^#\/?/, '')
43 const [pathPart, queryPart] = raw.split('?')
44 const seg = pathPart.split('/').filter(Boolean)
45 const candidate = seg[0] as View
46 const view: View = views.includes(candidate) ? candidate : 'dashboard'
47 const id = seg[1] && /^\d+$/.test(seg[1]) ? Number(seg[1]) : undefined
48 const tab = seg[2] ? decodeURIComponent(seg[2]) : undefined
49 return { view, id, tab, query: new URLSearchParams(queryPart ?? '') }
50}
51
52function toHash(route: RouteState): string {
53 const seg: string[] = [route.view]
54 if (route.id) seg.push(String(route.id))
55 if (route.tab) seg.push(encodeURIComponent(route.tab))
56 const qs = route.query.toString()
57 return '#/' + seg.join('/') + (qs ? '?' + qs : '')
58}
59
60export const route = ref<RouteState>(parseHash(window.location.hash))
61
62export function navigate(
63 view: View,
64 opts: { id?: number; tab?: string; query?: Record<string, string> } = {},
65) {
66 const next: RouteState = {
67 view,
68 id: opts.id,
69 tab: opts.tab,
70 query: new URLSearchParams(opts.query ?? {}),
71 }
72 if (!canLeave()) return
73 route.value = next
74 const hash = toHash(next)
75 if (window.location.hash !== hash) window.location.hash = hash
76 window.scrollTo({ top: 0, behavior: 'auto' })
77}
78
79/** Replace query parameters without adding a history entry. */
80export function updateQuery(patch: Record<string, string | undefined>) {
81 const q = new URLSearchParams(route.value.query)
82 for (const [k, v] of Object.entries(patch)) {
83 if (v === undefined || v === '') q.delete(k)
84 else q.set(k, v)
85 }
86 route.value = { ...route.value, query: q }
87 history.replaceState(null, '', toHash(route.value))
88}
89
90window.addEventListener('hashchange', () => {
91 const next = parseHash(window.location.hash)
92 // Our own navigate() already updated route; only real history moves get the
93 // guard treatment.
94 if (toHash(route.value) === window.location.hash) {
95 route.value = next
96 return
97 }
98 if (!canLeave()) {
99 history.replaceState(null, '', toHash(route.value))
100 return
101 }
102 route.value = next
103 window.scrollTo({ top: 0, behavior: 'auto' })
104})
105
106window.addEventListener('beforeunload', (e) => {
107 if (hasUnsaved()) {
108 e.preventDefault()
109 e.returnValue = ''
110 }
111})