@okyrychenko-dev/react-action-guard-router 0.2.4 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +228 -0
- package/README.md +187 -110
- package/dist/index.cjs +30 -17
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +9 -101
- package/dist/index.d.ts +9 -101
- package/dist/index.js +28 -17
- package/dist/index.js.map +1 -1
- package/dist/nextjs/index.cjs +89 -53
- package/dist/nextjs/index.cjs.map +1 -1
- package/dist/nextjs/index.d.cts +1 -100
- package/dist/nextjs/index.d.ts +1 -100
- package/dist/nextjs/index.js +83 -47
- package/dist/nextjs/index.js.map +1 -1
- package/dist/react-router/index.cjs +69 -46
- package/dist/react-router/index.cjs.map +1 -1
- package/dist/react-router/index.d.cts +1 -87
- package/dist/react-router/index.d.ts +1 -87
- package/dist/react-router/index.js +69 -46
- package/dist/react-router/index.js.map +1 -1
- package/dist/tanstack-router/index.cjs +57 -105
- package/dist/tanstack-router/index.cjs.map +1 -1
- package/dist/tanstack-router/index.d.cts +2 -63
- package/dist/tanstack-router/index.d.ts +2 -63
- package/dist/tanstack-router/index.js +58 -106
- package/dist/tanstack-router/index.js.map +1 -1
- package/dist/{types-C3CPuZip.d.cts → types-xxRwsJ1N.d.cts} +0 -35
- package/dist/{types-C3CPuZip.d.ts → types-xxRwsJ1N.d.ts} +0 -35
- package/package.json +80 -66
package/dist/nextjs/index.cjs
CHANGED
|
@@ -1,21 +1,20 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var router_js = require('next/router.js');
|
|
4
4
|
var react = require('react');
|
|
5
|
+
var typeUtils = require('@okyrychenko-dev/type-utils');
|
|
5
6
|
var reactActionGuard = require('@okyrychenko-dev/react-action-guard');
|
|
6
7
|
|
|
7
8
|
// src/nextjs/usePagesRouterBlocker.ts
|
|
8
|
-
|
|
9
|
-
// src/core/utils.ts
|
|
10
9
|
function resolveCondition(condition) {
|
|
11
|
-
return
|
|
10
|
+
return typeUtils.isFunction(condition) ? condition() : condition;
|
|
12
11
|
}
|
|
13
|
-
var hasThen = (value) =>
|
|
12
|
+
var hasThen = (value) => typeUtils.isObject(value) && "then" in value;
|
|
14
13
|
function isThenable(value) {
|
|
15
14
|
if (!hasThen(value)) {
|
|
16
15
|
return false;
|
|
17
16
|
}
|
|
18
|
-
return
|
|
17
|
+
return typeUtils.isFunction(value.then);
|
|
19
18
|
}
|
|
20
19
|
function resolveConfirmResult(message, onConfirm, fallbackConfirm) {
|
|
21
20
|
if (!onConfirm) {
|
|
@@ -27,14 +26,14 @@ function resolveConfirmResult(message, onConfirm, fallbackConfirm) {
|
|
|
27
26
|
}
|
|
28
27
|
return { kind: "sync", confirmed: result };
|
|
29
28
|
}
|
|
30
|
-
function isDefined(value) {
|
|
31
|
-
return value !== void 0 && value !== null;
|
|
32
|
-
}
|
|
33
29
|
function normalizeScope(scope) {
|
|
34
30
|
if (!scope) {
|
|
35
31
|
return [];
|
|
36
32
|
}
|
|
37
|
-
return
|
|
33
|
+
return typeUtils.isArray(scope) ? scope : [scope];
|
|
34
|
+
}
|
|
35
|
+
function createScopeKey(scope) {
|
|
36
|
+
return JSON.stringify([...new Set(normalizeScope(scope))].sort());
|
|
38
37
|
}
|
|
39
38
|
|
|
40
39
|
// src/core/useBeforeUnload.ts
|
|
@@ -61,35 +60,19 @@ function useShouldBlock(when, scope) {
|
|
|
61
60
|
const scopes = react.useMemo(() => normalizeScope(scope), [scope]);
|
|
62
61
|
const isScopeBlocked = reactActionGuard.useIsBlocked(scopes.length === 1 ? scopes[0] : scopes);
|
|
63
62
|
const warnedMissingConditionRef = react.useRef(false);
|
|
64
|
-
const warnedFunctionRef = react.useRef(false);
|
|
65
63
|
react.useEffect(() => {
|
|
66
64
|
if (process.env.NODE_ENV !== "development") {
|
|
67
65
|
return;
|
|
68
66
|
}
|
|
69
|
-
if (!warnedMissingConditionRef.current && !isDefined(when) && !scope) {
|
|
67
|
+
if (!warnedMissingConditionRef.current && !typeUtils.isDefined(when) && !scope) {
|
|
70
68
|
warnedMissingConditionRef.current = true;
|
|
71
69
|
console.warn(
|
|
72
70
|
'[react-action-guard-router] useShouldBlock: Neither "when" nor "scope" provided. This hook will always return false. Please provide at least one condition.'
|
|
73
71
|
);
|
|
74
72
|
}
|
|
75
|
-
if (!warnedFunctionRef.current && typeof when === "function") {
|
|
76
|
-
warnedFunctionRef.current = true;
|
|
77
|
-
console.warn(
|
|
78
|
-
'[react-action-guard-router] useShouldBlock: "when" is a function. Make sure to wrap it with useCallback to avoid unnecessary re-computations.'
|
|
79
|
-
);
|
|
80
|
-
}
|
|
81
73
|
}, [when, scope]);
|
|
82
|
-
const
|
|
83
|
-
|
|
84
|
-
if (isDefined(when)) {
|
|
85
|
-
blockCondition = resolveCondition(when);
|
|
86
|
-
}
|
|
87
|
-
if (scope && isScopeBlocked) {
|
|
88
|
-
blockCondition = true;
|
|
89
|
-
}
|
|
90
|
-
return blockCondition;
|
|
91
|
-
}, [when, scope, isScopeBlocked]);
|
|
92
|
-
return shouldBlock;
|
|
74
|
+
const blockCondition = typeUtils.isDefined(when) && resolveCondition(when);
|
|
75
|
+
return blockCondition || Boolean(scope && isScopeBlocked);
|
|
93
76
|
}
|
|
94
77
|
|
|
95
78
|
// src/core/constants.ts
|
|
@@ -100,56 +83,109 @@ var ROUTE_ERRORS = {
|
|
|
100
83
|
BLOCKED: "Route change blocked"
|
|
101
84
|
};
|
|
102
85
|
|
|
86
|
+
// src/core/confirmationOwner.utils.ts
|
|
87
|
+
function createConfirmationOwner() {
|
|
88
|
+
let currentAttempt = 0;
|
|
89
|
+
function invalidate() {
|
|
90
|
+
currentAttempt += 1;
|
|
91
|
+
}
|
|
92
|
+
function begin() {
|
|
93
|
+
const attempt = ++currentAttempt;
|
|
94
|
+
function settle() {
|
|
95
|
+
if (attempt !== currentAttempt) {
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
invalidate();
|
|
99
|
+
return true;
|
|
100
|
+
}
|
|
101
|
+
return settle;
|
|
102
|
+
}
|
|
103
|
+
return { begin, invalidate };
|
|
104
|
+
}
|
|
105
|
+
|
|
103
106
|
// src/nextjs/usePagesRouterBlocker.ts
|
|
104
107
|
function useNavigationBlocker(options) {
|
|
105
108
|
const { when, scope, message, onBlock, onAllow, blockBrowserUnload = true, onConfirm } = options;
|
|
106
|
-
const router
|
|
107
|
-
const
|
|
109
|
+
const router = router_js.useRouter();
|
|
110
|
+
const callbacksRef = react.useRef({ onBlock, onAllow, onConfirm });
|
|
111
|
+
react.useInsertionEffect(() => {
|
|
112
|
+
callbacksRef.current = { onBlock, onAllow, onConfirm };
|
|
113
|
+
}, [onBlock, onAllow, onConfirm]);
|
|
108
114
|
const shouldBlock = useShouldBlock(when, scope);
|
|
109
|
-
|
|
115
|
+
const scopeKey = createScopeKey(scope);
|
|
116
|
+
react.useInsertionEffect(() => {
|
|
110
117
|
if (!shouldBlock) {
|
|
111
118
|
return;
|
|
112
119
|
}
|
|
113
|
-
const
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
120
|
+
const confirmationOwner = createConfirmationOwner();
|
|
121
|
+
let allowedNavigation = null;
|
|
122
|
+
let currentAttempt = null;
|
|
123
|
+
function handleRouteChangeStart(url) {
|
|
124
|
+
if (allowedNavigation?.url === url) {
|
|
125
|
+
allowedNavigation = null;
|
|
117
126
|
return;
|
|
118
127
|
}
|
|
119
|
-
|
|
128
|
+
allowedNavigation = null;
|
|
129
|
+
const settle = confirmationOwner.begin();
|
|
130
|
+
currentAttempt = settle;
|
|
131
|
+
const { onBlock: onBlock2, onAllow: onAllow2, onConfirm: onConfirm2 } = callbacksRef.current;
|
|
132
|
+
onBlock2?.();
|
|
120
133
|
if (!message) {
|
|
121
|
-
router
|
|
134
|
+
router.events.emit("routeChangeError");
|
|
122
135
|
throw new Error(ROUTE_ERRORS.BLOCKED);
|
|
123
136
|
}
|
|
124
137
|
const confirmation = resolveConfirmResult(
|
|
125
138
|
message,
|
|
126
|
-
|
|
139
|
+
onConfirm2,
|
|
127
140
|
(value) => window.confirm(value)
|
|
128
141
|
);
|
|
129
142
|
if (confirmation.kind === "sync" && !confirmation.confirmed) {
|
|
130
|
-
router
|
|
143
|
+
router.events.emit("routeChangeError");
|
|
131
144
|
throw new Error(ROUTE_ERRORS.ABORTED);
|
|
132
145
|
}
|
|
133
146
|
if (confirmation.kind === "sync") {
|
|
134
|
-
|
|
147
|
+
if (!settle()) {
|
|
148
|
+
router.events.emit("routeChangeError");
|
|
149
|
+
throw new Error(ROUTE_ERRORS.ABORTED);
|
|
150
|
+
}
|
|
151
|
+
onAllow2?.();
|
|
152
|
+
if (currentAttempt !== settle) {
|
|
153
|
+
router.events.emit("routeChangeError");
|
|
154
|
+
throw new Error(ROUTE_ERRORS.ABORTED);
|
|
155
|
+
}
|
|
135
156
|
return;
|
|
136
157
|
}
|
|
137
|
-
router
|
|
138
|
-
|
|
139
|
-
if (confirmed) {
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
158
|
+
router.events.emit("routeChangeError");
|
|
159
|
+
async function complete(confirmed) {
|
|
160
|
+
if (!settle() || !confirmed) {
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
const permission = { url };
|
|
164
|
+
allowedNavigation = permission;
|
|
165
|
+
const { onAllow: notifyAllow } = callbacksRef.current;
|
|
166
|
+
try {
|
|
167
|
+
notifyAllow?.();
|
|
168
|
+
if (allowedNavigation !== permission) {
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
await router.push(url);
|
|
172
|
+
} finally {
|
|
173
|
+
if (allowedNavigation === permission) {
|
|
174
|
+
allowedNavigation = null;
|
|
175
|
+
}
|
|
143
176
|
}
|
|
144
|
-
}
|
|
145
|
-
|
|
177
|
+
}
|
|
178
|
+
void confirmation.promise.then(complete).catch(() => complete(false));
|
|
146
179
|
throw new Error(ROUTE_ERRORS.ABORTED);
|
|
147
|
-
}
|
|
148
|
-
router
|
|
180
|
+
}
|
|
181
|
+
router.events.on("routeChangeStart", handleRouteChangeStart);
|
|
149
182
|
return () => {
|
|
150
|
-
|
|
183
|
+
confirmationOwner.invalidate();
|
|
184
|
+
currentAttempt = null;
|
|
185
|
+
allowedNavigation = null;
|
|
186
|
+
router.events.off("routeChangeStart", handleRouteChangeStart);
|
|
151
187
|
};
|
|
152
|
-
}, [shouldBlock,
|
|
188
|
+
}, [shouldBlock, scopeKey, message, router]);
|
|
153
189
|
useBeforeUnload(blockBrowserUnload && shouldBlock, message ?? DEFAULT_UNLOAD_MESSAGE);
|
|
154
190
|
return {
|
|
155
191
|
isBlocking: shouldBlock
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/core/utils.ts","../../src/core/useBeforeUnload.ts","../../src/core/useShouldBlock.ts","../../src/core/constants.ts","../../src/nextjs/usePagesRouterBlocker.ts","../../src/nextjs/useAppRouterBlocker.ts"],"names":["useEffect","useMemo","useIsBlocked","useRef","router","useRouter","useNavigationBlocker"],"mappings":";;;;;;;;;AAMO,SAAS,iBAAiB,SAAA,EAA+C;AAC9E,EAAA,OAAO,OAAO,SAAA,KAAc,UAAA,GAAa,SAAA,EAAU,GAAI,SAAA;AACzD;AAMA,IAAM,OAAA,GAAU,CAAC,KAAA,KACf,OAAO,UAAU,QAAA,IAAY,KAAA,KAAU,QAAQ,MAAA,IAAU,KAAA;AAKpD,SAAS,WAAc,KAAA,EAAyC;AACrE,EAAA,IAAI,CAAC,OAAA,CAAQ,KAAK,CAAA,EAAG;AACnB,IAAA,OAAO,KAAA;AAAA,EACT;AACA,EAAA,OAAO,OAAO,MAAM,IAAA,KAAS,UAAA;AAC/B;AAiBO,SAAS,oBAAA,CACd,OAAA,EACA,SAAA,EACA,eAAA,EACe;AACf,EAAA,IAAI,CAAC,SAAA,EAAW;AACd,IAAA,OAAO,EAAE,IAAA,EAAM,MAAA,EAAQ,SAAA,EAAW,eAAA,CAAgB,OAAO,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AA,MAAM,WAAA,GAAc,cAAA,CAAe,IAAA,EAAM,KAAK,CAAA;AAG9C,EAAAN,gBAAU,MAAM;AACd,IAAA,IAAI,OAAA,CAAQ,GAAA,CAAI,QAAA,KAAa,aAAA,IAAiB,WAAA,EAAa;AACzD,MAAA,OAAA,CAAQ,IAAA;AAAA,QACN;AAAA,OAEF;AAAA,IACF;AAAA,EACF,CAAA,EAAG,CAAC,WAAW,CAAC,CAAA;AAIhB,EAAA,eAAA,CAAgB,kBAAA,IAAsB,WAAA,EAAa,OAAA,IAAW,sBAAsB,CAAA;AAEpF,EAAA,OAAO;AAAA,IACL,UAAA,EAAY;AAAA,GACd;AACF","file":"index.cjs","sourcesContent":["/**\n * Resolves a condition value (boolean or function returning boolean)\n *\n * @param condition - Boolean value or function\n * @returns Resolved boolean value\n */\nexport function resolveCondition(condition: boolean | (() => boolean)): boolean {\n return typeof condition === \"function\" ? condition() : condition;\n}\n\ninterface Thenable {\n then: (...args: Array<unknown>) => unknown;\n}\n\nconst hasThen = (value: unknown): value is Thenable =>\n typeof value === \"object\" && value !== null && \"then\" in value;\n\n/**\n * Checks if a value behaves like a Promise (thenable)\n */\nexport function isThenable<T>(value: unknown): value is PromiseLike<T> {\n if (!hasThen(value)) {\n return false;\n }\n return typeof value.then === \"function\";\n}\n\nexport interface ConfirmResultSync {\n kind: \"sync\";\n confirmed: boolean;\n}\n\nexport interface ConfirmResultAsync {\n kind: \"async\";\n promise: Promise<boolean>;\n}\n\nexport type ConfirmResult = ConfirmResultSync | ConfirmResultAsync;\n\n/**\n * Normalizes custom confirm result into sync or async branch.\n */\nexport function resolveConfirmResult(\n message: string,\n onConfirm: ((message: string) => boolean | PromiseLike<boolean>) | undefined,\n fallbackConfirm: (message: string) => boolean\n): ConfirmResult {\n if (!onConfirm) {\n return { kind: \"sync\", confirmed: fallbackConfirm(message) };\n }\n\n const result = onConfirm(message);\n if (isThenable<boolean>(result)) {\n return { kind: \"async\", promise: Promise.resolve(result) };\n }\n\n return { kind: \"sync\", confirmed: result };\n}\n\n/**\n * Generates a unique blocker ID based on scope and timestamp\n *\n * @param prefix - Prefix for the ID\n * @param scope - Optional scope\n * @returns Unique blocker ID\n */\nexport function createBlockerId(prefix: string, scope?: string | Array<string>): string {\n const scopePart = scope ? `-${Array.isArray(scope) ? scope.join(\"-\") : scope}` : \"\";\n const timestamp = String(Date.now());\n return `${prefix}${scopePart}-${timestamp}`;\n}\n\n/**\n * Checks if a value is defined and not empty\n *\n * @param value - Value to check\n * @returns True if value is defined and not empty\n */\nexport function isDefined<T>(value: T | undefined | null): value is T {\n return value !== undefined && value !== null;\n}\n\n/**\n * Normalizes scope to an array\n *\n * @param scope - String or array of strings\n * @returns Array of scope strings\n */\nexport function normalizeScope(scope: string | Array<string> | undefined): Array<string> {\n if (!scope) {\n return [];\n }\n return Array.isArray(scope) ? scope : [scope];\n}\n","import { useEffect } from \"react\";\nimport { resolveCondition } from \"./utils\";\n\n/**\n * Default message shown when preventing browser unload\n */\nexport const DEFAULT_UNLOAD_MESSAGE = \"Changes you made may not be saved.\";\n\n/**\n * Blocks browser tab close/refresh when condition is met.\n *\n * This hook adds a `beforeunload` event listener to warn users\n * before they close or refresh the browser tab. Modern browsers\n * may ignore custom messages and show their own generic warning.\n *\n * @param when - Boolean or function returning boolean to determine if blocking should be active\n * @param message - Optional custom message (may be ignored by browsers)\n *\n * @example\n * ```tsx\n * function MyForm() {\n * const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);\n *\n * useBeforeUnload(hasUnsavedChanges, 'You have unsaved changes');\n *\n * return <form>...</form>;\n * }\n * ```\n *\n * @example\n * ```tsx\n * // With function condition\n * function EditPage() {\n * const isFormDirty = useIsBlocked('form');\n *\n * useBeforeUnload(() => isFormDirty);\n *\n * return <div>...</div>;\n * }\n * ```\n */\nexport function useBeforeUnload(\n when: boolean | (() => boolean),\n message = DEFAULT_UNLOAD_MESSAGE\n): void {\n useEffect(() => {\n const shouldBlock = resolveCondition(when);\n\n if (!shouldBlock) {\n return;\n }\n\n const handleBeforeUnload = (event: BeforeUnloadEvent): void => {\n // Prevent default to trigger the browser's confirmation dialog\n event.preventDefault();\n\n // Fallback for legacy browsers/WebViews that still rely on returnValue.\n if (\"returnValue\" in event) {\n // eslint-disable-next-line @typescript-eslint/no-deprecated\n event.returnValue = message;\n }\n };\n\n window.addEventListener(\"beforeunload\", handleBeforeUnload);\n\n return () => {\n window.removeEventListener(\"beforeunload\", handleBeforeUnload);\n };\n }, [when, message]);\n}\n","import { useIsBlocked } from \"@okyrychenko-dev/react-action-guard\";\nimport { useEffect, useMemo, useRef } from \"react\";\nimport { isDefined, normalizeScope, resolveCondition } from \"./utils\";\n\n/**\n * Shared hook to determine if blocking should be active based on\n * condition and/or scope state.\n *\n * This hook uses `useMemo` for optimal performance, ensuring blocking state\n * is computed synchronously without additional re-renders.\n *\n * @param when - Optional condition (boolean or function)\n * @param scope - Optional scope(s) to check\n * @returns Whether blocking should be active\n *\n * @internal\n */\nexport function useShouldBlock(\n when?: boolean | (() => boolean),\n scope?: string | Array<string>\n): boolean {\n // Memoize scope normalization to avoid recalculation on every render\n const scopes = useMemo(() => normalizeScope(scope), [scope]);\n\n // Check if any specified scopes are blocked\n const isScopeBlocked = useIsBlocked(scopes.length === 1 ? scopes[0] : scopes);\n\n // Development-only validation\n const warnedMissingConditionRef = useRef(false);\n const warnedFunctionRef = useRef(false);\n\n useEffect(() => {\n if (process.env.NODE_ENV !== \"development\") {\n return;\n }\n\n if (!warnedMissingConditionRef.current && !isDefined(when) && !scope) {\n warnedMissingConditionRef.current = true;\n console.warn(\n '[react-action-guard-router] useShouldBlock: Neither \"when\" nor \"scope\" provided. ' +\n \"This hook will always return false. Please provide at least one condition.\"\n );\n }\n\n if (!warnedFunctionRef.current && typeof when === \"function\") {\n warnedFunctionRef.current = true;\n console.warn(\n '[react-action-guard-router] useShouldBlock: \"when\" is a function. ' +\n \"Make sure to wrap it with useCallback to avoid unnecessary re-computations.\"\n );\n }\n }, [when, scope]);\n\n // Compute blocking state synchronously using useMemo\n // This avoids the useState + useEffect pattern which causes an extra render\n const shouldBlock = useMemo(() => {\n let blockCondition = false;\n\n // Check manual condition\n if (isDefined(when)) {\n blockCondition = resolveCondition(when);\n }\n\n // Check scope-based blocking (OR logic - block if either condition is true)\n if (scope && isScopeBlocked) {\n blockCondition = true;\n }\n\n return blockCondition;\n }, [when, scope, isScopeBlocked]);\n\n return shouldBlock;\n}\n","/**\n * Error messages for route blocking\n */\nexport const ROUTE_ERRORS = {\n /** Route change was aborted by the user */\n ABORTED: \"Route change aborted by user\",\n /** Route change was blocked */\n BLOCKED: \"Route change blocked\",\n} as const;\n","import { useRouter } from \"next/router\";\nimport { useEffect, useRef } from \"react\";\nimport {\n DEFAULT_UNLOAD_MESSAGE,\n ROUTE_ERRORS,\n resolveConfirmResult,\n useBeforeUnload,\n useShouldBlock,\n} from \"../core\";\nimport type { NavigationBlockerReturn } from \"../core/types\";\nimport type { UseNavigationBlockerOptions } from \"./types\";\n\n/**\n * Blocks navigation in Next.js Pages Router applications.\n *\n * This hook integrates with Next.js Pages Router's route change events and\n * react-action-guard's scope system to prevent navigation when certain conditions\n * are met or when specific scopes are blocked.\n *\n * **Note:** This hook ONLY works with Next.js Pages Router (pages/ directory).\n * For App Router, use the App Router adapter instead.\n *\n * **Features:**\n * - Block navigation based on boolean condition or function\n * - Automatically block when react-action-guard scopes are active\n * - Support for browser `beforeunload` event (tab close/refresh)\n * - Customizable confirmation dialog\n * - Callbacks for block/allow events\n *\n * **Custom confirm note:**\n * Async `onConfirm` is supported, but Pages Router requires a re-attempted\n * navigation after confirmation (via `router.push(url)` with default options).\n *\n * ⚠️ **Limitation:** When using async `onConfirm`, the re-attempted navigation\n * uses default options. Original `as`, `shallow`, `locale`, and `scroll` params\n * may be lost because Next.js Pages Router does not expose these in\n * the `routeChangeStart` event. For precise control, use synchronous confirmations.\n *\n * @param options - Configuration options\n * @returns Object with `isBlocking` state\n *\n * @example\n * ```tsx\n * // pages/edit.tsx\n * function EditPage() {\n * const [hasChanges, setHasChanges] = useState(false);\n *\n * useNavigationBlocker({\n * when: hasChanges,\n * message: 'You have unsaved changes. Leave anyway?',\n * });\n *\n * return <form>...</form>;\n * }\n * ```\n *\n * @example\n * ```tsx\n * // Block based on scope\n * function CheckoutFlow() {\n * useNavigationBlocker({\n * scope: 'checkout',\n * message: 'Your order is being processed. Please wait.',\n * });\n * }\n * ```\n */\nexport function useNavigationBlocker(\n options: UseNavigationBlockerOptions\n): NavigationBlockerReturn {\n const { when, scope, message, onBlock, onAllow, blockBrowserUnload = true, onConfirm } = options;\n\n const router = useRouter();\n const allowNextUrlRef = useRef<string | null>(null);\n\n // Use shared logic to determine if blocking should be active\n const shouldBlock = useShouldBlock(when, scope);\n\n // Block navigation using Next.js router events\n useEffect(() => {\n if (!shouldBlock) {\n return;\n }\n\n const handleRouteChangeStart = (url: string): void => {\n // Early return for allowed URL\n if (allowNextUrlRef.current === url) {\n allowNextUrlRef.current = null;\n onAllow?.();\n return;\n }\n\n // Trigger onBlock callback\n onBlock?.();\n\n // If no message, block silently\n if (!message) {\n router.events.emit(\"routeChangeError\");\n throw new Error(ROUTE_ERRORS.BLOCKED);\n }\n\n const confirmation = resolveConfirmResult(message, onConfirm, (value) =>\n window.confirm(value)\n );\n\n if (confirmation.kind === \"sync\" && !confirmation.confirmed) {\n router.events.emit(\"routeChangeError\");\n throw new Error(ROUTE_ERRORS.ABORTED);\n }\n\n if (confirmation.kind === \"sync\") {\n onAllow?.();\n return;\n }\n\n router.events.emit(\"routeChangeError\");\n confirmation.promise\n .then((confirmed) => {\n if (confirmed) {\n allowNextUrlRef.current = url;\n onAllow?.();\n void router.push(url);\n }\n })\n .catch(() => {\n // On error, treat as cancelled\n });\n throw new Error(ROUTE_ERRORS.ABORTED);\n };\n\n router.events.on(\"routeChangeStart\", handleRouteChangeStart);\n\n return () => {\n router.events.off(\"routeChangeStart\", handleRouteChangeStart);\n };\n }, [shouldBlock, message, onBlock, onAllow, router, onConfirm]);\n\n // Also block browser unload if requested\n useBeforeUnload(blockBrowserUnload && shouldBlock, message ?? DEFAULT_UNLOAD_MESSAGE);\n\n return {\n isBlocking: shouldBlock,\n };\n}\n","import { useEffect } from \"react\";\nimport { DEFAULT_UNLOAD_MESSAGE, useBeforeUnload, useShouldBlock } from \"../core\";\nimport type { NavigationBlockerReturn } from \"../core/types\";\nimport type { UseNavigationBlockerOptions } from \"./types\";\n\n/**\n * Blocks navigation in Next.js App Router applications.\n *\n * **⚠️ IMPORTANT LIMITATION:**\n * Next.js App Router (app/ directory) does not currently provide an official API\n * for blocking navigation. This implementation provides best-effort blocking using\n * available mechanisms, but has limitations:\n *\n * - ✅ Browser back/forward buttons are blocked via `beforeunload`\n * - ✅ Tab close/refresh is blocked via `beforeunload`\n * - ❌ Next.js `<Link>` components are NOT blocked\n * - ❌ Programmatic `router.push()` is NOT blocked\n * - ❌ Browser address bar navigation is NOT fully blocked\n *\n * For production use with full blocking capabilities, consider using Pages Router\n * or wait for official Next.js App Router blocking API.\n *\n * @param options - Configuration options\n * @returns Object with `isBlocking` state\n *\n * @example\n * ```tsx\n * // app/edit/page.tsx\n * 'use client';\n *\n * function EditPage() {\n * const [hasChanges, setHasChanges] = useState(false);\n *\n * useNavigationBlocker({\n * when: hasChanges,\n * message: 'You have unsaved changes.',\n * });\n *\n * return <form>...</form>;\n * }\n * ```\n *\n * @example\n * ```tsx\n * // Block based on scope\n * 'use client';\n *\n * function CheckoutFlow() {\n * useNavigationBlocker({\n * scope: 'checkout',\n * message: 'Your order is being processed.',\n * });\n * }\n * ```\n */\nexport function useNavigationBlocker(\n options: UseNavigationBlockerOptions\n): NavigationBlockerReturn {\n const { when, scope, message, blockBrowserUnload = true } = options;\n\n // Use shared logic to determine if blocking should be active\n const shouldBlock = useShouldBlock(when, scope);\n\n // Log warning in development\n useEffect(() => {\n if (process.env.NODE_ENV === \"development\" && shouldBlock) {\n console.warn(\n \"[react-action-guard-router] App Router has limited blocking support. \" +\n \"Link clicks cannot be blocked. Use Pages Router for full support.\"\n );\n }\n }, [shouldBlock]);\n\n // Best effort: Block browser navigation via beforeunload\n // This will prevent tab close, refresh, and some browser back/forward\n useBeforeUnload(blockBrowserUnload && shouldBlock, message ?? DEFAULT_UNLOAD_MESSAGE);\n\n return {\n isBlocking: shouldBlock,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/core/utils.ts","../../src/core/useBeforeUnload.ts","../../src/core/useShouldBlock.ts","../../src/core/constants.ts","../../src/core/confirmationOwner.utils.ts","../../src/nextjs/usePagesRouterBlocker.ts","../../src/nextjs/useAppRouterBlocker.ts"],"names":["isFunction","isObject","isArray","useEffect","useMemo","useIsBlocked","useRef","isDefined","useRouter","useInsertionEffect","onBlock","onAllow","onConfirm","useNavigationBlocker"],"mappings":";;;;;;;;AASO,SAAS,iBAAiB,SAAA,EAA+C;AAC9E,EAAA,OAAOA,oBAAA,CAAW,SAAS,CAAA,GAAI,SAAA,EAAU,GAAI,SAAA;AAC/C;AAMA,IAAM,UAAU,CAAC,KAAA,KAAsCC,kBAAA,CAAS,KAAK,KAAK,MAAA,IAAU,KAAA;AAK7E,SAAS,WAAc,KAAA,EAAyC;AACrE,EAAA,IAAI,CAAC,OAAA,CAAQ,KAAK,CAAA,EAAG;AACnB,IAAA,OAAO,KAAA;AAAA,EACT;AAEA,EAAA,OAAOD,oBAAA,CAAW,MAAM,IAAI,CAAA;AAC9B;AAiBO,SAAS,oBAAA,CACd,OAAA,EACA,SAAA,EACA,eAAA,EACe;AACf,EAAA,IAAI,CAAC,SAAA,EAAW;AACd,IAAA,OAAO,EAAE,IAAA,EAAM,MAAA,EAAQ,SAAA,EAAW,eAAA,CAAgB,OAAO,CAAA,EAAE;AAAA,EAC7D;AAEA,EAAA,MAAM,MAAA,GAAS,UAAU,OAAO,CAAA;AAEhC,EAAA,IAAI,UAAA,CAAoB,MAAM,CAAA,EAAG;AAC/B,IAAA,OAAO,EAAE,IAAA,EAAM,OAAA,EAAS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AAG5D,EAAA,MAAM,WAAA,GAAc,cAAA,CAAe,IAAA,EAAM,KAAK,CAAA;AAG9C,EAAAV,gBAAU,MAAM;AACd,IAAA,IAAI,OAAA,CAAQ,GAAA,CAAI,QAAA,KAAa,aAAA,IAAiB,WAAA,EAAa;AACzD,MAAA,OAAA,CAAQ,IAAA;AAAA,QACN;AAAA,OAEF;AAAA,IACF;AAAA,EACF,CAAA,EAAG,CAAC,WAAW,CAAC,CAAA;AAIhB,EAAA,eAAA,CAAgB,kBAAA,IAAsB,WAAA,EAAa,OAAA,IAAW,sBAAsB,CAAA;AAEpF,EAAA,OAAO;AAAA,IACL,UAAA,EAAY;AAAA,GACd;AACF","file":"index.cjs","sourcesContent":["import { isArray, isFunction, isObject } from \"@okyrychenko-dev/type-utils\";\nimport type { Optional } from \"@okyrychenko-dev/type-utils\";\n\n/**\n * Resolves a condition value (boolean or function returning boolean)\n *\n * @param condition - Boolean value or function\n * @returns Resolved boolean value\n */\nexport function resolveCondition(condition: boolean | (() => boolean)): boolean {\n return isFunction(condition) ? condition() : condition;\n}\n\ninterface Thenable {\n then: (...args: Array<unknown>) => unknown;\n}\n\nconst hasThen = (value: unknown): value is Thenable => isObject(value) && \"then\" in value;\n\n/**\n * Checks if a value behaves like a Promise (thenable)\n */\nexport function isThenable<T>(value: unknown): value is PromiseLike<T> {\n if (!hasThen(value)) {\n return false;\n }\n\n return isFunction(value.then);\n}\n\nexport interface ConfirmResultSync {\n kind: \"sync\";\n confirmed: boolean;\n}\n\nexport interface ConfirmResultAsync {\n kind: \"async\";\n promise: Promise<boolean>;\n}\n\nexport type ConfirmResult = ConfirmResultSync | ConfirmResultAsync;\n\n/**\n * Normalizes custom confirm result into sync or async branch.\n */\nexport function resolveConfirmResult(\n message: string,\n onConfirm: Optional<(message: string) => boolean | PromiseLike<boolean>>,\n fallbackConfirm: (message: string) => boolean\n): ConfirmResult {\n if (!onConfirm) {\n return { kind: \"sync\", confirmed: fallbackConfirm(message) };\n }\n\n const result = onConfirm(message);\n\n if (isThenable<boolean>(result)) {\n return { kind: \"async\", promise: Promise.resolve(result) };\n }\n\n return { kind: \"sync\", confirmed: result };\n}\n\n/**\n * Generates a unique blocker ID based on scope and timestamp\n *\n * @param prefix - Prefix for the ID\n * @param scope - Optional scope\n * @returns Unique blocker ID\n */\nexport function createBlockerId(prefix: string, scope?: string | Array<string>): string {\n const scopePart = scope ? `-${isArray(scope) ? scope.join(\"-\") : scope}` : \"\";\n const timestamp = String(Date.now());\n\n return `${prefix}${scopePart}-${timestamp}`;\n}\n\n/**\n * Checks if a value is defined and not empty\n *\n * @param value - Value to check\n * @returns True if value is defined and not empty\n */\nexport { isDefined } from \"@okyrychenko-dev/type-utils\";\n\n/**\n * Normalizes scope to an array\n *\n * @param scope - String or array of strings\n * @returns Array of scope strings\n */\nexport function normalizeScope(scope: Optional<string | Array<string>>): Array<string> {\n if (!scope) {\n return [];\n }\n\n return isArray(scope) ? scope : [scope];\n}\n\n/** Identifies protection independently of scope order and duplicate entries. */\nexport function createScopeKey(scope: Optional<string | Array<string>>): string {\n return JSON.stringify([...new Set(normalizeScope(scope))].sort());\n}\n","import { useEffect } from \"react\";\nimport { resolveCondition } from \"./utils\";\n\n/**\n * Default message shown when preventing browser unload\n */\nexport const DEFAULT_UNLOAD_MESSAGE = \"Changes you made may not be saved.\";\n\n/**\n * Blocks browser tab close/refresh when condition is met.\n */\nexport function useBeforeUnload(\n when: boolean | (() => boolean),\n message = DEFAULT_UNLOAD_MESSAGE\n): void {\n useEffect(() => {\n const shouldBlock = resolveCondition(when);\n\n if (!shouldBlock) {\n return;\n }\n\n const handleBeforeUnload = (event: BeforeUnloadEvent): void => {\n // Prevent default to trigger the browser's confirmation dialog\n event.preventDefault();\n\n // Fallback for legacy browsers/WebViews that still rely on returnValue.\n if (\"returnValue\" in event) {\n // eslint-disable-next-line @typescript-eslint/no-deprecated\n event.returnValue = message;\n }\n };\n\n window.addEventListener(\"beforeunload\", handleBeforeUnload);\n\n return () => {\n window.removeEventListener(\"beforeunload\", handleBeforeUnload);\n };\n }, [when, message]);\n}\n","import { useIsBlocked } from \"@okyrychenko-dev/react-action-guard\";\nimport { isDefined } from \"@okyrychenko-dev/type-utils\";\nimport { useEffect, useMemo, useRef } from \"react\";\nimport { normalizeScope, resolveCondition } from \"./utils\";\n\n/**\n * Shared hook to determine if blocking should be active based on\n * condition and/or scope state.\n *\n * Pure function conditions are evaluated synchronously on every render.\n * Mutating a ref alone does not trigger a render.\n *\n * @param when - Optional condition (boolean or function)\n * @param scope - Optional scope(s) to check\n * @returns Whether blocking should be active\n *\n * @internal\n */\nexport function useShouldBlock(\n when?: boolean | (() => boolean),\n scope?: string | Array<string>\n): boolean {\n // Memoize scope normalization to avoid recalculation on every render\n const scopes = useMemo(() => normalizeScope(scope), [scope]);\n\n // Check if any specified scopes are blocked\n const isScopeBlocked = useIsBlocked(scopes.length === 1 ? scopes[0] : scopes);\n\n // Development-only validation\n const warnedMissingConditionRef = useRef(false);\n\n useEffect(() => {\n if (process.env.NODE_ENV !== \"development\") {\n return;\n }\n\n if (!warnedMissingConditionRef.current && !isDefined(when) && !scope) {\n warnedMissingConditionRef.current = true;\n console.warn(\n '[react-action-guard-router] useShouldBlock: Neither \"when\" nor \"scope\" provided. ' +\n \"This hook will always return false. Please provide at least one condition.\"\n );\n }\n }, [when, scope]);\n\n const blockCondition = isDefined(when) && resolveCondition(when);\n\n return blockCondition || Boolean(scope && isScopeBlocked);\n}\n","/**\n * Error messages for route blocking\n */\nexport const ROUTE_ERRORS = {\n /** Route change was aborted by the user */\n ABORTED: \"Route change aborted by user\",\n /** Route change was blocked */\n BLOCKED: \"Route change blocked\",\n} as const;\n","import type { ConfirmationOwner } from \"./confirmationOwner.types\";\n\nexport function createConfirmationOwner(): ConfirmationOwner {\n let currentAttempt = 0;\n\n function invalidate(): void {\n currentAttempt += 1;\n }\n\n function begin(): () => boolean {\n const attempt = ++currentAttempt;\n\n function settle(): boolean {\n if (attempt !== currentAttempt) {\n return false;\n }\n invalidate();\n\n return true;\n }\n\n return settle;\n }\n\n return { begin, invalidate };\n}\n","import { useRouter } from \"next/router.js\";\nimport { useInsertionEffect, useRef } from \"react\";\nimport {\n DEFAULT_UNLOAD_MESSAGE,\n ROUTE_ERRORS,\n createConfirmationOwner,\n createScopeKey,\n resolveConfirmResult,\n useBeforeUnload,\n useShouldBlock,\n} from \"../core\";\nimport type { Nullable } from \"@okyrychenko-dev/type-utils\";\nimport type { NavigationBlockerReturn } from \"../core\";\nimport type { UseNavigationBlockerOptions } from \"./types\";\n\n/**\n * Blocks navigation in Next.js Pages Router applications.\n */\nexport function useNavigationBlocker(\n options: UseNavigationBlockerOptions\n): NavigationBlockerReturn {\n const { when, scope, message, onBlock, onAllow, blockBrowserUnload = true, onConfirm } = options;\n\n const router = useRouter();\n const callbacksRef = useRef({ onBlock, onAllow, onConfirm });\n\n // Publish committed callbacks before any component can navigate from a layout effect.\n // Callback identity changes do not replace the protected navigation attempt.\n useInsertionEffect(() => {\n callbacksRef.current = { onBlock, onAllow, onConfirm };\n }, [onBlock, onAllow, onConfirm]);\n\n // Use shared logic to determine if blocking should be active\n const shouldBlock = useShouldBlock(when, scope);\n\n const scopeKey = createScopeKey(scope);\n\n // Replace protection and its listener before layout-triggered navigation can run.\n useInsertionEffect(() => {\n if (!shouldBlock) {\n return;\n }\n\n const confirmationOwner = createConfirmationOwner();\n let allowedNavigation: Nullable<{ url: string }> = null;\n let currentAttempt: Nullable<() => boolean> = null;\n\n function handleRouteChangeStart(url: string): void {\n // Early return for allowed URL\n if (allowedNavigation?.url === url) {\n allowedNavigation = null;\n\n return;\n }\n\n allowedNavigation = null;\n\n const settle = confirmationOwner.begin();\n\n currentAttempt = settle;\n\n const { onBlock, onAllow, onConfirm } = callbacksRef.current;\n\n // Trigger onBlock callback\n onBlock?.();\n\n // If no message, block silently\n if (!message) {\n router.events.emit(\"routeChangeError\");\n throw new Error(ROUTE_ERRORS.BLOCKED);\n }\n\n const confirmation = resolveConfirmResult(message, onConfirm, (value) =>\n window.confirm(value)\n );\n\n if (confirmation.kind === \"sync\" && !confirmation.confirmed) {\n router.events.emit(\"routeChangeError\");\n throw new Error(ROUTE_ERRORS.ABORTED);\n }\n\n if (confirmation.kind === \"sync\") {\n if (!settle()) {\n router.events.emit(\"routeChangeError\");\n throw new Error(ROUTE_ERRORS.ABORTED);\n }\n\n onAllow?.();\n\n if (currentAttempt !== settle) {\n router.events.emit(\"routeChangeError\");\n throw new Error(ROUTE_ERRORS.ABORTED);\n }\n\n return;\n }\n\n router.events.emit(\"routeChangeError\");\n async function complete(confirmed: boolean): Promise<void> {\n if (!settle() || !confirmed) {\n return;\n }\n\n const permission = { url };\n\n allowedNavigation = permission;\n\n const { onAllow: notifyAllow } = callbacksRef.current;\n\n try {\n notifyAllow?.();\n\n // User callbacks can replace the attempt or detach this listener synchronously.\n if (allowedNavigation !== permission) {\n return;\n }\n\n await router.push(url);\n } finally {\n if (allowedNavigation === permission) {\n allowedNavigation = null;\n }\n }\n }\n\n // Treat confirmation, callback and retry failures as cancellation.\n void confirmation.promise.then(complete).catch(() => complete(false));\n throw new Error(ROUTE_ERRORS.ABORTED);\n }\n\n router.events.on(\"routeChangeStart\", handleRouteChangeStart);\n\n return () => {\n confirmationOwner.invalidate();\n currentAttempt = null;\n allowedNavigation = null;\n router.events.off(\"routeChangeStart\", handleRouteChangeStart);\n };\n }, [shouldBlock, scopeKey, message, router]);\n\n // Also block browser unload if requested\n useBeforeUnload(blockBrowserUnload && shouldBlock, message ?? DEFAULT_UNLOAD_MESSAGE);\n\n return {\n isBlocking: shouldBlock,\n };\n}\n","import { useEffect } from \"react\";\nimport { DEFAULT_UNLOAD_MESSAGE, useBeforeUnload, useShouldBlock } from \"../core\";\nimport type { NavigationBlockerReturn } from \"../core\";\nimport type { UseNavigationBlockerOptions } from \"./types\";\n\n/**\n * Blocks navigation in Next.js App Router applications.\n */\nexport function useNavigationBlocker(\n options: UseNavigationBlockerOptions\n): NavigationBlockerReturn {\n const { when, scope, message, blockBrowserUnload = true } = options;\n\n // Use shared logic to determine if blocking should be active\n const shouldBlock = useShouldBlock(when, scope);\n\n // Log warning in development\n useEffect(() => {\n if (process.env.NODE_ENV === \"development\" && shouldBlock) {\n console.warn(\n \"[react-action-guard-router] App Router has limited blocking support. \" +\n \"Link clicks cannot be blocked. Use Pages Router for full support.\"\n );\n }\n }, [shouldBlock]);\n\n // Request a native prompt on document unload, subject to browser policy.\n // Same-document App Router back/forward does not trigger beforeunload.\n useBeforeUnload(blockBrowserUnload && shouldBlock, message ?? DEFAULT_UNLOAD_MESSAGE);\n\n return {\n isBlocking: shouldBlock,\n };\n}\n"]}
|
package/dist/nextjs/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { B as BaseNavigationBlockerOptions, N as NavigationBlockerReturn } from '../types-
|
|
1
|
+
import { B as BaseNavigationBlockerOptions, N as NavigationBlockerReturn } from '../types-xxRwsJ1N.cjs';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Options for Next.js navigation blocker
|
|
@@ -10,110 +10,11 @@ type UseNavigationBlockerOptions = BaseNavigationBlockerOptions;
|
|
|
10
10
|
|
|
11
11
|
/**
|
|
12
12
|
* Blocks navigation in Next.js Pages Router applications.
|
|
13
|
-
*
|
|
14
|
-
* This hook integrates with Next.js Pages Router's route change events and
|
|
15
|
-
* react-action-guard's scope system to prevent navigation when certain conditions
|
|
16
|
-
* are met or when specific scopes are blocked.
|
|
17
|
-
*
|
|
18
|
-
* **Note:** This hook ONLY works with Next.js Pages Router (pages/ directory).
|
|
19
|
-
* For App Router, use the App Router adapter instead.
|
|
20
|
-
*
|
|
21
|
-
* **Features:**
|
|
22
|
-
* - Block navigation based on boolean condition or function
|
|
23
|
-
* - Automatically block when react-action-guard scopes are active
|
|
24
|
-
* - Support for browser `beforeunload` event (tab close/refresh)
|
|
25
|
-
* - Customizable confirmation dialog
|
|
26
|
-
* - Callbacks for block/allow events
|
|
27
|
-
*
|
|
28
|
-
* **Custom confirm note:**
|
|
29
|
-
* Async `onConfirm` is supported, but Pages Router requires a re-attempted
|
|
30
|
-
* navigation after confirmation (via `router.push(url)` with default options).
|
|
31
|
-
*
|
|
32
|
-
* ⚠️ **Limitation:** When using async `onConfirm`, the re-attempted navigation
|
|
33
|
-
* uses default options. Original `as`, `shallow`, `locale`, and `scroll` params
|
|
34
|
-
* may be lost because Next.js Pages Router does not expose these in
|
|
35
|
-
* the `routeChangeStart` event. For precise control, use synchronous confirmations.
|
|
36
|
-
*
|
|
37
|
-
* @param options - Configuration options
|
|
38
|
-
* @returns Object with `isBlocking` state
|
|
39
|
-
*
|
|
40
|
-
* @example
|
|
41
|
-
* ```tsx
|
|
42
|
-
* // pages/edit.tsx
|
|
43
|
-
* function EditPage() {
|
|
44
|
-
* const [hasChanges, setHasChanges] = useState(false);
|
|
45
|
-
*
|
|
46
|
-
* useNavigationBlocker({
|
|
47
|
-
* when: hasChanges,
|
|
48
|
-
* message: 'You have unsaved changes. Leave anyway?',
|
|
49
|
-
* });
|
|
50
|
-
*
|
|
51
|
-
* return <form>...</form>;
|
|
52
|
-
* }
|
|
53
|
-
* ```
|
|
54
|
-
*
|
|
55
|
-
* @example
|
|
56
|
-
* ```tsx
|
|
57
|
-
* // Block based on scope
|
|
58
|
-
* function CheckoutFlow() {
|
|
59
|
-
* useNavigationBlocker({
|
|
60
|
-
* scope: 'checkout',
|
|
61
|
-
* message: 'Your order is being processed. Please wait.',
|
|
62
|
-
* });
|
|
63
|
-
* }
|
|
64
|
-
* ```
|
|
65
13
|
*/
|
|
66
14
|
declare function useNavigationBlocker$1(options: UseNavigationBlockerOptions): NavigationBlockerReturn;
|
|
67
15
|
|
|
68
16
|
/**
|
|
69
17
|
* Blocks navigation in Next.js App Router applications.
|
|
70
|
-
*
|
|
71
|
-
* **⚠️ IMPORTANT LIMITATION:**
|
|
72
|
-
* Next.js App Router (app/ directory) does not currently provide an official API
|
|
73
|
-
* for blocking navigation. This implementation provides best-effort blocking using
|
|
74
|
-
* available mechanisms, but has limitations:
|
|
75
|
-
*
|
|
76
|
-
* - ✅ Browser back/forward buttons are blocked via `beforeunload`
|
|
77
|
-
* - ✅ Tab close/refresh is blocked via `beforeunload`
|
|
78
|
-
* - ❌ Next.js `<Link>` components are NOT blocked
|
|
79
|
-
* - ❌ Programmatic `router.push()` is NOT blocked
|
|
80
|
-
* - ❌ Browser address bar navigation is NOT fully blocked
|
|
81
|
-
*
|
|
82
|
-
* For production use with full blocking capabilities, consider using Pages Router
|
|
83
|
-
* or wait for official Next.js App Router blocking API.
|
|
84
|
-
*
|
|
85
|
-
* @param options - Configuration options
|
|
86
|
-
* @returns Object with `isBlocking` state
|
|
87
|
-
*
|
|
88
|
-
* @example
|
|
89
|
-
* ```tsx
|
|
90
|
-
* // app/edit/page.tsx
|
|
91
|
-
* 'use client';
|
|
92
|
-
*
|
|
93
|
-
* function EditPage() {
|
|
94
|
-
* const [hasChanges, setHasChanges] = useState(false);
|
|
95
|
-
*
|
|
96
|
-
* useNavigationBlocker({
|
|
97
|
-
* when: hasChanges,
|
|
98
|
-
* message: 'You have unsaved changes.',
|
|
99
|
-
* });
|
|
100
|
-
*
|
|
101
|
-
* return <form>...</form>;
|
|
102
|
-
* }
|
|
103
|
-
* ```
|
|
104
|
-
*
|
|
105
|
-
* @example
|
|
106
|
-
* ```tsx
|
|
107
|
-
* // Block based on scope
|
|
108
|
-
* 'use client';
|
|
109
|
-
*
|
|
110
|
-
* function CheckoutFlow() {
|
|
111
|
-
* useNavigationBlocker({
|
|
112
|
-
* scope: 'checkout',
|
|
113
|
-
* message: 'Your order is being processed.',
|
|
114
|
-
* });
|
|
115
|
-
* }
|
|
116
|
-
* ```
|
|
117
18
|
*/
|
|
118
19
|
declare function useNavigationBlocker(options: UseNavigationBlockerOptions): NavigationBlockerReturn;
|
|
119
20
|
|
package/dist/nextjs/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { B as BaseNavigationBlockerOptions, N as NavigationBlockerReturn } from '../types-
|
|
1
|
+
import { B as BaseNavigationBlockerOptions, N as NavigationBlockerReturn } from '../types-xxRwsJ1N.js';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Options for Next.js navigation blocker
|
|
@@ -10,110 +10,11 @@ type UseNavigationBlockerOptions = BaseNavigationBlockerOptions;
|
|
|
10
10
|
|
|
11
11
|
/**
|
|
12
12
|
* Blocks navigation in Next.js Pages Router applications.
|
|
13
|
-
*
|
|
14
|
-
* This hook integrates with Next.js Pages Router's route change events and
|
|
15
|
-
* react-action-guard's scope system to prevent navigation when certain conditions
|
|
16
|
-
* are met or when specific scopes are blocked.
|
|
17
|
-
*
|
|
18
|
-
* **Note:** This hook ONLY works with Next.js Pages Router (pages/ directory).
|
|
19
|
-
* For App Router, use the App Router adapter instead.
|
|
20
|
-
*
|
|
21
|
-
* **Features:**
|
|
22
|
-
* - Block navigation based on boolean condition or function
|
|
23
|
-
* - Automatically block when react-action-guard scopes are active
|
|
24
|
-
* - Support for browser `beforeunload` event (tab close/refresh)
|
|
25
|
-
* - Customizable confirmation dialog
|
|
26
|
-
* - Callbacks for block/allow events
|
|
27
|
-
*
|
|
28
|
-
* **Custom confirm note:**
|
|
29
|
-
* Async `onConfirm` is supported, but Pages Router requires a re-attempted
|
|
30
|
-
* navigation after confirmation (via `router.push(url)` with default options).
|
|
31
|
-
*
|
|
32
|
-
* ⚠️ **Limitation:** When using async `onConfirm`, the re-attempted navigation
|
|
33
|
-
* uses default options. Original `as`, `shallow`, `locale`, and `scroll` params
|
|
34
|
-
* may be lost because Next.js Pages Router does not expose these in
|
|
35
|
-
* the `routeChangeStart` event. For precise control, use synchronous confirmations.
|
|
36
|
-
*
|
|
37
|
-
* @param options - Configuration options
|
|
38
|
-
* @returns Object with `isBlocking` state
|
|
39
|
-
*
|
|
40
|
-
* @example
|
|
41
|
-
* ```tsx
|
|
42
|
-
* // pages/edit.tsx
|
|
43
|
-
* function EditPage() {
|
|
44
|
-
* const [hasChanges, setHasChanges] = useState(false);
|
|
45
|
-
*
|
|
46
|
-
* useNavigationBlocker({
|
|
47
|
-
* when: hasChanges,
|
|
48
|
-
* message: 'You have unsaved changes. Leave anyway?',
|
|
49
|
-
* });
|
|
50
|
-
*
|
|
51
|
-
* return <form>...</form>;
|
|
52
|
-
* }
|
|
53
|
-
* ```
|
|
54
|
-
*
|
|
55
|
-
* @example
|
|
56
|
-
* ```tsx
|
|
57
|
-
* // Block based on scope
|
|
58
|
-
* function CheckoutFlow() {
|
|
59
|
-
* useNavigationBlocker({
|
|
60
|
-
* scope: 'checkout',
|
|
61
|
-
* message: 'Your order is being processed. Please wait.',
|
|
62
|
-
* });
|
|
63
|
-
* }
|
|
64
|
-
* ```
|
|
65
13
|
*/
|
|
66
14
|
declare function useNavigationBlocker$1(options: UseNavigationBlockerOptions): NavigationBlockerReturn;
|
|
67
15
|
|
|
68
16
|
/**
|
|
69
17
|
* Blocks navigation in Next.js App Router applications.
|
|
70
|
-
*
|
|
71
|
-
* **⚠️ IMPORTANT LIMITATION:**
|
|
72
|
-
* Next.js App Router (app/ directory) does not currently provide an official API
|
|
73
|
-
* for blocking navigation. This implementation provides best-effort blocking using
|
|
74
|
-
* available mechanisms, but has limitations:
|
|
75
|
-
*
|
|
76
|
-
* - ✅ Browser back/forward buttons are blocked via `beforeunload`
|
|
77
|
-
* - ✅ Tab close/refresh is blocked via `beforeunload`
|
|
78
|
-
* - ❌ Next.js `<Link>` components are NOT blocked
|
|
79
|
-
* - ❌ Programmatic `router.push()` is NOT blocked
|
|
80
|
-
* - ❌ Browser address bar navigation is NOT fully blocked
|
|
81
|
-
*
|
|
82
|
-
* For production use with full blocking capabilities, consider using Pages Router
|
|
83
|
-
* or wait for official Next.js App Router blocking API.
|
|
84
|
-
*
|
|
85
|
-
* @param options - Configuration options
|
|
86
|
-
* @returns Object with `isBlocking` state
|
|
87
|
-
*
|
|
88
|
-
* @example
|
|
89
|
-
* ```tsx
|
|
90
|
-
* // app/edit/page.tsx
|
|
91
|
-
* 'use client';
|
|
92
|
-
*
|
|
93
|
-
* function EditPage() {
|
|
94
|
-
* const [hasChanges, setHasChanges] = useState(false);
|
|
95
|
-
*
|
|
96
|
-
* useNavigationBlocker({
|
|
97
|
-
* when: hasChanges,
|
|
98
|
-
* message: 'You have unsaved changes.',
|
|
99
|
-
* });
|
|
100
|
-
*
|
|
101
|
-
* return <form>...</form>;
|
|
102
|
-
* }
|
|
103
|
-
* ```
|
|
104
|
-
*
|
|
105
|
-
* @example
|
|
106
|
-
* ```tsx
|
|
107
|
-
* // Block based on scope
|
|
108
|
-
* 'use client';
|
|
109
|
-
*
|
|
110
|
-
* function CheckoutFlow() {
|
|
111
|
-
* useNavigationBlocker({
|
|
112
|
-
* scope: 'checkout',
|
|
113
|
-
* message: 'Your order is being processed.',
|
|
114
|
-
* });
|
|
115
|
-
* }
|
|
116
|
-
* ```
|
|
117
18
|
*/
|
|
118
19
|
declare function useNavigationBlocker(options: UseNavigationBlockerOptions): NavigationBlockerReturn;
|
|
119
20
|
|