@okyrychenko-dev/react-action-guard-router 0.2.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/LICENSE +21 -0
- package/README.md +519 -0
- package/dist/index.cjs +91 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +158 -0
- package/dist/index.d.ts +158 -0
- package/dist/index.js +84 -0
- package/dist/index.js.map +1 -0
- package/dist/nextjs/index.cjs +178 -0
- package/dist/nextjs/index.cjs.map +1 -0
- package/dist/nextjs/index.d.cts +120 -0
- package/dist/nextjs/index.d.ts +120 -0
- package/dist/nextjs/index.js +174 -0
- package/dist/nextjs/index.js.map +1 -0
- package/dist/react-router/index.cjs +193 -0
- package/dist/react-router/index.cjs.map +1 -0
- package/dist/react-router/index.d.cts +137 -0
- package/dist/react-router/index.d.ts +137 -0
- package/dist/react-router/index.js +189 -0
- package/dist/react-router/index.js.map +1 -0
- package/dist/tanstack-router/index.cjs +172 -0
- package/dist/tanstack-router/index.cjs.map +1 -0
- package/dist/tanstack-router/index.d.cts +75 -0
- package/dist/tanstack-router/index.d.ts +75 -0
- package/dist/tanstack-router/index.js +170 -0
- package/dist/tanstack-router/index.js.map +1 -0
- package/dist/types-C3CPuZip.d.cts +105 -0
- package/dist/types-C3CPuZip.d.ts +105 -0
- package/package.json +139 -0
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var reactRouter = require('@tanstack/react-router');
|
|
4
|
+
var react = require('react');
|
|
5
|
+
var reactActionGuard = require('@okyrychenko-dev/react-action-guard');
|
|
6
|
+
|
|
7
|
+
// src/tanstack-router/useNavigationBlocker.ts
|
|
8
|
+
|
|
9
|
+
// src/core/utils.ts
|
|
10
|
+
function resolveCondition(condition) {
|
|
11
|
+
return typeof condition === "function" ? condition() : condition;
|
|
12
|
+
}
|
|
13
|
+
var hasThen = (value) => typeof value === "object" && value !== null && "then" in value;
|
|
14
|
+
function isThenable(value) {
|
|
15
|
+
if (!hasThen(value)) {
|
|
16
|
+
return false;
|
|
17
|
+
}
|
|
18
|
+
return typeof value.then === "function";
|
|
19
|
+
}
|
|
20
|
+
function resolveConfirmResult(message, onConfirm, fallbackConfirm) {
|
|
21
|
+
if (!onConfirm) {
|
|
22
|
+
return { kind: "sync", confirmed: fallbackConfirm(message) };
|
|
23
|
+
}
|
|
24
|
+
const result = onConfirm(message);
|
|
25
|
+
if (isThenable(result)) {
|
|
26
|
+
return { kind: "async", promise: Promise.resolve(result) };
|
|
27
|
+
}
|
|
28
|
+
return { kind: "sync", confirmed: result };
|
|
29
|
+
}
|
|
30
|
+
function isDefined(value) {
|
|
31
|
+
return value !== void 0 && value !== null;
|
|
32
|
+
}
|
|
33
|
+
function normalizeScope(scope) {
|
|
34
|
+
if (!scope) {
|
|
35
|
+
return [];
|
|
36
|
+
}
|
|
37
|
+
return Array.isArray(scope) ? scope : [scope];
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// src/core/useBeforeUnload.ts
|
|
41
|
+
var DEFAULT_UNLOAD_MESSAGE = "Changes you made may not be saved.";
|
|
42
|
+
function useBeforeUnload(when, message = DEFAULT_UNLOAD_MESSAGE) {
|
|
43
|
+
react.useEffect(() => {
|
|
44
|
+
const shouldBlock = resolveCondition(when);
|
|
45
|
+
if (!shouldBlock) {
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
const handleBeforeUnload = (event) => {
|
|
49
|
+
event.preventDefault();
|
|
50
|
+
if ("returnValue" in event) {
|
|
51
|
+
event.returnValue = message;
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
window.addEventListener("beforeunload", handleBeforeUnload);
|
|
55
|
+
return () => {
|
|
56
|
+
window.removeEventListener("beforeunload", handleBeforeUnload);
|
|
57
|
+
};
|
|
58
|
+
}, [when, message]);
|
|
59
|
+
}
|
|
60
|
+
function useShouldBlock(when, scope) {
|
|
61
|
+
const scopes = react.useMemo(() => normalizeScope(scope), [scope]);
|
|
62
|
+
const isScopeBlocked = reactActionGuard.useIsBlocked(scopes.length === 1 ? scopes[0] : scopes);
|
|
63
|
+
const warnedMissingConditionRef = react.useRef(false);
|
|
64
|
+
const warnedFunctionRef = react.useRef(false);
|
|
65
|
+
react.useEffect(() => {
|
|
66
|
+
if (process.env.NODE_ENV !== "development") {
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
if (!warnedMissingConditionRef.current && !isDefined(when) && !scope) {
|
|
70
|
+
warnedMissingConditionRef.current = true;
|
|
71
|
+
console.warn(
|
|
72
|
+
'[react-action-guard-router] useShouldBlock: Neither "when" nor "scope" provided. This hook will always return false. Please provide at least one condition.'
|
|
73
|
+
);
|
|
74
|
+
}
|
|
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
|
+
}, [when, scope]);
|
|
82
|
+
const shouldBlock = react.useMemo(() => {
|
|
83
|
+
let blockCondition = false;
|
|
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;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// src/tanstack-router/useNavigationBlocker.ts
|
|
96
|
+
var hasBlockingHistory = (value) => {
|
|
97
|
+
if (!value || typeof value !== "object") {
|
|
98
|
+
return false;
|
|
99
|
+
}
|
|
100
|
+
if (!("history" in value)) {
|
|
101
|
+
return false;
|
|
102
|
+
}
|
|
103
|
+
const history = value.history;
|
|
104
|
+
if (!history || typeof history !== "object") {
|
|
105
|
+
return false;
|
|
106
|
+
}
|
|
107
|
+
if (!("block" in history)) {
|
|
108
|
+
return false;
|
|
109
|
+
}
|
|
110
|
+
return typeof history.block === "function";
|
|
111
|
+
};
|
|
112
|
+
var hasRetry = (value) => typeof value.retry === "function";
|
|
113
|
+
var attemptRetry = (update) => {
|
|
114
|
+
if (hasRetry(update)) {
|
|
115
|
+
try {
|
|
116
|
+
update.retry();
|
|
117
|
+
} catch {
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
function useNavigationBlocker(options) {
|
|
122
|
+
const { when, scope, message, onBlock, onAllow, blockBrowserUnload = true, onConfirm } = options;
|
|
123
|
+
const router = reactRouter.useRouter();
|
|
124
|
+
const shouldBlock = useShouldBlock(when, scope);
|
|
125
|
+
react.useEffect(() => {
|
|
126
|
+
if (!shouldBlock || !hasBlockingHistory(router)) {
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
const unblock = router.history.block((update) => {
|
|
130
|
+
if (!message) {
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
onBlock?.();
|
|
134
|
+
const confirmation = resolveConfirmResult(
|
|
135
|
+
message,
|
|
136
|
+
onConfirm,
|
|
137
|
+
(value) => window.confirm(value)
|
|
138
|
+
);
|
|
139
|
+
if (confirmation.kind === "async") {
|
|
140
|
+
confirmation.promise.then((confirmed) => {
|
|
141
|
+
if (confirmed) {
|
|
142
|
+
onAllow?.();
|
|
143
|
+
unblock();
|
|
144
|
+
attemptRetry(update);
|
|
145
|
+
}
|
|
146
|
+
}).catch((error) => {
|
|
147
|
+
unblock();
|
|
148
|
+
if (process.env.NODE_ENV !== "production") {
|
|
149
|
+
console.error("[react-action-guard-router] Confirmation error:", error);
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
if (confirmation.confirmed) {
|
|
155
|
+
onAllow?.();
|
|
156
|
+
unblock();
|
|
157
|
+
attemptRetry(update);
|
|
158
|
+
}
|
|
159
|
+
});
|
|
160
|
+
return () => {
|
|
161
|
+
unblock();
|
|
162
|
+
};
|
|
163
|
+
}, [shouldBlock, message, onBlock, onAllow, router, onConfirm]);
|
|
164
|
+
useBeforeUnload(blockBrowserUnload && shouldBlock, message ?? DEFAULT_UNLOAD_MESSAGE);
|
|
165
|
+
return {
|
|
166
|
+
isBlocking: shouldBlock
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
exports.useNavigationBlocker = useNavigationBlocker;
|
|
171
|
+
//# sourceMappingURL=index.cjs.map
|
|
172
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/core/utils.ts","../../src/core/useBeforeUnload.ts","../../src/core/useShouldBlock.ts","../../src/tanstack-router/useNavigationBlocker.ts"],"names":["useEffect","useMemo","useIsBlocked","useRef","useRouter"],"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,CAAA,EAAE;AAAA,EAC7D;AAEA,EAAA,MAAM,MAAA,GAAS,UAAU,OAAO,CAAA;AAChC,EAA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AAO;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","import { useRouter } from \"@tanstack/react-router\";\nimport { useEffect } from \"react\";\nimport {\n DEFAULT_UNLOAD_MESSAGE,\n resolveConfirmResult,\n useBeforeUnload,\n useShouldBlock,\n} from \"../core\";\nimport type { SafeTanStackRouter, UseNavigationBlockerOptions } from \"./types\";\nimport type { NavigationBlockerReturn } from \"../core/types\";\n\ninterface RetryableUpdate {\n [key: string]: unknown;\n retry: () => void;\n}\n\nconst hasBlockingHistory = (value: unknown): value is SafeTanStackRouter => {\n if (!value || typeof value !== \"object\") {\n return false;\n }\n if (!(\"history\" in value)) {\n return false;\n }\n const history = value.history;\n if (!history || typeof history !== \"object\") {\n return false;\n }\n if (!(\"block\" in history)) {\n return false;\n }\n return typeof history.block === \"function\";\n};\n\nconst hasRetry = (value: Record<string, unknown>): value is RetryableUpdate =>\n typeof value.retry === \"function\";\n\nconst attemptRetry = (update: Record<string, unknown>): void => {\n if (hasRetry(update)) {\n try {\n update.retry();\n } catch {\n // Swallow retry errors to avoid breaking blocking flow.\n }\n }\n};\n\n/**\n * Blocks navigation in TanStack Router applications based on conditions or scope state.\n *\n * This hook integrates with TanStack Router's history blocking mechanism 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 * **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 * @param options - Configuration options\n * @returns Object with `isBlocking` state\n *\n * @example\n * ```tsx\n * // Block based on scope\n * function EditForm() {\n * useNavigationBlocker({\n * scope: 'form',\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 condition\n * function UnsavedChanges() {\n * const [hasChanges, setHasChanges] = useState(false);\n *\n * useNavigationBlocker({\n * when: hasChanges,\n * message: 'Discard changes?',\n * onBlock: () => console.log('Navigation blocked'),\n * });\n * }\n * ```\n *\n * @example\n * ```tsx\n * // Type-safe with scopes\n * import { createTypedHooks } from '@okyrychenko-dev/react-action-guard';\n *\n * type AppScopes = 'global' | 'form' | 'checkout';\n * const { useBlocker } = createTypedHooks<AppScopes>();\n *\n * function MyComponent() {\n * useBlocker('blocker-id', { scope: 'form' });\n *\n * useNavigationBlocker({\n * scope: 'form', // Type-safe!\n * message: 'Leave?',\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\n // Use shared logic to determine if blocking should be active\n const shouldBlock = useShouldBlock(when, scope);\n\n // Block navigation using TanStack Router's history\n useEffect(() => {\n if (!shouldBlock || !hasBlockingHistory(router)) {\n return;\n }\n\n // Block navigation with properly typed update parameter\n type NavigationUpdate = Record<string, unknown> & { retry?: () => void };\n const unblock = router.history.block((update: NavigationUpdate) => {\n // Early return if no message\n if (!message) {\n return;\n }\n\n // Trigger onBlock callback\n onBlock?.();\n\n const confirmation = resolveConfirmResult(message, onConfirm, (value) =>\n window.confirm(value)\n );\n\n if (confirmation.kind === \"async\") {\n confirmation.promise\n .then((confirmed) => {\n if (confirmed) {\n onAllow?.();\n unblock();\n attemptRetry(update);\n }\n })\n .catch((error: unknown) => {\n // On error, unblock but don't retry\n unblock();\n if (process.env.NODE_ENV !== \"production\") {\n console.error(\"[react-action-guard-router] Confirmation error:\", error);\n }\n });\n return;\n }\n\n if (confirmation.confirmed) {\n onAllow?.();\n unblock();\n attemptRetry(update);\n }\n });\n\n return () => {\n unblock();\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"]}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { B as BaseNavigationBlockerOptions, N as NavigationBlockerReturn } from '../types-C3CPuZip.cjs';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Options for TanStack Router navigation blocker
|
|
5
|
+
*
|
|
6
|
+
* Currently uses all base options. This type exists for
|
|
7
|
+
* future TanStack Router-specific options extension.
|
|
8
|
+
*/
|
|
9
|
+
type UseNavigationBlockerOptions = BaseNavigationBlockerOptions;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Blocks navigation in TanStack Router applications based on conditions or scope state.
|
|
13
|
+
*
|
|
14
|
+
* This hook integrates with TanStack Router's history blocking mechanism 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
|
+
* **Features:**
|
|
19
|
+
* - Block navigation based on boolean condition or function
|
|
20
|
+
* - Automatically block when react-action-guard scopes are active
|
|
21
|
+
* - Support for browser `beforeunload` event (tab close/refresh)
|
|
22
|
+
* - Customizable confirmation dialog
|
|
23
|
+
* - Callbacks for block/allow events
|
|
24
|
+
*
|
|
25
|
+
* @param options - Configuration options
|
|
26
|
+
* @returns Object with `isBlocking` state
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* ```tsx
|
|
30
|
+
* // Block based on scope
|
|
31
|
+
* function EditForm() {
|
|
32
|
+
* useNavigationBlocker({
|
|
33
|
+
* scope: 'form',
|
|
34
|
+
* message: 'You have unsaved changes. Leave anyway?',
|
|
35
|
+
* });
|
|
36
|
+
*
|
|
37
|
+
* return <form>...</form>;
|
|
38
|
+
* }
|
|
39
|
+
* ```
|
|
40
|
+
*
|
|
41
|
+
* @example
|
|
42
|
+
* ```tsx
|
|
43
|
+
* // Block based on condition
|
|
44
|
+
* function UnsavedChanges() {
|
|
45
|
+
* const [hasChanges, setHasChanges] = useState(false);
|
|
46
|
+
*
|
|
47
|
+
* useNavigationBlocker({
|
|
48
|
+
* when: hasChanges,
|
|
49
|
+
* message: 'Discard changes?',
|
|
50
|
+
* onBlock: () => console.log('Navigation blocked'),
|
|
51
|
+
* });
|
|
52
|
+
* }
|
|
53
|
+
* ```
|
|
54
|
+
*
|
|
55
|
+
* @example
|
|
56
|
+
* ```tsx
|
|
57
|
+
* // Type-safe with scopes
|
|
58
|
+
* import { createTypedHooks } from '@okyrychenko-dev/react-action-guard';
|
|
59
|
+
*
|
|
60
|
+
* type AppScopes = 'global' | 'form' | 'checkout';
|
|
61
|
+
* const { useBlocker } = createTypedHooks<AppScopes>();
|
|
62
|
+
*
|
|
63
|
+
* function MyComponent() {
|
|
64
|
+
* useBlocker('blocker-id', { scope: 'form' });
|
|
65
|
+
*
|
|
66
|
+
* useNavigationBlocker({
|
|
67
|
+
* scope: 'form', // Type-safe!
|
|
68
|
+
* message: 'Leave?',
|
|
69
|
+
* });
|
|
70
|
+
* }
|
|
71
|
+
* ```
|
|
72
|
+
*/
|
|
73
|
+
declare function useNavigationBlocker(options: UseNavigationBlockerOptions): NavigationBlockerReturn;
|
|
74
|
+
|
|
75
|
+
export { type UseNavigationBlockerOptions, useNavigationBlocker };
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { B as BaseNavigationBlockerOptions, N as NavigationBlockerReturn } from '../types-C3CPuZip.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Options for TanStack Router navigation blocker
|
|
5
|
+
*
|
|
6
|
+
* Currently uses all base options. This type exists for
|
|
7
|
+
* future TanStack Router-specific options extension.
|
|
8
|
+
*/
|
|
9
|
+
type UseNavigationBlockerOptions = BaseNavigationBlockerOptions;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Blocks navigation in TanStack Router applications based on conditions or scope state.
|
|
13
|
+
*
|
|
14
|
+
* This hook integrates with TanStack Router's history blocking mechanism 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
|
+
* **Features:**
|
|
19
|
+
* - Block navigation based on boolean condition or function
|
|
20
|
+
* - Automatically block when react-action-guard scopes are active
|
|
21
|
+
* - Support for browser `beforeunload` event (tab close/refresh)
|
|
22
|
+
* - Customizable confirmation dialog
|
|
23
|
+
* - Callbacks for block/allow events
|
|
24
|
+
*
|
|
25
|
+
* @param options - Configuration options
|
|
26
|
+
* @returns Object with `isBlocking` state
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* ```tsx
|
|
30
|
+
* // Block based on scope
|
|
31
|
+
* function EditForm() {
|
|
32
|
+
* useNavigationBlocker({
|
|
33
|
+
* scope: 'form',
|
|
34
|
+
* message: 'You have unsaved changes. Leave anyway?',
|
|
35
|
+
* });
|
|
36
|
+
*
|
|
37
|
+
* return <form>...</form>;
|
|
38
|
+
* }
|
|
39
|
+
* ```
|
|
40
|
+
*
|
|
41
|
+
* @example
|
|
42
|
+
* ```tsx
|
|
43
|
+
* // Block based on condition
|
|
44
|
+
* function UnsavedChanges() {
|
|
45
|
+
* const [hasChanges, setHasChanges] = useState(false);
|
|
46
|
+
*
|
|
47
|
+
* useNavigationBlocker({
|
|
48
|
+
* when: hasChanges,
|
|
49
|
+
* message: 'Discard changes?',
|
|
50
|
+
* onBlock: () => console.log('Navigation blocked'),
|
|
51
|
+
* });
|
|
52
|
+
* }
|
|
53
|
+
* ```
|
|
54
|
+
*
|
|
55
|
+
* @example
|
|
56
|
+
* ```tsx
|
|
57
|
+
* // Type-safe with scopes
|
|
58
|
+
* import { createTypedHooks } from '@okyrychenko-dev/react-action-guard';
|
|
59
|
+
*
|
|
60
|
+
* type AppScopes = 'global' | 'form' | 'checkout';
|
|
61
|
+
* const { useBlocker } = createTypedHooks<AppScopes>();
|
|
62
|
+
*
|
|
63
|
+
* function MyComponent() {
|
|
64
|
+
* useBlocker('blocker-id', { scope: 'form' });
|
|
65
|
+
*
|
|
66
|
+
* useNavigationBlocker({
|
|
67
|
+
* scope: 'form', // Type-safe!
|
|
68
|
+
* message: 'Leave?',
|
|
69
|
+
* });
|
|
70
|
+
* }
|
|
71
|
+
* ```
|
|
72
|
+
*/
|
|
73
|
+
declare function useNavigationBlocker(options: UseNavigationBlockerOptions): NavigationBlockerReturn;
|
|
74
|
+
|
|
75
|
+
export { type UseNavigationBlockerOptions, useNavigationBlocker };
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { useRouter } from '@tanstack/react-router';
|
|
2
|
+
import { useEffect, useMemo, useRef } from 'react';
|
|
3
|
+
import { useIsBlocked } from '@okyrychenko-dev/react-action-guard';
|
|
4
|
+
|
|
5
|
+
// src/tanstack-router/useNavigationBlocker.ts
|
|
6
|
+
|
|
7
|
+
// src/core/utils.ts
|
|
8
|
+
function resolveCondition(condition) {
|
|
9
|
+
return typeof condition === "function" ? condition() : condition;
|
|
10
|
+
}
|
|
11
|
+
var hasThen = (value) => typeof value === "object" && value !== null && "then" in value;
|
|
12
|
+
function isThenable(value) {
|
|
13
|
+
if (!hasThen(value)) {
|
|
14
|
+
return false;
|
|
15
|
+
}
|
|
16
|
+
return typeof value.then === "function";
|
|
17
|
+
}
|
|
18
|
+
function resolveConfirmResult(message, onConfirm, fallbackConfirm) {
|
|
19
|
+
if (!onConfirm) {
|
|
20
|
+
return { kind: "sync", confirmed: fallbackConfirm(message) };
|
|
21
|
+
}
|
|
22
|
+
const result = onConfirm(message);
|
|
23
|
+
if (isThenable(result)) {
|
|
24
|
+
return { kind: "async", promise: Promise.resolve(result) };
|
|
25
|
+
}
|
|
26
|
+
return { kind: "sync", confirmed: result };
|
|
27
|
+
}
|
|
28
|
+
function isDefined(value) {
|
|
29
|
+
return value !== void 0 && value !== null;
|
|
30
|
+
}
|
|
31
|
+
function normalizeScope(scope) {
|
|
32
|
+
if (!scope) {
|
|
33
|
+
return [];
|
|
34
|
+
}
|
|
35
|
+
return Array.isArray(scope) ? scope : [scope];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// src/core/useBeforeUnload.ts
|
|
39
|
+
var DEFAULT_UNLOAD_MESSAGE = "Changes you made may not be saved.";
|
|
40
|
+
function useBeforeUnload(when, message = DEFAULT_UNLOAD_MESSAGE) {
|
|
41
|
+
useEffect(() => {
|
|
42
|
+
const shouldBlock = resolveCondition(when);
|
|
43
|
+
if (!shouldBlock) {
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
const handleBeforeUnload = (event) => {
|
|
47
|
+
event.preventDefault();
|
|
48
|
+
if ("returnValue" in event) {
|
|
49
|
+
event.returnValue = message;
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
window.addEventListener("beforeunload", handleBeforeUnload);
|
|
53
|
+
return () => {
|
|
54
|
+
window.removeEventListener("beforeunload", handleBeforeUnload);
|
|
55
|
+
};
|
|
56
|
+
}, [when, message]);
|
|
57
|
+
}
|
|
58
|
+
function useShouldBlock(when, scope) {
|
|
59
|
+
const scopes = useMemo(() => normalizeScope(scope), [scope]);
|
|
60
|
+
const isScopeBlocked = useIsBlocked(scopes.length === 1 ? scopes[0] : scopes);
|
|
61
|
+
const warnedMissingConditionRef = useRef(false);
|
|
62
|
+
const warnedFunctionRef = useRef(false);
|
|
63
|
+
useEffect(() => {
|
|
64
|
+
if (process.env.NODE_ENV !== "development") {
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
if (!warnedMissingConditionRef.current && !isDefined(when) && !scope) {
|
|
68
|
+
warnedMissingConditionRef.current = true;
|
|
69
|
+
console.warn(
|
|
70
|
+
'[react-action-guard-router] useShouldBlock: Neither "when" nor "scope" provided. This hook will always return false. Please provide at least one condition.'
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
if (!warnedFunctionRef.current && typeof when === "function") {
|
|
74
|
+
warnedFunctionRef.current = true;
|
|
75
|
+
console.warn(
|
|
76
|
+
'[react-action-guard-router] useShouldBlock: "when" is a function. Make sure to wrap it with useCallback to avoid unnecessary re-computations.'
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
}, [when, scope]);
|
|
80
|
+
const shouldBlock = useMemo(() => {
|
|
81
|
+
let blockCondition = false;
|
|
82
|
+
if (isDefined(when)) {
|
|
83
|
+
blockCondition = resolveCondition(when);
|
|
84
|
+
}
|
|
85
|
+
if (scope && isScopeBlocked) {
|
|
86
|
+
blockCondition = true;
|
|
87
|
+
}
|
|
88
|
+
return blockCondition;
|
|
89
|
+
}, [when, scope, isScopeBlocked]);
|
|
90
|
+
return shouldBlock;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// src/tanstack-router/useNavigationBlocker.ts
|
|
94
|
+
var hasBlockingHistory = (value) => {
|
|
95
|
+
if (!value || typeof value !== "object") {
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
if (!("history" in value)) {
|
|
99
|
+
return false;
|
|
100
|
+
}
|
|
101
|
+
const history = value.history;
|
|
102
|
+
if (!history || typeof history !== "object") {
|
|
103
|
+
return false;
|
|
104
|
+
}
|
|
105
|
+
if (!("block" in history)) {
|
|
106
|
+
return false;
|
|
107
|
+
}
|
|
108
|
+
return typeof history.block === "function";
|
|
109
|
+
};
|
|
110
|
+
var hasRetry = (value) => typeof value.retry === "function";
|
|
111
|
+
var attemptRetry = (update) => {
|
|
112
|
+
if (hasRetry(update)) {
|
|
113
|
+
try {
|
|
114
|
+
update.retry();
|
|
115
|
+
} catch {
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
function useNavigationBlocker(options) {
|
|
120
|
+
const { when, scope, message, onBlock, onAllow, blockBrowserUnload = true, onConfirm } = options;
|
|
121
|
+
const router = useRouter();
|
|
122
|
+
const shouldBlock = useShouldBlock(when, scope);
|
|
123
|
+
useEffect(() => {
|
|
124
|
+
if (!shouldBlock || !hasBlockingHistory(router)) {
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
const unblock = router.history.block((update) => {
|
|
128
|
+
if (!message) {
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
onBlock?.();
|
|
132
|
+
const confirmation = resolveConfirmResult(
|
|
133
|
+
message,
|
|
134
|
+
onConfirm,
|
|
135
|
+
(value) => window.confirm(value)
|
|
136
|
+
);
|
|
137
|
+
if (confirmation.kind === "async") {
|
|
138
|
+
confirmation.promise.then((confirmed) => {
|
|
139
|
+
if (confirmed) {
|
|
140
|
+
onAllow?.();
|
|
141
|
+
unblock();
|
|
142
|
+
attemptRetry(update);
|
|
143
|
+
}
|
|
144
|
+
}).catch((error) => {
|
|
145
|
+
unblock();
|
|
146
|
+
if (process.env.NODE_ENV !== "production") {
|
|
147
|
+
console.error("[react-action-guard-router] Confirmation error:", error);
|
|
148
|
+
}
|
|
149
|
+
});
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
if (confirmation.confirmed) {
|
|
153
|
+
onAllow?.();
|
|
154
|
+
unblock();
|
|
155
|
+
attemptRetry(update);
|
|
156
|
+
}
|
|
157
|
+
});
|
|
158
|
+
return () => {
|
|
159
|
+
unblock();
|
|
160
|
+
};
|
|
161
|
+
}, [shouldBlock, message, onBlock, onAllow, router, onConfirm]);
|
|
162
|
+
useBeforeUnload(blockBrowserUnload && shouldBlock, message ?? DEFAULT_UNLOAD_MESSAGE);
|
|
163
|
+
return {
|
|
164
|
+
isBlocking: shouldBlock
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export { useNavigationBlocker };
|
|
169
|
+
//# sourceMappingURL=index.js.map
|
|
170
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/core/utils.ts","../../src/core/useBeforeUnload.ts","../../src/core/useShouldBlock.ts","../../src/tanstack-router/useNavigationBlocker.ts"],"names":["useEffect"],"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,O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A,IAAU;AACV,QAAA,OAAA,EAAQ;AACR,QAAA,YAAA,CAAa,MAAM,CAAA;AAAA,MACrB;AAAA,IACF,CAAC,CAAA;AAED,IAAA,OAAO,MAAM;AACX,MAAA,OAAA,EAAQ;AAAA,IACV,CAAA;AAAA,EACF,CAAA,EAAG,CAAC,WAAA,EAAa,OAAA,EAAS,SAAS,OAAA,EAAS,MAAA,EAAQ,SAAS,CAAC,CAAA;AAG9D,EAAA,eAAA,CAAgB,kBAAA,IAAsB,WAAA,EAAa,OAAA,IAAW,sBAAsB,CAAA;AAEpF,EAAA,OAAO;AAAA,IACL,UAAA,EAAY;AAAA,GACd;AACF","file":"index.js","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","import { useRouter } from \"@tanstack/react-router\";\nimport { useEffect } from \"react\";\nimport {\n DEFAULT_UNLOAD_MESSAGE,\n resolveConfirmResult,\n useBeforeUnload,\n useShouldBlock,\n} from \"../core\";\nimport type { SafeTanStackRouter, UseNavigationBlockerOptions } from \"./types\";\nimport type { NavigationBlockerReturn } from \"../core/types\";\n\ninterface RetryableUpdate {\n [key: string]: unknown;\n retry: () => void;\n}\n\nconst hasBlockingHistory = (value: unknown): value is SafeTanStackRouter => {\n if (!value || typeof value !== \"object\") {\n return false;\n }\n if (!(\"history\" in value)) {\n return false;\n }\n const history = value.history;\n if (!history || typeof history !== \"object\") {\n return false;\n }\n if (!(\"block\" in history)) {\n return false;\n }\n return typeof history.block === \"function\";\n};\n\nconst hasRetry = (value: Record<string, unknown>): value is RetryableUpdate =>\n typeof value.retry === \"function\";\n\nconst attemptRetry = (update: Record<string, unknown>): void => {\n if (hasRetry(update)) {\n try {\n update.retry();\n } catch {\n // Swallow retry errors to avoid breaking blocking flow.\n }\n }\n};\n\n/**\n * Blocks navigation in TanStack Router applications based on conditions or scope state.\n *\n * This hook integrates with TanStack Router's history blocking mechanism 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 * **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 * @param options - Configuration options\n * @returns Object with `isBlocking` state\n *\n * @example\n * ```tsx\n * // Block based on scope\n * function EditForm() {\n * useNavigationBlocker({\n * scope: 'form',\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 condition\n * function UnsavedChanges() {\n * const [hasChanges, setHasChanges] = useState(false);\n *\n * useNavigationBlocker({\n * when: hasChanges,\n * message: 'Discard changes?',\n * onBlock: () => console.log('Navigation blocked'),\n * });\n * }\n * ```\n *\n * @example\n * ```tsx\n * // Type-safe with scopes\n * import { createTypedHooks } from '@okyrychenko-dev/react-action-guard';\n *\n * type AppScopes = 'global' | 'form' | 'checkout';\n * const { useBlocker } = createTypedHooks<AppScopes>();\n *\n * function MyComponent() {\n * useBlocker('blocker-id', { scope: 'form' });\n *\n * useNavigationBlocker({\n * scope: 'form', // Type-safe!\n * message: 'Leave?',\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\n // Use shared logic to determine if blocking should be active\n const shouldBlock = useShouldBlock(when, scope);\n\n // Block navigation using TanStack Router's history\n useEffect(() => {\n if (!shouldBlock || !hasBlockingHistory(router)) {\n return;\n }\n\n // Block navigation with properly typed update parameter\n type NavigationUpdate = Record<string, unknown> & { retry?: () => void };\n const unblock = router.history.block((update: NavigationUpdate) => {\n // Early return if no message\n if (!message) {\n return;\n }\n\n // Trigger onBlock callback\n onBlock?.();\n\n const confirmation = resolveConfirmResult(message, onConfirm, (value) =>\n window.confirm(value)\n );\n\n if (confirmation.kind === \"async\") {\n confirmation.promise\n .then((confirmed) => {\n if (confirmed) {\n onAllow?.();\n unblock();\n attemptRetry(update);\n }\n })\n .catch((error: unknown) => {\n // On error, unblock but don't retry\n unblock();\n if (process.env.NODE_ENV !== \"production\") {\n console.error(\"[react-action-guard-router] Confirmation error:\", error);\n }\n });\n return;\n }\n\n if (confirmation.confirmed) {\n onAllow?.();\n unblock();\n attemptRetry(update);\n }\n });\n\n return () => {\n unblock();\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"]}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Core types for navigation blocking functionality
|
|
3
|
+
*/
|
|
4
|
+
/**
|
|
5
|
+
* Base configuration for navigation blocking
|
|
6
|
+
*/
|
|
7
|
+
interface BaseNavigationBlockerOptions {
|
|
8
|
+
/**
|
|
9
|
+
* Condition to determine if blocking should be active
|
|
10
|
+
* Can be a boolean value or a function that returns a boolean
|
|
11
|
+
*/
|
|
12
|
+
when?: boolean | (() => boolean);
|
|
13
|
+
/**
|
|
14
|
+
* Scope(s) from react-action-guard to check for blocking
|
|
15
|
+
* When specified, navigation is blocked if any of these scopes are currently blocked
|
|
16
|
+
*/
|
|
17
|
+
scope?: string | Array<string>;
|
|
18
|
+
/**
|
|
19
|
+
* Message to show in confirmation dialog
|
|
20
|
+
* @default "Are you sure you want to leave? Changes you made may not be saved."
|
|
21
|
+
*/
|
|
22
|
+
message?: string;
|
|
23
|
+
/**
|
|
24
|
+
* Callback when navigation is blocked
|
|
25
|
+
*/
|
|
26
|
+
onBlock?: () => void;
|
|
27
|
+
/**
|
|
28
|
+
* Callback when navigation is allowed
|
|
29
|
+
*/
|
|
30
|
+
onAllow?: () => void;
|
|
31
|
+
/**
|
|
32
|
+
* Whether to also block browser unload events (tab close, refresh)
|
|
33
|
+
* @default true
|
|
34
|
+
*/
|
|
35
|
+
blockBrowserUnload?: boolean;
|
|
36
|
+
/**
|
|
37
|
+
* Custom confirmation handler for showing your own dialog UI.
|
|
38
|
+
*
|
|
39
|
+
* If provided, this will be called instead of window.confirm() to allow
|
|
40
|
+
* custom dialog components. Async handlers are supported, but note:
|
|
41
|
+
* - Next.js Pages Router re-attempts navigation after resolve.
|
|
42
|
+
* - Router adapters may ignore stale resolves if a newer confirm starts.
|
|
43
|
+
*
|
|
44
|
+
* @param message - The confirmation message to display
|
|
45
|
+
* @returns boolean | Promise<boolean> - true to allow navigation, false to block
|
|
46
|
+
*
|
|
47
|
+
* @example
|
|
48
|
+
* ```tsx
|
|
49
|
+
* // With custom dialog component
|
|
50
|
+
* const [dialogState, setDialogState] = useState(null);
|
|
51
|
+
*
|
|
52
|
+
* onConfirm: (message) => {
|
|
53
|
+
* return new Promise((resolve) => {
|
|
54
|
+
* setDialogState({ message, resolve });
|
|
55
|
+
* });
|
|
56
|
+
* }
|
|
57
|
+
*
|
|
58
|
+
* // In JSX:
|
|
59
|
+
* {dialogState && (
|
|
60
|
+
* <CustomDialog
|
|
61
|
+
* message={dialogState.message}
|
|
62
|
+
* onConfirm={() => {
|
|
63
|
+
* dialogState.resolve(true);
|
|
64
|
+
* setDialogState(null);
|
|
65
|
+
* }}
|
|
66
|
+
* onCancel={() => {
|
|
67
|
+
* dialogState.resolve(false);
|
|
68
|
+
* setDialogState(null);
|
|
69
|
+
* }}
|
|
70
|
+
* />
|
|
71
|
+
* )}
|
|
72
|
+
* ```
|
|
73
|
+
*/
|
|
74
|
+
onConfirm?: (message: string) => boolean | PromiseLike<boolean>;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Configuration for browser beforeunload event
|
|
78
|
+
*/
|
|
79
|
+
interface BeforeUnloadOptions {
|
|
80
|
+
/**
|
|
81
|
+
* Condition to determine if blocking should be active
|
|
82
|
+
*/
|
|
83
|
+
when: boolean | (() => boolean);
|
|
84
|
+
/**
|
|
85
|
+
* Custom message (may be ignored by modern browsers)
|
|
86
|
+
* @default "Changes you made may not be saved."
|
|
87
|
+
*/
|
|
88
|
+
message?: string;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Return type for navigation blocker hooks
|
|
92
|
+
*/
|
|
93
|
+
interface NavigationBlockerReturn {
|
|
94
|
+
/**
|
|
95
|
+
* Whether the blocking condition is currently active.
|
|
96
|
+
*/
|
|
97
|
+
isBlocking: boolean;
|
|
98
|
+
/**
|
|
99
|
+
* Whether navigation is currently being intercepted.
|
|
100
|
+
* Only available for adapters that can observe active interception state.
|
|
101
|
+
*/
|
|
102
|
+
isIntercepting?: boolean;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export type { BaseNavigationBlockerOptions as B, NavigationBlockerReturn as N, BeforeUnloadOptions as a };
|