@judo/guards 0.1.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 ADDED
@@ -0,0 +1,277 @@
1
+ Eclipse Public License - v 2.0
2
+
3
+ THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE
4
+ PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION
5
+ OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
6
+
7
+ 1. DEFINITIONS
8
+
9
+ "Contribution" means:
10
+
11
+ a) in the case of the initial Contributor, the initial content
12
+ Distributed under this Agreement, and
13
+
14
+ b) in the case of each subsequent Contributor:
15
+ i) changes to the Program, and
16
+ ii) additions to the Program;
17
+ where such changes and/or additions to the Program originate from
18
+ and are Distributed by that particular Contributor. A Contribution
19
+ "originates" from a Contributor if it was added to the Program by
20
+ such Contributor itself or anyone acting on such Contributor's behalf.
21
+ Contributions do not include changes or additions to the Program that
22
+ are not Modified Works.
23
+
24
+ "Contributor" means any person or entity that Distributes the Program.
25
+
26
+ "Licensed Patents" mean patent claims licensable by a Contributor which
27
+ are necessarily infringed by the use or sale of its Contribution alone
28
+ or when combined with the Program.
29
+
30
+ "Program" means the Contributions Distributed in accordance with this
31
+ Agreement.
32
+
33
+ "Recipient" means anyone who receives the Program under this Agreement
34
+ or any Secondary License (as applicable), including Contributors.
35
+
36
+ "Derivative Works" shall mean any work, whether in Source Code or other
37
+ form, that is based on (or derived from) the Program and for which the
38
+ editorial revisions, annotations, elaborations, or other modifications
39
+ represent, as a whole, an original work of authorship.
40
+
41
+ "Modified Works" shall mean any work in Source Code or other form that
42
+ results from an addition to, deletion from, or modification of the
43
+ contents of the Program, including, for purposes of clarity any new file
44
+ in Source Code form that contains any contents of the Program. Modified
45
+ Works shall not include works that contain only declarations,
46
+ interfaces, types, classes, structures, or files of the Program solely
47
+ in each case in order to link to, bind by name, or subclass the Program
48
+ or Modified Works thereof.
49
+
50
+ "Distribute" means the acts of a) distributing or b) making available
51
+ in any manner that enables the transfer of a copy.
52
+
53
+ "Source Code" means the form of a Program preferred for making
54
+ modifications, including but not limited to software source code,
55
+ documentation source, and configuration files.
56
+
57
+ "Secondary License" means either the GNU General Public License,
58
+ Version 2.0, or any later versions of that license, including any
59
+ exceptions or additional permissions as identified by the initial
60
+ Contributor.
61
+
62
+ 2. GRANT OF RIGHTS
63
+
64
+ a) Subject to the terms of this Agreement, each Contributor hereby
65
+ grants Recipient a non-exclusive, worldwide, royalty-free copyright
66
+ license to reproduce, prepare Derivative Works of, publicly display,
67
+ publicly perform, Distribute and sublicense the Contribution of such
68
+ Contributor, if any, and such Derivative Works.
69
+
70
+ b) Subject to the terms of this Agreement, each Contributor hereby
71
+ grants Recipient a non-exclusive, worldwide, royalty-free patent
72
+ license under Licensed Patents to make, use, sell, offer to sell,
73
+ import and otherwise transfer the Contribution of such Contributor,
74
+ if any, in Source Code or other form. This patent license shall
75
+ apply to the combination of the Contribution and the Program if, at
76
+ the time the Contribution is added by the Contributor, such addition
77
+ of the Contribution causes such combination to be covered by the
78
+ Licensed Patents. The patent license shall not apply to any other
79
+ combinations which include the Contribution. No hardware per se is
80
+ licensed hereunder.
81
+
82
+ c) Recipient understands that although each Contributor grants the
83
+ licenses to its Contributions set forth herein, no assurances are
84
+ provided by any Contributor that the Program does not infringe the
85
+ patent or other intellectual property rights of any other entity.
86
+ Each Contributor disclaims any liability to Recipient for claims
87
+ brought by any other entity based on infringement of intellectual
88
+ property rights or otherwise. As a condition to exercising the
89
+ rights and licenses granted hereunder, each Recipient hereby
90
+ assumes sole responsibility to secure any other intellectual
91
+ property rights needed, if any. For example, if a third party
92
+ patent license is required to allow Recipient to Distribute the
93
+ Program, it is Recipient's responsibility to acquire that license
94
+ before distributing the Program.
95
+
96
+ d) Each Contributor represents that to its knowledge it has
97
+ sufficient copyright rights in its Contribution, if any, to grant
98
+ the copyright license set forth in this Agreement.
99
+
100
+ e) Notwithstanding the terms of any Secondary License, no
101
+ Contributor makes additional grants to any Recipient (other than
102
+ those set forth in this Agreement) as a result of such Recipient's
103
+ receipt of the Program under the terms of a Secondary License
104
+ (if permitted under the terms of Section 3).
105
+
106
+ 3. REQUIREMENTS
107
+
108
+ 3.1 If a Contributor Distributes the Program in any form, then:
109
+
110
+ a) the Program must also be made available as Source Code, in
111
+ accordance with section 3.2, and the Contributor must accompany
112
+ the Program with a statement that the Source Code for the Program
113
+ is available under this Agreement, and informs Recipients how to
114
+ obtain it in a reasonable manner on or through a medium customarily
115
+ used for software exchange; and
116
+
117
+ b) the Contributor may Distribute the Program under a license
118
+ different than this Agreement, provided that such license:
119
+ i) effectively disclaims on behalf of all other Contributors all
120
+ warranties and conditions, express and implied, including
121
+ warranties or conditions of title and non-infringement, and
122
+ implied warranties or conditions of merchantability and fitness
123
+ for a particular purpose;
124
+
125
+ ii) effectively excludes on behalf of all other Contributors all
126
+ liability for damages, including direct, indirect, special,
127
+ incidental and consequential damages, such as lost profits;
128
+
129
+ iii) does not attempt to limit or alter the recipients' rights
130
+ in the Source Code under section 3.2; and
131
+
132
+ iv) requires any subsequent distribution of the Program by any
133
+ party to be under a license that satisfies the requirements
134
+ of this section 3.
135
+
136
+ 3.2 When the Program is Distributed as Source Code:
137
+
138
+ a) it must be made available under this Agreement, or if the
139
+ Program (i) is combined with other material in a separate file or
140
+ files made available under a Secondary License, and (ii) the initial
141
+ Contributor attached to the Source Code the notice described in
142
+ Exhibit A of this Agreement, then the Program may be made available
143
+ under the terms of such Secondary Licenses, and
144
+
145
+ b) a copy of this Agreement must be included with each copy of
146
+ the Program.
147
+
148
+ 3.3 Contributors may not remove or alter any copyright, patent,
149
+ trademark, attribution notices, disclaimers of warranty, or limitations
150
+ of liability ("notices") contained within the Program from any copy of
151
+ the Program which they Distribute, provided that Contributors may add
152
+ their own appropriate notices.
153
+
154
+ 4. COMMERCIAL DISTRIBUTION
155
+
156
+ Commercial distributors of software may accept certain responsibilities
157
+ with respect to end users, business partners and the like. While this
158
+ license is intended to facilitate the commercial use of the Program,
159
+ the Contributor who includes the Program in a commercial product
160
+ offering should do so in a manner which does not create potential
161
+ liability for other Contributors. Therefore, if a Contributor includes
162
+ the Program in a commercial product offering, such Contributor
163
+ ("Commercial Contributor") hereby agrees to defend and indemnify every
164
+ other Contributor ("Indemnified Contributor") against any losses,
165
+ damages and costs (collectively "Losses") arising from claims, lawsuits
166
+ and other legal actions brought by a third party against the Indemnified
167
+ Contributor to the extent caused by the acts or omissions of such
168
+ Commercial Contributor in connection with its distribution of the Program
169
+ in a commercial product offering. The obligations in this section do not
170
+ apply to any claims or Losses relating to any actual or alleged
171
+ intellectual property infringement. In order to qualify, an Indemnified
172
+ Contributor must: a) promptly notify the Commercial Contributor in
173
+ writing of such claim, and b) allow the Commercial Contributor to control,
174
+ and cooperate with the Commercial Contributor in, the defense and any
175
+ related settlement negotiations. The Indemnified Contributor may
176
+ participate in any such claim at its own expense.
177
+
178
+ For example, a Contributor might include the Program in a commercial
179
+ product offering, Product X. That Contributor is then a Commercial
180
+ Contributor. If that Commercial Contributor then makes performance
181
+ claims, or offers warranties related to Product X, those performance
182
+ claims and warranties are such Commercial Contributor's responsibility
183
+ alone. Under this section, the Commercial Contributor would have to
184
+ defend claims against the other Contributors related to those performance
185
+ claims and warranties, and if a court requires any other Contributor to
186
+ pay any damages as a result, the Commercial Contributor must pay
187
+ those damages.
188
+
189
+ 5. NO WARRANTY
190
+
191
+ EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT
192
+ PERMITTED BY APPLICABLE LAW, THE PROGRAM IS PROVIDED ON AN "AS IS"
193
+ BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR
194
+ IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF
195
+ TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR
196
+ PURPOSE. Each Recipient is solely responsible for determining the
197
+ appropriateness of using and distributing the Program and assumes all
198
+ risks associated with its exercise of rights under this Agreement,
199
+ including but not limited to the risks and costs of program errors,
200
+ compliance with applicable laws, damage to or loss of data, programs
201
+ or equipment, and unavailability or interruption of operations.
202
+
203
+ 6. DISCLAIMER OF LIABILITY
204
+
205
+ EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT
206
+ PERMITTED BY APPLICABLE LAW, NEITHER RECIPIENT NOR ANY CONTRIBUTORS
207
+ SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
208
+ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST
209
+ PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
210
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
211
+ ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE
212
+ EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE
213
+ POSSIBILITY OF SUCH DAMAGES.
214
+
215
+ 7. GENERAL
216
+
217
+ If any provision of this Agreement is invalid or unenforceable under
218
+ applicable law, it shall not affect the validity or enforceability of
219
+ the remainder of the terms of this Agreement, and without further
220
+ action by the parties hereto, such provision shall be reformed to the
221
+ minimum extent necessary to make such provision valid and enforceable.
222
+
223
+ If Recipient institutes patent litigation against any entity
224
+ (including a cross-claim or counterclaim in a lawsuit) alleging that the
225
+ Program itself (excluding combinations of the Program with other software
226
+ or hardware) infringes such Recipient's patent(s), then such Recipient's
227
+ rights granted under Section 2(b) shall terminate as of the date such
228
+ litigation is filed.
229
+
230
+ All Recipient's rights under this Agreement shall terminate if it
231
+ fails to comply with any of the material terms or conditions of this
232
+ Agreement and does not cure such failure in a reasonable period of
233
+ time after becoming aware of such noncompliance. If all Recipient's
234
+ rights under this Agreement terminate, Recipient agrees to cease use
235
+ and distribution of the Program as soon as reasonably practicable.
236
+ However, Recipient's obligations under this Agreement and any licenses
237
+ granted by Recipient relating to the Program shall continue and survive.
238
+
239
+ Everyone is permitted to copy and distribute copies of this Agreement,
240
+ but in order to avoid inconsistency the Agreement is copyrighted and
241
+ may only be modified in the following manner. The Agreement Steward
242
+ reserves the right to publish new versions (including revisions) of
243
+ this Agreement from time to time. No one other than the Agreement
244
+ Steward has the right to modify this Agreement. The Eclipse Foundation
245
+ is the initial Agreement Steward. The Eclipse Foundation may assign the
246
+ responsibility to serve as the Agreement Steward to a suitable separate
247
+ entity. Each new version of the Agreement will be given a distinguishing
248
+ version number. The Program (including Contributions) may always be
249
+ Distributed subject to the version of the Agreement under which it was
250
+ received. In addition, after a new version of the Agreement is published,
251
+ Contributor may elect to Distribute the Program (including its
252
+ Contributions) under the new version.
253
+
254
+ Except as expressly stated in Sections 2(a) and 2(b) above, Recipient
255
+ receives no rights or licenses to the intellectual property of any
256
+ Contributor under this Agreement, whether expressly, by implication,
257
+ estoppel or otherwise. All rights in the Program not expressly granted
258
+ under this Agreement are reserved. Nothing in this Agreement is intended
259
+ to be enforceable by any entity that is not a Contributor or Recipient.
260
+ No third-party beneficiary rights are created under this Agreement.
261
+
262
+ Exhibit A - Form of Secondary Licenses Notice
263
+
264
+ "This Source Code may also be made available under the following
265
+ Secondary Licenses when the conditions for such availability set forth
266
+ in the Eclipse Public License, v. 2.0 are satisfied: {name license(s),
267
+ version(s), and exceptions or additional permissions here}."
268
+
269
+ Simply including a copy of this Agreement, including this Exhibit A
270
+ is not sufficient to license the Source Code under Secondary Licenses.
271
+
272
+ If it is not possible or desirable to put the notice in a particular
273
+ file, then You may include the notice in a location (such as a LICENSE
274
+ file in a relevant directory) where a recipient would be likely to
275
+ look for such a notice.
276
+
277
+ You may add additional accurate notices of copyright ownership.
package/README.md ADDED
@@ -0,0 +1,89 @@
1
+ # @judo/guards
2
+
3
+ > Navigation guards for JUDO UI Runtime
4
+
5
+ ## Purpose
6
+
7
+ Provides two runtime guard mechanisms:
8
+
9
+ 1. **Unsaved Changes Guard** — prevents navigation away from dirty forms, with browser `beforeunload` support
10
+ 2. **Session Timeout Guard** — monitors user inactivity, shows a warning dialog before session expiry, and forces logout on timeout
11
+
12
+ ## Architecture Layer
13
+
14
+ **Layer 4 (Features)** — consumed by `app-shell` and `core` for navigation protection.
15
+
16
+ ## Dependencies
17
+
18
+ - `@judo/model-api` — model type definitions (peer)
19
+ - `@judo/feedback` — dialog service for confirmation dialogs (peer)
20
+ - `@mui/material ^7` — MUI components for session timeout dialog (peer)
21
+ - `react ^19` — React (peer)
22
+ - `react-router ^7` — routing (peer)
23
+
24
+ ## File Structure
25
+
26
+ ```
27
+ src/
28
+ ├── index.ts # Barrel re-exports
29
+ ├── unsaved-changes/
30
+ │ ├── unsaved-changes-guard.ts # Interface + class
31
+ │ ├── use-unsaved-changes-guard.ts # React hook
32
+ │ ├── unsaved-changes-guard.test.ts
33
+ │ └── use-unsaved-changes-guard.test.tsx
34
+ └── session-timeout/
35
+ ├── session-timeout-guard.ts # Interface + config + class
36
+ ├── session-timeout-dialog.tsx # React component
37
+ ├── session-timeout-guard.test.tsx
38
+ └── session-timeout-dialog.test.tsx
39
+ ```
40
+
41
+ ## Exports Summary
42
+
43
+ ### Unsaved Changes Guard
44
+
45
+ | Export | Kind | Description |
46
+ | ---------------------------------------- | --------- | ----------------------------------------------------------------------------------------------------------- |
47
+ | `UnsavedChangesGuard` | interface | Interface for managing unsaved-changes warnings across multiple forms/pages. |
48
+ | `UnsavedChangesGuardImpl` | class | Concrete implementation. Stores dirty-checkers in a `Map`. Uses `DialogService` for confirmation. |
49
+ | `useUnsavedChangesGuard(guard, isDirty)` | hook | Registers the component with the guard when dirty. Attaches browser `beforeunload` handler. Auto-cleans up. |
50
+
51
+ **`UnsavedChangesGuard` methods:**
52
+
53
+ | Method | Returns | Description |
54
+ | ----------------------- | ------------------ | ---------------------------------------------------------------------------- |
55
+ | `hasUnsavedChanges()` | `boolean` | Iterates all registered dirty-checkers; returns `true` if any is dirty. |
56
+ | `register(id, isDirty)` | `() => void` | Registers a form/page by ID with a dirty callback. Returns cleanup function. |
57
+ | `unregister(id)` | `void` | Removes a previously registered dirty-checker. |
58
+ | `confirmNavigation()` | `Promise<boolean>` | If dirty, shows a confirm dialog; resolves `true` if user chooses to leave. |
59
+
60
+ ### Session Timeout Guard
61
+
62
+ | Export | Kind | Description |
63
+ | --------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------ |
64
+ | `SessionTimeoutGuard` | interface | Interface for monitoring user inactivity and triggering timeout flows. |
65
+ | `SessionTimeoutConfig` | interface | Configuration: `timeoutMs?` (default: 30 min), `warningMs?` (default: 5 min), `onTimeout?`, `onWarning?`. All fields optional. |
66
+ | `SessionTimeoutGuardImpl` | class | Implementation with timer cascade and DOM activity listeners. |
67
+ | `SessionTimeoutDialog` | component | MUI Dialog showing either "Session Expiring" (with continue/logout) or "Session Expired" (with login). |
68
+ | `SessionTimeoutDialogProps` | interface | Props: `guard`, `onLogout`. |
69
+
70
+ **`SessionTimeoutGuard` methods:**
71
+
72
+ | Method | Returns | Description |
73
+ | --------------------- | ------------ | ---------------------------------------------------------------------------------------------------------------- |
74
+ | `start()` | `void` | Begins monitoring; attaches DOM listeners (`mousedown`, `keydown`, `scroll`, `touchstart`) and schedules timers. |
75
+ | `stop()` | `void` | Clears timers, detaches listeners, resets state, notifies subscribers. |
76
+ | `resetActivity()` | `void` | Resets inactivity timer (no-op if already timed out). |
77
+ | `isTimedOut()` | `boolean` | Returns current timed-out state. |
78
+ | `subscribe(listener)` | `() => void` | Subscribes to `(isWarning, isTimedOut)` state changes; returns unsubscribe function. |
79
+
80
+ ## Key Patterns
81
+
82
+ - **Interface + Impl class**: Both guards define an interface and a separate `*Impl` class, enabling DI and testability
83
+ - **Manual pub/sub**: `SessionTimeoutGuardImpl` uses a `Set<listener>` with `subscribe` returning unsubscribe — compatible with `useSyncExternalStore`
84
+ - **`useSyncExternalStore`**: `SessionTimeoutDialog` bridges the imperative guard to React's concurrent-safe external store API
85
+ - **`useId` for registration**: `useUnsavedChangesGuard` uses React 18+ `useId` for a stable, unique registration key
86
+ - **Browser `beforeunload`**: The unsaved-changes hook traps browser-level navigation (tab close, refresh)
87
+ - **Timer cascade**: Session timeout uses a two-phase timer: `scheduleWarning()` fires first (at `timeoutMs - warningMs`), then chains to `scheduleTimeout()` which fires after the remaining `warningMs` window. On timeout, activity listeners are detached.
88
+ - **No React context/provider**: Guards are plain classes passed as props or hook arguments — no provider in this package
89
+ - **Dependency on `@judo/feedback`**: `UnsavedChangesGuardImpl` takes a `DialogService` for confirmation dialogs
@@ -0,0 +1,3 @@
1
+ export { type UnsavedChangesGuard, UnsavedChangesGuardImpl, useUnsavedChangesGuard } from './unsaved-changes';
2
+ export { type SessionTimeoutGuard, type SessionTimeoutConfig, SessionTimeoutGuardImpl, SessionTimeoutDialog, type SessionTimeoutDialogProps, } from './session-timeout';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,mBAAmB,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AAG9G,OAAO,EACN,KAAK,mBAAmB,EACxB,KAAK,oBAAoB,EACzB,uBAAuB,EACvB,oBAAoB,EACpB,KAAK,yBAAyB,GAC9B,MAAM,mBAAmB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,156 @@
1
+ import { useCallback, useEffect, useId, useState, useSyncExternalStore } from "react";
2
+ import Button from "@mui/material/Button";
3
+ import Dialog from "@mui/material/Dialog";
4
+ import DialogActions from "@mui/material/DialogActions";
5
+ import DialogContent from "@mui/material/DialogContent";
6
+ import DialogContentText from "@mui/material/DialogContentText";
7
+ import DialogTitle from "@mui/material/DialogTitle";
8
+ import { jsx, jsxs } from "react/jsx-runtime";
9
+ var UnsavedChangesGuardImpl = class {
10
+ dirtyCheckers = /* @__PURE__ */ new Map();
11
+ dialogService;
12
+ constructor(e) {
13
+ this.dialogService = e;
14
+ }
15
+ hasUnsavedChanges() {
16
+ for (let [, e] of this.dirtyCheckers) if (e()) return !0;
17
+ return !1;
18
+ }
19
+ register(e, l) {
20
+ return this.dirtyCheckers.set(e, l), () => this.unregister(e);
21
+ }
22
+ unregister(e) {
23
+ this.dirtyCheckers.delete(e);
24
+ }
25
+ async confirmNavigation() {
26
+ return this.hasUnsavedChanges() ? this.dialogService.confirm({
27
+ title: "Unsaved Changes",
28
+ message: "You have unsaved changes. Are you sure you want to leave?",
29
+ confirmText: "Leave",
30
+ cancelText: "Stay",
31
+ destructive: !0
32
+ }) : !0;
33
+ }
34
+ };
35
+ function useUnsavedChangesGuard(e, d) {
36
+ let f = useId();
37
+ useEffect(() => {
38
+ if (d) return e.register(f, () => d);
39
+ }, [
40
+ d,
41
+ e,
42
+ f
43
+ ]), useEffect(() => {
44
+ if (!d) return;
45
+ let e = (e) => {
46
+ e.preventDefault();
47
+ };
48
+ return window.addEventListener("beforeunload", e), () => window.removeEventListener("beforeunload", e);
49
+ }, [d]);
50
+ }
51
+ var DEFAULT_TIMEOUT_MS = 1800 * 1e3, DEFAULT_WARNING_MS = 300 * 1e3, SessionTimeoutGuardImpl = class {
52
+ config;
53
+ timeoutId = null;
54
+ warningTimeoutId = null;
55
+ lastActivity = Date.now();
56
+ isWarningState = !1;
57
+ isTimedOutState = !1;
58
+ listeners = /* @__PURE__ */ new Set();
59
+ activityEvents = [
60
+ "mousedown",
61
+ "keydown",
62
+ "scroll",
63
+ "touchstart"
64
+ ];
65
+ boundResetActivity;
66
+ constructor(e = {}) {
67
+ this.config = {
68
+ timeoutMs: e.timeoutMs ?? DEFAULT_TIMEOUT_MS,
69
+ warningMs: e.warningMs ?? DEFAULT_WARNING_MS,
70
+ onTimeout: e.onTimeout ?? (() => {}),
71
+ onWarning: e.onWarning ?? (() => {})
72
+ }, this.boundResetActivity = this.resetActivity.bind(this);
73
+ }
74
+ start() {
75
+ this.lastActivity = Date.now(), this.isWarningState = !1, this.isTimedOutState = !1, this.scheduleWarning(), this.attachActivityListeners();
76
+ }
77
+ stop() {
78
+ this.clearTimers(), this.detachActivityListeners(), this.isWarningState = !1, this.isTimedOutState = !1, this.notifyListeners();
79
+ }
80
+ resetActivity() {
81
+ this.isTimedOutState || (this.lastActivity = Date.now(), this.isWarningState = !1, this.clearTimers(), this.scheduleWarning(), this.notifyListeners());
82
+ }
83
+ isTimedOut() {
84
+ return this.isTimedOutState;
85
+ }
86
+ subscribe(e) {
87
+ return this.listeners.add(e), () => this.listeners.delete(e);
88
+ }
89
+ scheduleWarning() {
90
+ let e = this.config.timeoutMs - this.config.warningMs;
91
+ this.warningTimeoutId = setTimeout(() => {
92
+ this.isWarningState = !0, this.config.onWarning(), this.notifyListeners(), this.scheduleTimeout();
93
+ }, e);
94
+ }
95
+ scheduleTimeout() {
96
+ this.timeoutId = setTimeout(() => {
97
+ this.isTimedOutState = !0, this.config.onTimeout(), this.detachActivityListeners(), this.notifyListeners();
98
+ }, this.config.warningMs);
99
+ }
100
+ clearTimers() {
101
+ this.timeoutId &&= (clearTimeout(this.timeoutId), null), this.warningTimeoutId &&= (clearTimeout(this.warningTimeoutId), null);
102
+ }
103
+ attachActivityListeners() {
104
+ for (let e of this.activityEvents) window.addEventListener(e, this.boundResetActivity, { passive: !0 });
105
+ }
106
+ detachActivityListeners() {
107
+ for (let e of this.activityEvents) window.removeEventListener(e, this.boundResetActivity);
108
+ }
109
+ notifyListeners() {
110
+ for (let e of this.listeners) e(this.isWarningState, this.isTimedOutState);
111
+ }
112
+ };
113
+ function SessionTimeoutDialog({ guard: u, onLogout: p }) {
114
+ let m = useCallback((e) => u.subscribe(() => e()), [u]), h = useCallback(() => u.isTimedOut(), [u]), g = useSyncExternalStore(m, h, h), [_, v] = useState(!1);
115
+ useEffect(() => u.subscribe((e, l) => {
116
+ v(e && !l);
117
+ }), [u]);
118
+ let y = () => {
119
+ u.resetActivity();
120
+ }, b = () => {
121
+ u.stop(), p();
122
+ };
123
+ return _ && !g ? /* @__PURE__ */ jsxs(Dialog, {
124
+ open: !0,
125
+ "data-testid": "session-timeout-warning-dialog",
126
+ children: [
127
+ /* @__PURE__ */ jsx(DialogTitle, { children: "Session Expiring" }),
128
+ /* @__PURE__ */ jsx(DialogContent, { children: /* @__PURE__ */ jsx(DialogContentText, { children: "Your session is about to expire due to inactivity. Would you like to continue?" }) }),
129
+ /* @__PURE__ */ jsxs(DialogActions, { children: [/* @__PURE__ */ jsx(Button, {
130
+ onClick: b,
131
+ "data-testid": "session-timeout-logout-button",
132
+ children: "Log Out"
133
+ }), /* @__PURE__ */ jsx(Button, {
134
+ onClick: y,
135
+ variant: "contained",
136
+ autoFocus: !0,
137
+ "data-testid": "session-timeout-continue-button",
138
+ children: "Continue Session"
139
+ })] })
140
+ ]
141
+ }) : g ? /* @__PURE__ */ jsxs(Dialog, {
142
+ open: !0,
143
+ "data-testid": "session-timeout-dialog",
144
+ children: [
145
+ /* @__PURE__ */ jsx(DialogTitle, { children: "Session Expired" }),
146
+ /* @__PURE__ */ jsx(DialogContent, { children: /* @__PURE__ */ jsx(DialogContentText, { children: "Your session has expired. Please log in again to continue." }) }),
147
+ /* @__PURE__ */ jsx(DialogActions, { children: /* @__PURE__ */ jsx(Button, {
148
+ onClick: b,
149
+ variant: "contained",
150
+ "data-testid": "session-timeout-login-button",
151
+ children: "Log In"
152
+ }) })
153
+ ]
154
+ }) : null;
155
+ }
156
+ export { SessionTimeoutDialog, SessionTimeoutGuardImpl, UnsavedChangesGuardImpl, useUnsavedChangesGuard };
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/unsaved-changes/unsaved-changes-guard.ts","../src/unsaved-changes/use-unsaved-changes-guard.ts","../src/session-timeout/session-timeout-guard.ts","../src/session-timeout/session-timeout-dialog.tsx"],"sourcesContent":["import type { DialogService } from \"@judo/feedback\";\n\n/**\n * UnsavedChangesGuard interface for managing unsaved changes warnings.\n */\nexport interface UnsavedChangesGuard {\n\t/** Check if there are unsaved changes */\n\thasUnsavedChanges(): boolean;\n\n\t/** Register a form/page with unsaved changes check */\n\tregister(id: string, isDirty: () => boolean): () => void;\n\n\t/** Unregister a form/page */\n\tunregister(id: string): void;\n\n\t/** Prompt user and return true if navigation allowed */\n\tconfirmNavigation(): Promise<boolean>;\n}\n\n/**\n * Implementation of UnsavedChangesGuard.\n */\nexport class UnsavedChangesGuardImpl implements UnsavedChangesGuard {\n\tprivate dirtyCheckers = new Map<string, () => boolean>();\n\tprivate dialogService: DialogService;\n\n\tconstructor(dialogService: DialogService) {\n\t\tthis.dialogService = dialogService;\n\t}\n\n\thasUnsavedChanges(): boolean {\n\t\tfor (const [, isDirty] of this.dirtyCheckers) {\n\t\t\tif (isDirty()) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tregister(id: string, isDirty: () => boolean): () => void {\n\t\tthis.dirtyCheckers.set(id, isDirty);\n\t\treturn () => this.unregister(id);\n\t}\n\n\tunregister(id: string): void {\n\t\tthis.dirtyCheckers.delete(id);\n\t}\n\n\tasync confirmNavigation(): Promise<boolean> {\n\t\tif (!this.hasUnsavedChanges()) {\n\t\t\treturn true;\n\t\t}\n\n\t\treturn this.dialogService.confirm({\n\t\t\ttitle: \"Unsaved Changes\",\n\t\t\tmessage: \"You have unsaved changes. Are you sure you want to leave?\",\n\t\t\tconfirmText: \"Leave\",\n\t\t\tcancelText: \"Stay\",\n\t\t\tdestructive: true,\n\t\t});\n\t}\n}\n","import { useEffect, useId } from \"react\";\nimport type { UnsavedChangesGuard } from \"./unsaved-changes-guard\";\n\n/**\n * Hook to register unsaved changes for a form/page.\n */\nexport function useUnsavedChangesGuard(guard: UnsavedChangesGuard, isDirty: boolean) {\n\tconst id = useId();\n\n\t// Register with guard when dirty\n\tuseEffect(() => {\n\t\tif (isDirty) {\n\t\t\treturn guard.register(id, () => isDirty);\n\t\t}\n\t\treturn undefined;\n\t}, [isDirty, guard, id]);\n\n\t// Handle browser beforeunload\n\tuseEffect(() => {\n\t\tif (!isDirty) return;\n\n\t\tconst handleBeforeUnload = (e: BeforeUnloadEvent) => {\n\t\t\te.preventDefault();\n\t\t};\n\n\t\twindow.addEventListener(\"beforeunload\", handleBeforeUnload);\n\t\treturn () => window.removeEventListener(\"beforeunload\", handleBeforeUnload);\n\t}, [isDirty]);\n}\n","/**\n * SessionTimeoutGuard interface for managing session timeout warnings.\n */\nexport interface SessionTimeoutGuard {\n\t/** Start monitoring for session timeout */\n\tstart(): void;\n\n\t/** Stop monitoring */\n\tstop(): void;\n\n\t/** Reset activity timer (called on user activity) */\n\tresetActivity(): void;\n\n\t/** Check if session is timed out */\n\tisTimedOut(): boolean;\n\n\t/** Subscribe to timeout state changes */\n\tsubscribe(listener: (isWarning: boolean, isTimedOut: boolean) => void): () => void;\n}\n\nexport interface SessionTimeoutConfig {\n\t/** Timeout duration in milliseconds (default: 30 minutes) */\n\ttimeoutMs?: number;\n\t/** Warning before timeout in milliseconds (default: 5 minutes) */\n\twarningMs?: number;\n\t/** Callback when session times out */\n\tonTimeout?: () => void;\n\t/** Callback when warning period starts */\n\tonWarning?: () => void;\n}\n\nconst DEFAULT_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes\nconst DEFAULT_WARNING_MS = 5 * 60 * 1000; // 5 minutes\n\n/**\n * Implementation of SessionTimeoutGuard.\n */\nexport class SessionTimeoutGuardImpl implements SessionTimeoutGuard {\n\tprivate config: Required<SessionTimeoutConfig>;\n\tprivate timeoutId: ReturnType<typeof setTimeout> | null = null;\n\tprivate warningTimeoutId: ReturnType<typeof setTimeout> | null = null;\n\tprivate lastActivity: number = Date.now();\n\tprivate isWarningState = false;\n\tprivate isTimedOutState = false;\n\tprivate listeners = new Set<(isWarning: boolean, isTimedOut: boolean) => void>();\n\tprivate activityEvents = [\"mousedown\", \"keydown\", \"scroll\", \"touchstart\"];\n\tprivate boundResetActivity: () => void;\n\n\tconstructor(config: SessionTimeoutConfig = {}) {\n\t\tthis.config = {\n\t\t\ttimeoutMs: config.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n\t\t\twarningMs: config.warningMs ?? DEFAULT_WARNING_MS,\n\t\t\tonTimeout: config.onTimeout ?? (() => {}),\n\t\t\tonWarning: config.onWarning ?? (() => {}),\n\t\t};\n\t\tthis.boundResetActivity = this.resetActivity.bind(this);\n\t}\n\n\tstart(): void {\n\t\tthis.lastActivity = Date.now();\n\t\tthis.isWarningState = false;\n\t\tthis.isTimedOutState = false;\n\t\tthis.scheduleWarning();\n\t\tthis.attachActivityListeners();\n\t}\n\n\tstop(): void {\n\t\tthis.clearTimers();\n\t\tthis.detachActivityListeners();\n\t\tthis.isWarningState = false;\n\t\tthis.isTimedOutState = false;\n\t\tthis.notifyListeners();\n\t}\n\n\tresetActivity(): void {\n\t\tif (this.isTimedOutState) return;\n\n\t\tthis.lastActivity = Date.now();\n\t\tthis.isWarningState = false;\n\t\tthis.clearTimers();\n\t\tthis.scheduleWarning();\n\t\tthis.notifyListeners();\n\t}\n\n\tisTimedOut(): boolean {\n\t\treturn this.isTimedOutState;\n\t}\n\n\tsubscribe(listener: (isWarning: boolean, isTimedOut: boolean) => void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => this.listeners.delete(listener);\n\t}\n\n\tprivate scheduleWarning(): void {\n\t\tconst warningTime = this.config.timeoutMs - this.config.warningMs;\n\t\tthis.warningTimeoutId = setTimeout(() => {\n\t\t\tthis.isWarningState = true;\n\t\t\tthis.config.onWarning();\n\t\t\tthis.notifyListeners();\n\t\t\tthis.scheduleTimeout();\n\t\t}, warningTime);\n\t}\n\n\tprivate scheduleTimeout(): void {\n\t\tthis.timeoutId = setTimeout(() => {\n\t\t\tthis.isTimedOutState = true;\n\t\t\tthis.config.onTimeout();\n\t\t\tthis.detachActivityListeners();\n\t\t\tthis.notifyListeners();\n\t\t}, this.config.warningMs);\n\t}\n\n\tprivate clearTimers(): void {\n\t\tif (this.timeoutId) {\n\t\t\tclearTimeout(this.timeoutId);\n\t\t\tthis.timeoutId = null;\n\t\t}\n\t\tif (this.warningTimeoutId) {\n\t\t\tclearTimeout(this.warningTimeoutId);\n\t\t\tthis.warningTimeoutId = null;\n\t\t}\n\t}\n\n\tprivate attachActivityListeners(): void {\n\t\tfor (const event of this.activityEvents) {\n\t\t\twindow.addEventListener(event, this.boundResetActivity, { passive: true });\n\t\t}\n\t}\n\n\tprivate detachActivityListeners(): void {\n\t\tfor (const event of this.activityEvents) {\n\t\t\twindow.removeEventListener(event, this.boundResetActivity);\n\t\t}\n\t}\n\n\tprivate notifyListeners(): void {\n\t\tfor (const listener of this.listeners) {\n\t\t\tlistener(this.isWarningState, this.isTimedOutState);\n\t\t}\n\t}\n}\n","import Button from \"@mui/material/Button\";\nimport Dialog from \"@mui/material/Dialog\";\nimport DialogActions from \"@mui/material/DialogActions\";\nimport DialogContent from \"@mui/material/DialogContent\";\nimport DialogContentText from \"@mui/material/DialogContentText\";\nimport DialogTitle from \"@mui/material/DialogTitle\";\nimport { useCallback, useEffect, useState, useSyncExternalStore } from \"react\";\nimport type { SessionTimeoutGuard } from \"./session-timeout-guard\";\n\nexport interface SessionTimeoutDialogProps {\n\tguard: SessionTimeoutGuard;\n\tonLogout: () => void;\n}\n\n/**\n * Session timeout warning dialog component.\n */\nexport function SessionTimeoutDialog({ guard, onLogout }: SessionTimeoutDialogProps) {\n\t// Track state with refs updated via subscribe\n\tconst subscribe = useCallback(\n\t\t(callback: () => void) => {\n\t\t\treturn guard.subscribe(() => callback());\n\t\t},\n\t\t[guard]\n\t);\n\n\tconst getSnapshot = useCallback(() => {\n\t\treturn guard.isTimedOut();\n\t}, [guard]);\n\n\tconst isTimedOut = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n\t// For warning state, we need to track it via the guard's internal state\n\t// Since there's no isWarning() method, we'll add a separate subscription pattern\n\tconst [isWarning, setIsWarning] = useState(false);\n\n\tuseEffect(() => {\n\t\tconst unsub = guard.subscribe((warning, timedOut) => {\n\t\t\tsetIsWarning(warning && !timedOut);\n\t\t});\n\t\treturn unsub;\n\t}, [guard]);\n\n\tconst handleContinue = () => {\n\t\tguard.resetActivity();\n\t};\n\n\tconst handleLogout = () => {\n\t\tguard.stop();\n\t\tonLogout();\n\t};\n\n\t// Show warning dialog\n\tif (isWarning && !isTimedOut) {\n\t\treturn (\n\t\t\t<Dialog open data-testid=\"session-timeout-warning-dialog\">\n\t\t\t\t<DialogTitle>Session Expiring</DialogTitle>\n\t\t\t\t<DialogContent>\n\t\t\t\t\t<DialogContentText>\n\t\t\t\t\t\tYour session is about to expire due to inactivity. Would you like to continue?\n\t\t\t\t\t</DialogContentText>\n\t\t\t\t</DialogContent>\n\t\t\t\t<DialogActions>\n\t\t\t\t\t<Button onClick={handleLogout} data-testid=\"session-timeout-logout-button\">\n\t\t\t\t\t\tLog Out\n\t\t\t\t\t</Button>\n\t\t\t\t\t{/* oxlint-disable jsx-a11y/no-autofocus */}\n\t\t\t\t\t<Button onClick={handleContinue} variant=\"contained\" autoFocus data-testid=\"session-timeout-continue-button\">\n\t\t\t\t\t\tContinue Session\n\t\t\t\t\t</Button>\n\t\t\t\t\t{/* oxlint-enable jsx-a11y/no-autofocus */}\n\t\t\t\t</DialogActions>\n\t\t\t</Dialog>\n\t\t);\n\t}\n\n\t// Show timeout dialog\n\tif (isTimedOut) {\n\t\treturn (\n\t\t\t<Dialog open data-testid=\"session-timeout-dialog\">\n\t\t\t\t<DialogTitle>Session Expired</DialogTitle>\n\t\t\t\t<DialogContent>\n\t\t\t\t\t<DialogContentText>Your session has expired. Please log in again to continue.</DialogContentText>\n\t\t\t\t</DialogContent>\n\t\t\t\t<DialogActions>\n\t\t\t\t\t<Button onClick={handleLogout} variant=\"contained\" data-testid=\"session-timeout-login-button\">\n\t\t\t\t\t\tLog In\n\t\t\t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;GAChB,oBAAC,eAAA,EAAA,UACA,oBAAC,QAAA;IAAO,SAAS;IAAc,SAAQ;IAAY,eAAY;cAA+B;KAErF,EAAA,CACM;;GACR,GAIJ"}
@@ -0,0 +1,3 @@
1
+ export { type SessionTimeoutGuard, type SessionTimeoutConfig, SessionTimeoutGuardImpl } from './session-timeout-guard';
2
+ export { SessionTimeoutDialog, type SessionTimeoutDialogProps } from './session-timeout-dialog';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/session-timeout/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,mBAAmB,EAAE,KAAK,oBAAoB,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AACvH,OAAO,EAAE,oBAAoB,EAAE,KAAK,yBAAyB,EAAE,MAAM,0BAA0B,CAAC"}
@@ -0,0 +1,10 @@
1
+ import { SessionTimeoutGuard } from './session-timeout-guard';
2
+ export interface SessionTimeoutDialogProps {
3
+ guard: SessionTimeoutGuard;
4
+ onLogout: () => void;
5
+ }
6
+ /**
7
+ * Session timeout warning dialog component.
8
+ */
9
+ export declare function SessionTimeoutDialog({ guard, onLogout }: SessionTimeoutDialogProps): import("react/jsx-runtime").JSX.Element | null;
10
+ //# sourceMappingURL=session-timeout-dialog.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-timeout-dialog.d.ts","sourceRoot":"","sources":["../../src/session-timeout/session-timeout-dialog.tsx"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAEnE,MAAM,WAAW,yBAAyB;IACzC,KAAK,EAAE,mBAAmB,CAAC;IAC3B,QAAQ,EAAE,MAAM,IAAI,CAAC;CACrB;AAED;;GAEG;AACH,wBAAgB,oBAAoB,CAAC,EAAE,KAAK,EAAE,QAAQ,EAAE,EAAE,yBAAyB,kDA6ElF"}
@@ -0,0 +1,52 @@
1
+ /**
2
+ * SessionTimeoutGuard interface for managing session timeout warnings.
3
+ */
4
+ export interface SessionTimeoutGuard {
5
+ /** Start monitoring for session timeout */
6
+ start(): void;
7
+ /** Stop monitoring */
8
+ stop(): void;
9
+ /** Reset activity timer (called on user activity) */
10
+ resetActivity(): void;
11
+ /** Check if session is timed out */
12
+ isTimedOut(): boolean;
13
+ /** Subscribe to timeout state changes */
14
+ subscribe(listener: (isWarning: boolean, isTimedOut: boolean) => void): () => void;
15
+ }
16
+ export interface SessionTimeoutConfig {
17
+ /** Timeout duration in milliseconds (default: 30 minutes) */
18
+ timeoutMs?: number;
19
+ /** Warning before timeout in milliseconds (default: 5 minutes) */
20
+ warningMs?: number;
21
+ /** Callback when session times out */
22
+ onTimeout?: () => void;
23
+ /** Callback when warning period starts */
24
+ onWarning?: () => void;
25
+ }
26
+ /**
27
+ * Implementation of SessionTimeoutGuard.
28
+ */
29
+ export declare class SessionTimeoutGuardImpl implements SessionTimeoutGuard {
30
+ private config;
31
+ private timeoutId;
32
+ private warningTimeoutId;
33
+ private lastActivity;
34
+ private isWarningState;
35
+ private isTimedOutState;
36
+ private listeners;
37
+ private activityEvents;
38
+ private boundResetActivity;
39
+ constructor(config?: SessionTimeoutConfig);
40
+ start(): void;
41
+ stop(): void;
42
+ resetActivity(): void;
43
+ isTimedOut(): boolean;
44
+ subscribe(listener: (isWarning: boolean, isTimedOut: boolean) => void): () => void;
45
+ private scheduleWarning;
46
+ private scheduleTimeout;
47
+ private clearTimers;
48
+ private attachActivityListeners;
49
+ private detachActivityListeners;
50
+ private notifyListeners;
51
+ }
52
+ //# sourceMappingURL=session-timeout-guard.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-timeout-guard.d.ts","sourceRoot":"","sources":["../../src/session-timeout/session-timeout-guard.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,WAAW,mBAAmB;IACnC,2CAA2C;IAC3C,KAAK,IAAI,IAAI,CAAC;IAEd,sBAAsB;I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Ae;CAKvB"}
@@ -0,0 +1,3 @@
1
+ export { type UnsavedChangesGuard, UnsavedChangesGuardImpl } from './unsaved-changes-guard';
2
+ export { useUnsavedChangesGuard } from './use-unsaved-changes-guard';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/unsaved-changes/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,mBAAmB,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAC5F,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC"}
@@ -0,0 +1,27 @@
1
+ import { DialogService } from '@judo/feedback';
2
+ /**
3
+ * UnsavedChangesGuard interface for managing unsaved changes warnings.
4
+ */
5
+ export interface UnsavedChangesGuard {
6
+ /** Check if there are unsaved changes */
7
+ hasUnsavedChanges(): boolean;
8
+ /** Register a form/page with unsaved changes check */
9
+ register(id: string, isDirty: () => boolean): () => void;
10
+ /** Unregister a form/page */
11
+ unregister(id: string): void;
12
+ /** Prompt user and return true if navigation allowed */
13
+ confirmNavigation(): Promise<boolean>;
14
+ }
15
+ /**
16
+ * Implementation of UnsavedChangesGuard.
17
+ */
18
+ export declare class UnsavedChangesGuardImpl implements UnsavedChangesGuard {
19
+ private dirtyCheckers;
20
+ private dialogService;
21
+ constructor(dialogService: DialogService);
22
+ hasUnsavedChanges(): boolean;
23
+ register(id: string, isDirty: () => boolean): () => void;
24
+ unregister(id: string): void;
25
+ confirmNavigation(): Promise<boolean>;
26
+ }
27
+ //# sourceMappingURL=unsaved-changes-guard.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"unsaved-changes-guard.d.ts","sourceRoot":"","sources":["../../src/unsaved-changes/unsaved-changes-guard.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAEpD;;GAEG;AACH,MAAM,WAAW,mBAAmB;IACnC,yCAAyC;IACzC,iBAAiB,IAAI,OAAO,CAAC;IAE7B,sDAAsD;IACtD,QAAQ,CAAC,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC;IAEzD,6BAA6B;IAC7B,UAAU,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI,CAAC;IAE7B,wDAAwD;IACxD,iBAAiB,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC;CACtC;AAED;;GAEG;AACH,qBAAa,uBAAwB,YAAW,mBAAmB;IAClE,OAAO,CAAC,aAAa,CAAoC;IACzD,OAAO,CAAC,aAAa,CAAgB;gBAEzB,aAAa,EAAE,aAAa;IAIxC,iBAAiB,IAAI,OAAO;IAS5B,QAAQ,CAAC,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,OAAO,GAAG,MAAM,IAAI;IAKxD,UAAU,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI;IAItB,iBAAiB,IAAI,OAAO,CAAC,OAAO,CAAC;CAa3C"}
@@ -0,0 +1,6 @@
1
+ import { UnsavedChangesGuard } from './unsaved-changes-guard';
2
+ /**
3
+ * Hook to register unsaved changes for a form/page.
4
+ */
5
+ export declare function useUnsavedChangesGuard(guard: UnsavedChangesGuard, isDirty: boolean): void;
6
+ //# sourceMappingURL=use-unsaved-changes-guard.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-unsaved-changes-guard.d.ts","sourceRoot":"","sources":["../../src/unsaved-changes/use-unsaved-changes-guard.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAEnE;;GAEG;AACH,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,mBAAmB,EAAE,OAAO,EAAE,OAAO,QAsBlF"}
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "@judo/guards",
3
+ "version": "0.1.0",
4
+ "description": "Navigation guards for JUDO UI Runtime",
5
+ "license": "EPL-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/BlackBeltTechnology/judo-frontend-runtime.git",
9
+ "directory": "packages/guards"
10
+ },
11
+ "files": [
12
+ "dist",
13
+ "LICENSE",
14
+ "README.md"
15
+ ],
16
+ "type": "module",
17
+ "sideEffects": false,
18
+ "main": "./dist/index.js",
19
+ "module": "./dist/index.js",
20
+ "types": "./dist/index.d.ts",
21
+ "exports": {
22
+ ".": {
23
+ "types": "./dist/index.d.ts",
24
+ "import": "./dist/index.js"
25
+ }
26
+ },
27
+ "publishConfig": {
28
+ "access": "public"
29
+ },
30
+ "dependencies": {
31
+ "@judo/feedback": "0.1.0",
32
+ "@judo/model-api": "0.1.0"
33
+ },
34
+ "devDependencies": {
35
+ "@testing-library/jest-dom": "^6.9.1",
36
+ "@testing-library/react": "^16.3.2",
37
+ "@types/react": "^19.2.14",
38
+ "typescript": "^5.9.3",
39
+ "vitest": "^4.0.18",
40
+ "@judo/feedback": "0.1.0",
41
+ "@judo/model-api": "0.1.0",
42
+ "@judo/testing": "0.1.0"
43
+ },
44
+ "peerDependencies": {
45
+ "@mui/material": "^7.0.0",
46
+ "react": "^19.0.0",
47
+ "react-router": "^7.0.0",
48
+ "@judo/feedback": "0.1.0",
49
+ "@judo/model-api": "0.1.0"
50
+ },
51
+ "scripts": {
52
+ "build": "vite build",
53
+ "test": "vitest run",
54
+ "test:watch": "vitest",
55
+ "test:coverage": "vitest run --coverage",
56
+ "type-check": "tsgo --noEmit"
57
+ }
58
+ }