@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.
@@ -0,0 +1,158 @@
1
+ export { B as BaseNavigationBlockerOptions, a as BeforeUnloadOptions, N as NavigationBlockerReturn } from './types-C3CPuZip.cjs';
2
+
3
+ /**
4
+ * Blocks browser tab close/refresh when condition is met.
5
+ *
6
+ * This hook adds a `beforeunload` event listener to warn users
7
+ * before they close or refresh the browser tab. Modern browsers
8
+ * may ignore custom messages and show their own generic warning.
9
+ *
10
+ * @param when - Boolean or function returning boolean to determine if blocking should be active
11
+ * @param message - Optional custom message (may be ignored by browsers)
12
+ *
13
+ * @example
14
+ * ```tsx
15
+ * function MyForm() {
16
+ * const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
17
+ *
18
+ * useBeforeUnload(hasUnsavedChanges, 'You have unsaved changes');
19
+ *
20
+ * return <form>...</form>;
21
+ * }
22
+ * ```
23
+ *
24
+ * @example
25
+ * ```tsx
26
+ * // With function condition
27
+ * function EditPage() {
28
+ * const isFormDirty = useIsBlocked('form');
29
+ *
30
+ * useBeforeUnload(() => isFormDirty);
31
+ *
32
+ * return <div>...</div>;
33
+ * }
34
+ * ```
35
+ */
36
+ declare function useBeforeUnload(when: boolean | (() => boolean), message?: string): void;
37
+
38
+ /**
39
+ * State object for a confirmation dialog
40
+ */
41
+ interface DialogState<T = string> {
42
+ /** Whether the dialog is currently open */
43
+ isOpen: boolean;
44
+ /** The data to display in the dialog (typically a message) */
45
+ message: T;
46
+ /** Resolver function to confirm/cancel navigation */
47
+ resolve: (confirmed: boolean) => void;
48
+ }
49
+ /**
50
+ * Return type for useDialogState hook
51
+ */
52
+ interface UseDialogStateReturn<T = string> {
53
+ /** Current dialog state (null when closed) */
54
+ dialogState: DialogState<T> | null;
55
+ /**
56
+ * Function to use as onConfirm callback.
57
+ * Returns a Promise that resolves when user confirms/cancels.
58
+ */
59
+ confirm: (message: T) => Promise<boolean>;
60
+ /** Close dialog with confirmation (allows navigation) */
61
+ onConfirm: () => void;
62
+ /** Close dialog with cancellation (blocks navigation) */
63
+ onCancel: () => void;
64
+ }
65
+ /**
66
+ * Hook to manage custom confirmation dialog state.
67
+ *
68
+ * Simplifies integration with custom dialog components when using
69
+ * navigation blocking with `onConfirm` callback.
70
+ *
71
+ * @template T - Type of message/data to pass to dialog (defaults to string)
72
+ * @returns Object with dialog state and control functions
73
+ *
74
+ * @example
75
+ * ```tsx
76
+ * function MyForm() {
77
+ * const [isDirty, setIsDirty] = useState(false);
78
+ * const { dialogState, confirm, onConfirm, onCancel } = useDialogState();
79
+ *
80
+ * useNavigationBlocker({
81
+ * when: isDirty,
82
+ * message: 'Unsaved changes',
83
+ * onConfirm: confirm,
84
+ * });
85
+ *
86
+ * return (
87
+ * <>
88
+ * <form>...</form>
89
+ * {dialogState && (
90
+ * <ConfirmDialog
91
+ * message={dialogState.message}
92
+ * onConfirm={onConfirm}
93
+ * onCancel={onCancel}
94
+ * />
95
+ * )}
96
+ * </>
97
+ * );
98
+ * }
99
+ * ```
100
+ *
101
+ * @example
102
+ * ```tsx
103
+ * // With Material-UI
104
+ * import { Dialog, DialogTitle, DialogActions, Button } from '@mui/material';
105
+ *
106
+ * function EditPage() {
107
+ * const { dialogState, confirm, onConfirm, onCancel } = useDialogState();
108
+ *
109
+ * useNavigationBlocker({
110
+ * when: hasChanges,
111
+ * onConfirm: confirm,
112
+ * });
113
+ *
114
+ * return (
115
+ * <Dialog open={dialogState?.isOpen ?? false}>
116
+ * <DialogTitle>{dialogState?.message}</DialogTitle>
117
+ * <DialogActions>
118
+ * <Button onClick={onCancel}>Stay</Button>
119
+ * <Button onClick={onConfirm}>Leave</Button>
120
+ * </DialogActions>
121
+ * </Dialog>
122
+ * );
123
+ * }
124
+ * ```
125
+ */
126
+ declare function useDialogState<T = string>(): UseDialogStateReturn<T>;
127
+
128
+ /**
129
+ * Resolves a condition value (boolean or function returning boolean)
130
+ *
131
+ * @param condition - Boolean value or function
132
+ * @returns Resolved boolean value
133
+ */
134
+ declare function resolveCondition(condition: boolean | (() => boolean)): boolean;
135
+ /**
136
+ * Generates a unique blocker ID based on scope and timestamp
137
+ *
138
+ * @param prefix - Prefix for the ID
139
+ * @param scope - Optional scope
140
+ * @returns Unique blocker ID
141
+ */
142
+ declare function createBlockerId(prefix: string, scope?: string | Array<string>): string;
143
+ /**
144
+ * Checks if a value is defined and not empty
145
+ *
146
+ * @param value - Value to check
147
+ * @returns True if value is defined and not empty
148
+ */
149
+ declare function isDefined<T>(value: T | undefined | null): value is T;
150
+ /**
151
+ * Normalizes scope to an array
152
+ *
153
+ * @param scope - String or array of strings
154
+ * @returns Array of scope strings
155
+ */
156
+ declare function normalizeScope(scope: string | Array<string> | undefined): Array<string>;
157
+
158
+ export { type DialogState, type UseDialogStateReturn, createBlockerId, isDefined, normalizeScope, resolveCondition, useBeforeUnload, useDialogState };
@@ -0,0 +1,158 @@
1
+ export { B as BaseNavigationBlockerOptions, a as BeforeUnloadOptions, N as NavigationBlockerReturn } from './types-C3CPuZip.js';
2
+
3
+ /**
4
+ * Blocks browser tab close/refresh when condition is met.
5
+ *
6
+ * This hook adds a `beforeunload` event listener to warn users
7
+ * before they close or refresh the browser tab. Modern browsers
8
+ * may ignore custom messages and show their own generic warning.
9
+ *
10
+ * @param when - Boolean or function returning boolean to determine if blocking should be active
11
+ * @param message - Optional custom message (may be ignored by browsers)
12
+ *
13
+ * @example
14
+ * ```tsx
15
+ * function MyForm() {
16
+ * const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
17
+ *
18
+ * useBeforeUnload(hasUnsavedChanges, 'You have unsaved changes');
19
+ *
20
+ * return <form>...</form>;
21
+ * }
22
+ * ```
23
+ *
24
+ * @example
25
+ * ```tsx
26
+ * // With function condition
27
+ * function EditPage() {
28
+ * const isFormDirty = useIsBlocked('form');
29
+ *
30
+ * useBeforeUnload(() => isFormDirty);
31
+ *
32
+ * return <div>...</div>;
33
+ * }
34
+ * ```
35
+ */
36
+ declare function useBeforeUnload(when: boolean | (() => boolean), message?: string): void;
37
+
38
+ /**
39
+ * State object for a confirmation dialog
40
+ */
41
+ interface DialogState<T = string> {
42
+ /** Whether the dialog is currently open */
43
+ isOpen: boolean;
44
+ /** The data to display in the dialog (typically a message) */
45
+ message: T;
46
+ /** Resolver function to confirm/cancel navigation */
47
+ resolve: (confirmed: boolean) => void;
48
+ }
49
+ /**
50
+ * Return type for useDialogState hook
51
+ */
52
+ interface UseDialogStateReturn<T = string> {
53
+ /** Current dialog state (null when closed) */
54
+ dialogState: DialogState<T> | null;
55
+ /**
56
+ * Function to use as onConfirm callback.
57
+ * Returns a Promise that resolves when user confirms/cancels.
58
+ */
59
+ confirm: (message: T) => Promise<boolean>;
60
+ /** Close dialog with confirmation (allows navigation) */
61
+ onConfirm: () => void;
62
+ /** Close dialog with cancellation (blocks navigation) */
63
+ onCancel: () => void;
64
+ }
65
+ /**
66
+ * Hook to manage custom confirmation dialog state.
67
+ *
68
+ * Simplifies integration with custom dialog components when using
69
+ * navigation blocking with `onConfirm` callback.
70
+ *
71
+ * @template T - Type of message/data to pass to dialog (defaults to string)
72
+ * @returns Object with dialog state and control functions
73
+ *
74
+ * @example
75
+ * ```tsx
76
+ * function MyForm() {
77
+ * const [isDirty, setIsDirty] = useState(false);
78
+ * const { dialogState, confirm, onConfirm, onCancel } = useDialogState();
79
+ *
80
+ * useNavigationBlocker({
81
+ * when: isDirty,
82
+ * message: 'Unsaved changes',
83
+ * onConfirm: confirm,
84
+ * });
85
+ *
86
+ * return (
87
+ * <>
88
+ * <form>...</form>
89
+ * {dialogState && (
90
+ * <ConfirmDialog
91
+ * message={dialogState.message}
92
+ * onConfirm={onConfirm}
93
+ * onCancel={onCancel}
94
+ * />
95
+ * )}
96
+ * </>
97
+ * );
98
+ * }
99
+ * ```
100
+ *
101
+ * @example
102
+ * ```tsx
103
+ * // With Material-UI
104
+ * import { Dialog, DialogTitle, DialogActions, Button } from '@mui/material';
105
+ *
106
+ * function EditPage() {
107
+ * const { dialogState, confirm, onConfirm, onCancel } = useDialogState();
108
+ *
109
+ * useNavigationBlocker({
110
+ * when: hasChanges,
111
+ * onConfirm: confirm,
112
+ * });
113
+ *
114
+ * return (
115
+ * <Dialog open={dialogState?.isOpen ?? false}>
116
+ * <DialogTitle>{dialogState?.message}</DialogTitle>
117
+ * <DialogActions>
118
+ * <Button onClick={onCancel}>Stay</Button>
119
+ * <Button onClick={onConfirm}>Leave</Button>
120
+ * </DialogActions>
121
+ * </Dialog>
122
+ * );
123
+ * }
124
+ * ```
125
+ */
126
+ declare function useDialogState<T = string>(): UseDialogStateReturn<T>;
127
+
128
+ /**
129
+ * Resolves a condition value (boolean or function returning boolean)
130
+ *
131
+ * @param condition - Boolean value or function
132
+ * @returns Resolved boolean value
133
+ */
134
+ declare function resolveCondition(condition: boolean | (() => boolean)): boolean;
135
+ /**
136
+ * Generates a unique blocker ID based on scope and timestamp
137
+ *
138
+ * @param prefix - Prefix for the ID
139
+ * @param scope - Optional scope
140
+ * @returns Unique blocker ID
141
+ */
142
+ declare function createBlockerId(prefix: string, scope?: string | Array<string>): string;
143
+ /**
144
+ * Checks if a value is defined and not empty
145
+ *
146
+ * @param value - Value to check
147
+ * @returns True if value is defined and not empty
148
+ */
149
+ declare function isDefined<T>(value: T | undefined | null): value is T;
150
+ /**
151
+ * Normalizes scope to an array
152
+ *
153
+ * @param scope - String or array of strings
154
+ * @returns Array of scope strings
155
+ */
156
+ declare function normalizeScope(scope: string | Array<string> | undefined): Array<string>;
157
+
158
+ export { type DialogState, type UseDialogStateReturn, createBlockerId, isDefined, normalizeScope, resolveCondition, useBeforeUnload, useDialogState };
package/dist/index.js ADDED
@@ -0,0 +1,84 @@
1
+ import { useEffect, useState, useRef, useCallback } from 'react';
2
+
3
+ // src/core/useBeforeUnload.ts
4
+
5
+ // src/core/utils.ts
6
+ function resolveCondition(condition) {
7
+ return typeof condition === "function" ? condition() : condition;
8
+ }
9
+ function createBlockerId(prefix, scope) {
10
+ const scopePart = scope ? `-${Array.isArray(scope) ? scope.join("-") : scope}` : "";
11
+ const timestamp = String(Date.now());
12
+ return `${prefix}${scopePart}-${timestamp}`;
13
+ }
14
+ function isDefined(value) {
15
+ return value !== void 0 && value !== null;
16
+ }
17
+ function normalizeScope(scope) {
18
+ if (!scope) {
19
+ return [];
20
+ }
21
+ return Array.isArray(scope) ? scope : [scope];
22
+ }
23
+
24
+ // src/core/useBeforeUnload.ts
25
+ var DEFAULT_UNLOAD_MESSAGE = "Changes you made may not be saved.";
26
+ function useBeforeUnload(when, message = DEFAULT_UNLOAD_MESSAGE) {
27
+ useEffect(() => {
28
+ const shouldBlock = resolveCondition(when);
29
+ if (!shouldBlock) {
30
+ return;
31
+ }
32
+ const handleBeforeUnload = (event) => {
33
+ event.preventDefault();
34
+ if ("returnValue" in event) {
35
+ event.returnValue = message;
36
+ }
37
+ };
38
+ window.addEventListener("beforeunload", handleBeforeUnload);
39
+ return () => {
40
+ window.removeEventListener("beforeunload", handleBeforeUnload);
41
+ };
42
+ }, [when, message]);
43
+ }
44
+ function useDialogState() {
45
+ const [dialogState, setDialogState] = useState(null);
46
+ const resolveRef = useRef(null);
47
+ const confirm = useCallback((message) => {
48
+ return new Promise((resolve) => {
49
+ if (resolveRef.current) {
50
+ resolveRef.current(false);
51
+ }
52
+ resolveRef.current = resolve;
53
+ setDialogState({
54
+ isOpen: true,
55
+ message,
56
+ resolve
57
+ });
58
+ });
59
+ }, []);
60
+ const closeDialog = useCallback((confirmed) => {
61
+ const resolve = resolveRef.current;
62
+ if (resolve) {
63
+ resolve(confirmed);
64
+ }
65
+ resolveRef.current = null;
66
+ setDialogState(null);
67
+ }, []);
68
+ const onConfirm = useCallback(() => {
69
+ closeDialog(true);
70
+ }, [closeDialog]);
71
+ const onCancel = useCallback(() => {
72
+ closeDialog(false);
73
+ }, [closeDialog]);
74
+ return {
75
+ dialogState,
76
+ confirm,
77
+ onConfirm,
78
+ onCancel
79
+ };
80
+ }
81
+
82
+ export { createBlockerId, isDefined, normalizeScope, resolveCondition, useBeforeUnload, useDialogState };
83
+ //# sourceMappingURL=index.js.map
84
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/utils.ts","../src/core/useBeforeUnload.ts","../src/core/useDialogState.ts"],"names":[],"mappings":";;;;;AAMO,SAAS,iBAAiB,SAAA,EAA+C;AAC9E,EAAA,OAAO,OAAO,SAAA,KAAc,UAAA,GAAa,SAAA,EAAU,GAAI,SAAA;AACzD;AA0DO,SAAS,eAAA,CAAgB,QAAgB,KAAA,EAAwC;AACtF,EAAA,MAAM,SAAA,GAAY,KAAA,GAAQ,CAAA,CAAA,EAAI,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA,GAAI,KAAA,CAAM,IAAA,CAAK,GAAG,CAAA,GAAI,KAAK,CAAA,CAAA,GAAK,EAAA;AACjF,EAAA,MAAM,SAAA,GAAY,MAAA,CAAO,IAAA,CAAK,GAAA,EAAK,CAAA;AACnC,EAAA,OAAO,CAAA,EAAG,MAAM,CAAA,EAAG,SAAS,IAAI,SAAS,CAAA,CAAA;AAC3C;AAQO,SAAS,UAAa,KAAA,EAAyC;AACpE,EAAA,OAAO,KAAA,KAAU,UAAa,KAAA,KAAU,IAAA;AAC1C;AAQO,SAAS,eAAe,KAAA,EAA0D;AACvF,EAAA,IAAI,CAAC,KAAA,EAAO;AACV,IAAA,OAAO,EAAC;AAAA,EACV;AACA,EAAA,OAAO,MAAM,OAAA,CAAQ,KAAK,CAAA,GAAI,KAAA,GAAQ,CAAC,KAAK,CAAA;AAC9C;;;ACvFO,IAAM,sBAAA,GAAyB,oCAAA;AAmC/B,SAAS,eAAA,CACd,IAAA,EACA,OAAA,GAAU,sBAAA,EACJ;AACN,EAAA,SAAA,CAAU,MAAM;AACd,IAAA,MAAM,WAAA,GAAc,iBAAiB,IAAI,CAAA;AAEzC,IAAA,IAAI,CAAC,WAAA,EAAa;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IAAA;AACrB,IAAA,cAAA,CAAe,IAAI,CAAA;AAAA,EACrB,CAAA,EAAG,EAAE,CAAA;AAEL,EAAA,MAAM,SAAA,GAAY,YAAY,MAAM;AAClC,IAAA,WAAA,CAAY,IAAI,CAAA;AAAA,EAClB,CAAA,EAAG,CAAC,WAAW,CAAC,CAAA;AAEhB,EAAA,MAAM,QAAA,GAAW,YAAY,MAAM;AACjC,IAAA,WAAA,CAAY,KAAK,CAAA;AAAA,EACnB,CAAA,EAAG,CAAC,WAAW,CAAC,CAAA;AAEhB,EAAA,OAAO;AAAA,IACL,WAAA;AAAA,IACA,OAAA;AAAA,IACA,SAAA;AAAA,IACA;AAAA,GACF;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 { useCallback, useRef, useState } from \"react\";\n\n/**\n * State object for a confirmation dialog\n */\nexport interface DialogState<T = string> {\n /** Whether the dialog is currently open */\n isOpen: boolean;\n\n /** The data to display in the dialog (typically a message) */\n message: T;\n\n /** Resolver function to confirm/cancel navigation */\n resolve: (confirmed: boolean) => void;\n}\n\n/**\n * Return type for useDialogState hook\n */\nexport interface UseDialogStateReturn<T = string> {\n /** Current dialog state (null when closed) */\n dialogState: DialogState<T> | null;\n\n /**\n * Function to use as onConfirm callback.\n * Returns a Promise that resolves when user confirms/cancels.\n */\n confirm: (message: T) => Promise<boolean>;\n\n /** Close dialog with confirmation (allows navigation) */\n onConfirm: () => void;\n\n /** Close dialog with cancellation (blocks navigation) */\n onCancel: () => void;\n}\n\n/**\n * Hook to manage custom confirmation dialog state.\n *\n * Simplifies integration with custom dialog components when using\n * navigation blocking with `onConfirm` callback.\n *\n * @template T - Type of message/data to pass to dialog (defaults to string)\n * @returns Object with dialog state and control functions\n *\n * @example\n * ```tsx\n * function MyForm() {\n * const [isDirty, setIsDirty] = useState(false);\n * const { dialogState, confirm, onConfirm, onCancel } = useDialogState();\n *\n * useNavigationBlocker({\n * when: isDirty,\n * message: 'Unsaved changes',\n * onConfirm: confirm,\n * });\n *\n * return (\n * <>\n * <form>...</form>\n * {dialogState && (\n * <ConfirmDialog\n * message={dialogState.message}\n * onConfirm={onConfirm}\n * onCancel={onCancel}\n * />\n * )}\n * </>\n * );\n * }\n * ```\n *\n * @example\n * ```tsx\n * // With Material-UI\n * import { Dialog, DialogTitle, DialogActions, Button } from '@mui/material';\n *\n * function EditPage() {\n * const { dialogState, confirm, onConfirm, onCancel } = useDialogState();\n *\n * useNavigationBlocker({\n * when: hasChanges,\n * onConfirm: confirm,\n * });\n *\n * return (\n * <Dialog open={dialogState?.isOpen ?? false}>\n * <DialogTitle>{dialogState?.message}</DialogTitle>\n * <DialogActions>\n * <Button onClick={onCancel}>Stay</Button>\n * <Button onClick={onConfirm}>Leave</Button>\n * </DialogActions>\n * </Dialog>\n * );\n * }\n * ```\n */\nexport function useDialogState<T = string>(): UseDialogStateReturn<T> {\n const [dialogState, setDialogState] = useState<DialogState<T> | null>(null);\n const resolveRef = useRef<DialogState<T>[\"resolve\"] | null>(null);\n\n const confirm = useCallback((message: T): Promise<boolean> => {\n return new Promise<boolean>((resolve) => {\n if (resolveRef.current) {\n resolveRef.current(false);\n }\n resolveRef.current = resolve;\n setDialogState({\n isOpen: true,\n message,\n resolve,\n });\n });\n }, []);\n\n const closeDialog = useCallback((confirmed: boolean) => {\n const resolve = resolveRef.current;\n if (resolve) {\n resolve(confirmed);\n }\n resolveRef.current = null;\n setDialogState(null);\n }, []);\n\n const onConfirm = useCallback(() => {\n closeDialog(true);\n }, [closeDialog]);\n\n const onCancel = useCallback(() => {\n closeDialog(false);\n }, [closeDialog]);\n\n return {\n dialogState,\n confirm,\n onConfirm,\n onCancel,\n };\n}\n"]}
@@ -0,0 +1,178 @@
1
+ 'use strict';
2
+
3
+ var router = require('next/router');
4
+ var react = require('react');
5
+ var reactActionGuard = require('@okyrychenko-dev/react-action-guard');
6
+
7
+ // src/nextjs/usePagesRouterBlocker.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/core/constants.ts
96
+ var ROUTE_ERRORS = {
97
+ /** Route change was aborted by the user */
98
+ ABORTED: "Route change aborted by user",
99
+ /** Route change was blocked */
100
+ BLOCKED: "Route change blocked"
101
+ };
102
+
103
+ // src/nextjs/usePagesRouterBlocker.ts
104
+ function useNavigationBlocker(options) {
105
+ const { when, scope, message, onBlock, onAllow, blockBrowserUnload = true, onConfirm } = options;
106
+ const router$1 = router.useRouter();
107
+ const allowNextUrlRef = react.useRef(null);
108
+ const shouldBlock = useShouldBlock(when, scope);
109
+ react.useEffect(() => {
110
+ if (!shouldBlock) {
111
+ return;
112
+ }
113
+ const handleRouteChangeStart = (url) => {
114
+ if (allowNextUrlRef.current === url) {
115
+ allowNextUrlRef.current = null;
116
+ onAllow?.();
117
+ return;
118
+ }
119
+ onBlock?.();
120
+ if (!message) {
121
+ router$1.events.emit("routeChangeError");
122
+ throw new Error(ROUTE_ERRORS.BLOCKED);
123
+ }
124
+ const confirmation = resolveConfirmResult(
125
+ message,
126
+ onConfirm,
127
+ (value) => window.confirm(value)
128
+ );
129
+ if (confirmation.kind === "sync" && !confirmation.confirmed) {
130
+ router$1.events.emit("routeChangeError");
131
+ throw new Error(ROUTE_ERRORS.ABORTED);
132
+ }
133
+ if (confirmation.kind === "sync") {
134
+ onAllow?.();
135
+ return;
136
+ }
137
+ router$1.events.emit("routeChangeError");
138
+ confirmation.promise.then((confirmed) => {
139
+ if (confirmed) {
140
+ allowNextUrlRef.current = url;
141
+ onAllow?.();
142
+ void router$1.push(url);
143
+ }
144
+ }).catch(() => {
145
+ });
146
+ throw new Error(ROUTE_ERRORS.ABORTED);
147
+ };
148
+ router$1.events.on("routeChangeStart", handleRouteChangeStart);
149
+ return () => {
150
+ router$1.events.off("routeChangeStart", handleRouteChangeStart);
151
+ };
152
+ }, [shouldBlock, message, onBlock, onAllow, router$1, onConfirm]);
153
+ useBeforeUnload(blockBrowserUnload && shouldBlock, message ?? DEFAULT_UNLOAD_MESSAGE);
154
+ return {
155
+ isBlocking: shouldBlock
156
+ };
157
+ }
158
+ function useNavigationBlocker2(options) {
159
+ const { when, scope, message, blockBrowserUnload = true } = options;
160
+ const shouldBlock = useShouldBlock(when, scope);
161
+ react.useEffect(() => {
162
+ if (process.env.NODE_ENV === "development" && shouldBlock) {
163
+ console.warn(
164
+ "[react-action-guard-router] App Router has limited blocking support. Link clicks cannot be blocked. Use Pages Router for full support."
165
+ );
166
+ }
167
+ }, [shouldBlock]);
168
+ useBeforeUnload(blockBrowserUnload && shouldBlock, message ?? DEFAULT_UNLOAD_MESSAGE);
169
+ return {
170
+ isBlocking: shouldBlock
171
+ };
172
+ }
173
+
174
+ exports.useAppRouterBlocker = useNavigationBlocker2;
175
+ exports.useNavigationBlocker = useNavigationBlocker;
176
+ exports.usePagesRouterBlocker = useNavigationBlocker;
177
+ //# sourceMappingURL=index.cjs.map
178
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +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,EAA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M;AACX,MAAAA,QAAA,CAAO,MAAA,CAAO,GAAA,CAAI,kBAAA,EAAoB,sBAAsB,CAAA;AAAA,IAC9D,CAAA;AAAA,EACF,CAAA,EAAG,CAAC,WAAA,EAAa,OAAA,EAAS,SAAS,OAAA,EAASA,QAAA,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;ACxFO,SAASE,sBACd,OAAA,EACyB;AACzB,EAAA,MAAM,EAAE,IAAA,EAAM,KAAA,EAAO,OAAA,EAAS,kBAAA,GAAqB,MAAK,GAAI,OAAA;AAG5D,EAAA,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 { UseNavigationBlockerOptions } from \"./types\";\nimport type { NavigationBlockerReturn } from \"../core/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 { UseNavigationBlockerOptions } from \"./types\";\nimport type { NavigationBlockerReturn } from \"../core/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"]}