|
| 1 | +import Router from "next/router"; |
| 2 | +import { BeforePopStateCallback, NextHistoryState } from "./types"; |
| 3 | + |
| 4 | +/** |
| 5 | + * Pop‐State Event Bus |
| 6 | + * |
| 7 | + * Provides a centralized mechanism for components to intercept |
| 8 | + * and optionally prevent Back/Forward navigation (Next.js beforePopState). |
| 9 | + */ |
| 10 | + |
| 11 | +/** |
| 12 | + * A set of callback functions that will run before Next.js performs a pop. |
| 13 | + * Each callback returns `true` to allow navigation or `false` to block. |
| 14 | + */ |
| 15 | +const beforePopCallbacks = new Set<BeforePopStateCallback>(); |
| 16 | + |
| 17 | +/** |
| 18 | + * Register a callback to be invoked immediately before any Next.js pop navigation. |
| 19 | + * Return `false` from your callback to prevent the pop; otherwise return `true`. |
| 20 | + * @param cb - The callback function to register. |
| 21 | + */ |
| 22 | +export function registerBeforePopCallback(cb: BeforePopStateCallback): void { |
| 23 | + beforePopCallbacks.add(cb); |
| 24 | +} |
| 25 | + |
| 26 | +/** |
| 27 | + * Unregister a previously registered “before pop” callback. |
| 28 | + * @param cb - The callback function to unregister. |
| 29 | + */ |
| 30 | +export function unregisterBeforePopCallback(cb: BeforePopStateCallback): void { |
| 31 | + beforePopCallbacks.delete(cb); |
| 32 | +} |
| 33 | + |
| 34 | +/** |
| 35 | + * Ensures that we only hook into Next.js once. After install, any pop event |
| 36 | + * will first invoke all registered callbacks and only proceed if all return true. |
| 37 | + */ |
| 38 | +let hasInstalledInterceptor = false; |
| 39 | + |
| 40 | +/** |
| 41 | + * Install the global “before pop” interceptor into Next.js’s router. |
| 42 | + * Subsequent calls to this function will be no‐ops. |
| 43 | + * |
| 44 | + * This method must be called once (e.g. in your app’s top‐level code) |
| 45 | + * to enable the pop‐state bus. |
| 46 | + */ |
| 47 | +export function registerPopStateHandler(): void { |
| 48 | + if (hasInstalledInterceptor) return; |
| 49 | + hasInstalledInterceptor = true; |
| 50 | + |
| 51 | + Router.beforePopState((state: NextHistoryState) => { |
| 52 | + // Iteratively call every callback. If any returns false, block navigation. |
| 53 | + let allAllow = true; |
| 54 | + beforePopCallbacks.forEach((cb) => { |
| 55 | + try { |
| 56 | + if (cb(state) === false) allAllow = false; |
| 57 | + } catch (e: unknown) { |
| 58 | + console.error("Pop listener failed:", e); |
| 59 | + } |
| 60 | + }); |
| 61 | + |
| 62 | + return allAllow; |
| 63 | + }); |
| 64 | +} |
0 commit comments