仰望星辰工作室

miaopanel

miaopanel/ web/src/guard.ts 809 B · 37 行 原始文件
1// A tiny leave-guard registry. Views with unsaved edits register two
2// functions: one that asks the user (returns false to stay) and one that only
3// reports dirtiness for the beforeunload prompt.
4type LeaveGuard = () => boolean
5type DirtyCheck = () => boolean
6
7let guard: LeaveGuard | null = null
8let dirty: DirtyCheck | null = null
9
10export function setLeaveGuard(fn: LeaveGuard, isDirty?: DirtyCheck) {
11 guard = fn
12 dirty = isDirty ?? null
13}
14
15export function clearLeaveGuard(fn?: LeaveGuard) {
16 if (!fn || guard === fn) {
17 guard = null
18 dirty = null
19 }
20}
21
22export function canLeave(): boolean {
23 if (!guard) return true
24 try {
25 return guard()
26 } catch {
27 return true
28 }
29}
30
31export function hasUnsaved(): boolean {
32 try {
33 return !!dirty && dirty()
34 } catch {
35 return false
36 }
37}