|
| 1 | +/** |
| 2 | + * WordPress dependencies. |
| 3 | + */ |
| 4 | +import { useEffect, useRef } from '@wordpress/element'; |
| 5 | +import { __ } from '@wordpress/i18n'; |
| 6 | + |
| 7 | +/** |
| 8 | + * Internal dependencies. |
| 9 | + */ |
| 10 | +import useConfirmDialog from './use-confirm-dialog'; |
| 11 | + |
| 12 | +type UseUnsavedChangesDialogOptions = { |
| 13 | + when: boolean; |
| 14 | +}; |
| 15 | + |
| 16 | +// Stack of mounted guards; the last entry owns the document-level handler so |
| 17 | +// only the most-recently-mounted guard prompts when several are active. Using a |
| 18 | +// stack keeps ownership correct under out-of-order unmounts. |
| 19 | +const activeGuards: symbol[] = []; |
| 20 | + |
| 21 | +/** |
| 22 | + * Returns true when `href` resolves to the same origin as the current page — |
| 23 | + * i.e. it is an internal navigation that would unload the wizard. External |
| 24 | + * `https://...` links, `mailto:`, `tel:`, and other schemes navigate to a new |
| 25 | + * context (new tab, mail client, dialer) without unloading the wizard, and |
| 26 | + * must not trigger the discard-changes prompt. |
| 27 | + */ |
| 28 | +function isSameOriginNavigation( link: HTMLAnchorElement ): boolean { |
| 29 | + try { |
| 30 | + const url = new URL( link.href, window.location.href ); |
| 31 | + return url.origin === window.location.origin && ( url.protocol === 'http:' || url.protocol === 'https:' ); |
| 32 | + } catch ( e ) { |
| 33 | + return false; |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +/** |
| 38 | + * Shared unsaved-changes guard. Wraps `useConfirmDialog` with standardized |
| 39 | + * messaging, intercepts same-origin link clicks so the dialog fires instead |
| 40 | + * of a silent navigation, and adds a `beforeunload` listener as the last-resort |
| 41 | + * guard for refresh / tab-close (browser-native, cannot be styled). The |
| 42 | + * returned `confirmDialog` element must be rendered in JSX. |
| 43 | + * |
| 44 | + * Single-consumer constraint: the click handler is attached at the document |
| 45 | + * level in capture phase. Two simultaneously-active instances will both fire |
| 46 | + * a dialog. A development-only warning surfaces this. |
| 47 | + */ |
| 48 | +function useUnsavedChangesDialog( { when }: UseUnsavedChangesDialogOptions ) { |
| 49 | + const { confirmDialog, requestConfirm } = useConfirmDialog( { |
| 50 | + when, |
| 51 | + message: __( 'You have unsaved changes that will be lost. Discard changes?', 'newspack-plugin' ), |
| 52 | + confirmButtonText: __( 'Discard changes', 'newspack-plugin' ), |
| 53 | + hideTitle: true, |
| 54 | + } ); |
| 55 | + |
| 56 | + // Tracks navigation the user has already approved via our custom dialog so |
| 57 | + // the beforeunload guard doesn't fire a second native prompt on top of it. |
| 58 | + const isNavigatingRef = useRef( false ); |
| 59 | + |
| 60 | + useEffect( () => { |
| 61 | + if ( ! when ) { |
| 62 | + return; |
| 63 | + } |
| 64 | + const ownerId = Symbol( 'unsaved-changes-guard' ); |
| 65 | + activeGuards.push( ownerId ); |
| 66 | + if ( process.env.NODE_ENV !== 'production' && activeGuards.length > 1 ) { |
| 67 | + // eslint-disable-next-line no-console |
| 68 | + console.warn( |
| 69 | + 'useUnsavedChangesDialog: more than one active instance detected. ' + |
| 70 | + 'Document-level click capture will fire a dialog per instance — ensure only one guard is active at a time.' |
| 71 | + ); |
| 72 | + } |
| 73 | + const handler = ( e: MouseEvent ) => { |
| 74 | + // Only the top-of-stack guard prompts, so concurrent guards can't stack dialogs. |
| 75 | + if ( activeGuards[ activeGuards.length - 1 ] !== ownerId ) { |
| 76 | + return; |
| 77 | + } |
| 78 | + if ( e.defaultPrevented || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0 ) { |
| 79 | + return; |
| 80 | + } |
| 81 | + const target = e.target as HTMLElement | null; |
| 82 | + const link = target?.closest( 'a[href]' ) as HTMLAnchorElement | null; |
| 83 | + if ( ! link ) { |
| 84 | + return; |
| 85 | + } |
| 86 | + const href = link.getAttribute( 'href' ); |
| 87 | + if ( ! href || href.startsWith( '#' ) || href.startsWith( 'javascript:' ) ) { |
| 88 | + // All `#`-prefixed links are skipped here: plain anchors |
| 89 | + // (`#section`) are scroll targets, and HashRouter paths |
| 90 | + // (`#/route`) are intercepted by `ConfirmDialog`'s built-in |
| 91 | + // `history.block` listener instead. Routing them through |
| 92 | + // `window.location.href` here would trigger a hashchange |
| 93 | + // that the still-active block re-catches, double-prompting. |
| 94 | + return; |
| 95 | + } |
| 96 | + if ( link.target && link.target !== '_self' ) { |
| 97 | + return; |
| 98 | + } |
| 99 | + // Skip mailto:, tel:, external origins, and any non-http(s) scheme — |
| 100 | + // they don't unload the wizard, so a discard prompt would be wrong. |
| 101 | + if ( ! isSameOriginNavigation( link ) ) { |
| 102 | + return; |
| 103 | + } |
| 104 | + e.preventDefault(); |
| 105 | + e.stopPropagation(); |
| 106 | + const destination = link.href; |
| 107 | + requestConfirm( () => { |
| 108 | + isNavigatingRef.current = true; |
| 109 | + window.location.href = destination; |
| 110 | + } ); |
| 111 | + }; |
| 112 | + document.addEventListener( 'click', handler, true ); |
| 113 | + return () => { |
| 114 | + document.removeEventListener( 'click', handler, true ); |
| 115 | + const idx = activeGuards.indexOf( ownerId ); |
| 116 | + if ( idx !== -1 ) { |
| 117 | + activeGuards.splice( idx, 1 ); |
| 118 | + } |
| 119 | + }; |
| 120 | + }, [ when, requestConfirm ] ); |
| 121 | + |
| 122 | + useEffect( () => { |
| 123 | + if ( ! when ) { |
| 124 | + return; |
| 125 | + } |
| 126 | + const handler = ( e: BeforeUnloadEvent ) => { |
| 127 | + if ( isNavigatingRef.current ) { |
| 128 | + return; |
| 129 | + } |
| 130 | + e.preventDefault(); |
| 131 | + e.returnValue = ''; |
| 132 | + }; |
| 133 | + window.addEventListener( 'beforeunload', handler ); |
| 134 | + return () => window.removeEventListener( 'beforeunload', handler ); |
| 135 | + }, [ when ] ); |
| 136 | + |
| 137 | + return { confirmDialog, requestConfirm }; |
| 138 | +} |
| 139 | + |
| 140 | +export default useUnsavedChangesDialog; |
0 commit comments