Files
faunosteo/apps/app/src/app/useLeaveGuard.ts
T
bchanot 553a0e57b2 feat(ui): harden modal dialogs, add afterModalsClosed
Re-show a natively closed dialog only when its consumer answered
'kept'; returnFocus; ignore a held Escape; Dialog honours reduced
motion; useBeforeUnload extracted; focusRow reports found only when
the row holds focus.
2026-11-13 17:57:47 +01:00

31 lines
1.0 KiB
TypeScript

import { useEffect } from 'react'
import { useLeaveGuardStore } from '@/state/leaveGuardStore'
/** While `dirty`, a reload, a tab close or a full-page redirect asks first (beforeunload). */
export function useBeforeUnload(dirty: boolean): void {
useEffect(() => {
if (!dirty) return
const guard = (event: BeforeUnloadEvent) => {
event.preventDefault()
event.returnValue = ''
}
window.addEventListener('beforeunload', guard)
return () => window.removeEventListener('beforeunload', guard)
}, [dirty])
}
/**
* While `dirty`, a reload, a tab close or a full-page redirect asks first
* (beforeunload), and AppLayout asks before following a link of the app. The
* declarative router has no navigation blocker: the browser's own back and
* forward buttons are not intercepted (contract §11.3).
*/
export function useLeaveGuard(dirty: boolean): void {
const arm = useLeaveGuardStore((s) => s.arm)
useEffect(() => {
arm(dirty)
return () => arm(false)
}, [dirty, arm])
useBeforeUnload(dirty)
}