import { router } from '@inertiajs/react'; export function departureUrl(current: string, href: string): string | null { const source = new URL(current); const target = new URL(href, source); if (!['http:', 'https:'].includes(target.protocol)) return null; if (source.origin !== target.origin) return null; if (source.pathname === target.pathname && source.search === target.search) return null; return target.href; } export function protectDepartures( dirty: (submittedForm?: HTMLFormElement) => boolean, prompt: (proceed: () => void) => void, ): () => void { let submittedForm: HTMLFormElement | undefined; const submit = (event: Event) => { if (!(event.target instanceof HTMLFormElement)) return; submittedForm = event.target; queueMicrotask(() => { submittedForm = undefined; }); }; const click = (event: MouseEvent) => { if (!(event.target instanceof Element)) return; const link = event.target.closest('a'); if ( !link || event.defaultPrevented || event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey || link.hasAttribute('download') || (link.target && link.target !== '_self') || !dirty() || !departureUrl(window.location.href, link.href) ) return; event.preventDefault(); event.stopPropagation(); const href = link.href; prompt(() => window.location.assign(href)); }; const offBefore = router.on('before', (event) => { const visit = event.detail.visit; if ( visit.method !== 'get' || !dirty(submittedForm) || !departureUrl(window.location.href, visit.url.href) ) return; event.preventDefault(); prompt(() => router.visit(visit.url, visit)); }); const unload = (event: BeforeUnloadEvent) => { if (dirty()) { event.preventDefault(); event.returnValue = ''; } }; document.addEventListener('click', click, true); document.addEventListener('submit', submit, true); window.addEventListener('beforeunload', unload); return () => { document.removeEventListener('click', click, true); document.removeEventListener('submit', submit, true); window.removeEventListener('beforeunload', unload); offBefore(); }; }