@svadmin/ui 0.120.0 → 0.121.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.
Files changed (31) hide show
  1. package/dist/app.css +136 -0
  2. package/dist/app.theme.css +136 -0
  3. package/dist/components/AboutSettings.svelte +1 -1
  4. package/dist/components/ContextMenu.svelte +268 -0
  5. package/dist/components/ContextMenu.svelte.d.ts +22 -0
  6. package/dist/components/JsonViewer.svelte +323 -0
  7. package/dist/components/JsonViewer.svelte.d.ts +20 -0
  8. package/dist/components/KpiCard.svelte +250 -0
  9. package/dist/components/KpiCard.svelte.d.ts +44 -0
  10. package/dist/components/OtpInput.svelte +209 -0
  11. package/dist/components/OtpInput.svelte.d.ts +17 -0
  12. package/dist/components/RecordCompareModal.svelte +428 -0
  13. package/dist/components/RecordCompareModal.svelte.d.ts +42 -0
  14. package/dist/components/ResultPage.svelte +166 -0
  15. package/dist/components/ResultPage.svelte.d.ts +28 -0
  16. package/dist/components/SignaturePad.svelte +230 -66
  17. package/dist/components/SignaturePad.svelte.d.ts +6 -5
  18. package/dist/components/Tour.svelte +71 -13
  19. package/dist/components/Tour.svelte.d.ts +1 -1
  20. package/dist/components/TrendIndicator.svelte +21 -13
  21. package/dist/components/TrendIndicator.svelte.d.ts +4 -2
  22. package/dist/components/UnsavedChangesGuard.svelte +138 -0
  23. package/dist/components/UnsavedChangesGuard.svelte.d.ts +32 -0
  24. package/dist/components/WatermarkContainer.svelte +196 -0
  25. package/dist/components/WatermarkContainer.svelte.d.ts +20 -0
  26. package/dist/components/useUnsavedChanges.d.svelte.ts +1 -0
  27. package/dist/components/useUnsavedChanges.svelte.d.ts +22 -0
  28. package/dist/components/useUnsavedChanges.svelte.js +105 -0
  29. package/dist/index.d.ts +19 -19
  30. package/dist/index.js +14 -2
  31. package/package.json +1 -1
@@ -15,10 +15,12 @@
15
15
  suffix?: string | undefined;
16
16
  /** Number of decimal places when auto computing rate (default: 1) */
17
17
  precision?: number | undefined;
18
+ /** Whether to explicitly prefix positive numbers with '+' (default: true) */
19
+ showSign?: boolean | undefined;
18
20
  /** Invert color semantics (useful for error rate, latency, queue backlog where lower is better) */
19
21
  reverseColor?: boolean | undefined;
20
- /** Visual style variant: 'text' (inline text), 'badge' (pill badge with subtle background), 'solid' */
21
- variant?: 'text' | 'badge' | 'solid' | undefined;
22
+ /** Visual style variant: 'text' (inline text), 'badge' (pill badge with subtle background), 'solid', 'icon' (compact icon only) */
23
+ variant?: 'text' | 'badge' | 'solid' | 'icon' | undefined;
22
24
  /** Size: 'sm' | 'md' | 'lg' */
23
25
  size?: 'sm' | 'md' | 'lg' | undefined;
24
26
  /** Whether to render trending arrow icon (default: true) */
@@ -34,6 +36,7 @@
34
36
  prefix,
35
37
  suffix = '%',
36
38
  precision = 1,
39
+ showSign = true,
37
40
  reverseColor = false,
38
41
  variant = 'text',
39
42
  size = 'md',
@@ -48,9 +51,10 @@
48
51
  const rateNum = (diff / Math.abs(prevValue)) * 100;
49
52
  const dir: 'up' | 'down' | 'neutral' = diff > 0 ? 'up' : diff < 0 ? 'down' : 'neutral';
50
53
  const formatted = Math.abs(rateNum).toFixed(precision);
54
+ const sign = showSign && dir === 'up' ? '+' : dir === 'down' ? '-' : '';
51
55
  return {
52
56
  direction: direction ?? dir,
53
- text: `${formatted}${suffix}`,
57
+ text: `${sign}${formatted}${suffix}`,
54
58
  };
55
59
  }
56
60
 
@@ -58,9 +62,10 @@
58
62
  if (typeof value === 'number') {
59
63
  const dir: 'up' | 'down' | 'neutral' = value > 0 ? 'up' : value < 0 ? 'down' : 'neutral';
60
64
  const formatted = Math.abs(value).toFixed(precision);
65
+ const sign = showSign && dir === 'up' ? '+' : dir === 'down' ? '-' : '';
61
66
  return {
62
67
  direction: direction ?? dir,
63
- text: `${formatted}${suffix}`,
68
+ text: `${sign}${formatted}${suffix}`,
64
69
  };
65
70
  }
66
71
 
@@ -101,12 +106,12 @@
101
106
  const sizeClasses = $derived.by(() => {
102
107
  switch (size) {
103
108
  case 'sm':
104
- return 'text-[11px] gap-0.5 px-1.5 py-0.5';
109
+ return variant === 'icon' ? 'p-1' : 'text-[11px] gap-0.5 px-1.5 py-0.5';
105
110
  case 'lg':
106
- return 'text-sm gap-1 px-2.5 py-1';
111
+ return variant === 'icon' ? 'p-2' : 'text-sm gap-1 px-2.5 py-1';
107
112
  case 'md':
108
113
  default:
109
- return 'text-xs gap-1 px-2 py-0.5';
114
+ return variant === 'icon' ? 'p-1.5' : 'text-xs gap-1 px-2 py-0.5';
110
115
  }
111
116
  });
112
117
 
@@ -126,7 +131,7 @@
126
131
  if (isPositive === null) {
127
132
  return variant === 'solid'
128
133
  ? 'bg-muted text-muted-foreground'
129
- : variant === 'badge'
134
+ : variant === 'badge' || variant === 'icon'
130
135
  ? 'bg-muted/50 text-muted-foreground'
131
136
  : 'text-muted-foreground';
132
137
  }
@@ -134,14 +139,14 @@
134
139
  if (isPositive) {
135
140
  return variant === 'solid'
136
141
  ? 'bg-success text-success-foreground'
137
- : variant === 'badge'
142
+ : variant === 'badge' || variant === 'icon'
138
143
  ? 'bg-success/15 text-success border border-success/20'
139
144
  : 'text-success';
140
145
  }
141
146
 
142
147
  return variant === 'solid'
143
148
  ? 'bg-destructive text-destructive-foreground'
144
- : variant === 'badge'
149
+ : variant === 'badge' || variant === 'icon'
145
150
  ? 'bg-destructive/15 text-destructive border border-destructive/20'
146
151
  : 'text-destructive';
147
152
  });
@@ -149,6 +154,7 @@
149
154
 
150
155
  <span
151
156
  data-svadmin-component="TrendIndicator"
157
+ title={variant === 'icon' ? (prefix ? `${prefix} ${computed.text}` : computed.text) : undefined}
152
158
  class={cn(
153
159
  'inline-flex items-center font-medium font-mono select-none transition-colors',
154
160
  variant !== 'text' && 'rounded-full font-semibold',
@@ -157,13 +163,13 @@
157
163
  className
158
164
  )}
159
165
  >
160
- {#if prefix}
166
+ {#if prefix && variant !== 'icon'}
161
167
  <span class="font-sans text-[11px] font-normal text-muted-foreground mr-0.5">
162
168
  {prefix}
163
169
  </span>
164
170
  {/if}
165
171
 
166
- {#if showIcon}
172
+ {#if showIcon || variant === 'icon'}
167
173
  {#if computed.direction === 'up'}
168
174
  <TrendingUp class={cn(iconSizeClasses, 'shrink-0')} />
169
175
  {:else if computed.direction === 'down'}
@@ -173,5 +179,7 @@
173
179
  {/if}
174
180
  {/if}
175
181
 
176
- <span>{computed.text}</span>
182
+ {#if variant !== 'icon'}
183
+ <span>{computed.text}</span>
184
+ {/if}
177
185
  </span>
@@ -11,10 +11,12 @@ export interface TrendIndicatorProps {
11
11
  suffix?: string | undefined;
12
12
  /** Number of decimal places when auto computing rate (default: 1) */
13
13
  precision?: number | undefined;
14
+ /** Whether to explicitly prefix positive numbers with '+' (default: true) */
15
+ showSign?: boolean | undefined;
14
16
  /** Invert color semantics (useful for error rate, latency, queue backlog where lower is better) */
15
17
  reverseColor?: boolean | undefined;
16
- /** Visual style variant: 'text' (inline text), 'badge' (pill badge with subtle background), 'solid' */
17
- variant?: 'text' | 'badge' | 'solid' | undefined;
18
+ /** Visual style variant: 'text' (inline text), 'badge' (pill badge with subtle background), 'solid', 'icon' (compact icon only) */
19
+ variant?: 'text' | 'badge' | 'solid' | 'icon' | undefined;
18
20
  /** Size: 'sm' | 'md' | 'lg' */
19
21
  size?: 'sm' | 'md' | 'lg' | undefined;
20
22
  /** Whether to render trending arrow icon (default: true) */
@@ -0,0 +1,138 @@
1
+ <script lang="ts">
2
+ import { AlertTriangle, X } from '@lucide/svelte';
3
+ import { onDestroy, type Snippet } from 'svelte';
4
+ import { cn } from '../utils.js';
5
+ import { useUnsavedChanges } from './useUnsavedChanges.svelte.js';
6
+
7
+ export interface UnsavedChangesGuardProps {
8
+ /** Controlled dirty flag indicating whether current form has unsaved modifications */
9
+ isDirty?: boolean | undefined;
10
+ /** Whether protection is actively enabled (default: true) */
11
+ enabled?: boolean | undefined;
12
+ /** Modal dialog title (default: 'Unsaved Changes') */
13
+ title?: string | undefined;
14
+ /** Modal dialog description / warning text */
15
+ message?: string | undefined;
16
+ /** Stay button label (default: 'Stay on Page') */
17
+ stayText?: string | undefined;
18
+ /** Leave button label (default: 'Discard & Leave') */
19
+ leaveText?: string | undefined;
20
+ /** Callback when user confirms discard */
21
+ onleave?: (() => void) | undefined;
22
+ /** Callback when user cancels and stays */
23
+ onstay?: (() => void) | undefined;
24
+ /** Extra classes for wrapper */
25
+ class?: string | undefined;
26
+ /** Page or form content */
27
+ children?: Snippet | undefined;
28
+ /** Custom modal replacement snippet */
29
+ modal?: Snippet<[{ proceed: () => void; cancel: () => void; isBlocked: boolean }]> | undefined;
30
+ }
31
+
32
+ let {
33
+ isDirty = false,
34
+ enabled = true,
35
+ title = 'Unsaved Changes',
36
+ message = 'You have unsaved changes that will be lost if you leave this page. Are you sure you want to discard them?',
37
+ stayText = 'Stay on Page',
38
+ leaveText = 'Discard & Leave',
39
+ onleave,
40
+ onstay,
41
+ class: className = '',
42
+ children,
43
+ modal,
44
+ }: UnsavedChangesGuardProps = $props();
45
+
46
+ const guard = useUnsavedChanges({
47
+ isDirty: () => isDirty,
48
+ enabled: () => enabled,
49
+ message: () => message,
50
+ onLeave: () => onleave?.(),
51
+ onStay: () => onstay?.(),
52
+ });
53
+
54
+ onDestroy(() => {
55
+ guard.destroy();
56
+ });
57
+ </script>
58
+
59
+ <div
60
+ data-svadmin-component="UnsavedChangesGuard"
61
+ data-dirty={isDirty ? 'true' : 'false'}
62
+ class={cn('w-full', className)}
63
+ >
64
+ {#if children}
65
+ {@render children()}
66
+ {/if}
67
+
68
+ {#if guard.isBlocked}
69
+ {#if modal}
70
+ {@render modal({ proceed: guard.proceed, cancel: guard.cancel, isBlocked: guard.isBlocked })}
71
+ {:else}
72
+ <div
73
+ role="alertdialog"
74
+ aria-modal="true"
75
+ aria-labelledby="unsaved-changes-title"
76
+ aria-describedby="unsaved-changes-desc"
77
+ class="fixed inset-0 z-50 flex items-center justify-center overflow-hidden p-4"
78
+ >
79
+ <!-- Backdrop -->
80
+ <!-- svelte-ignore a11y_click_events_have_key_events -->
81
+ <div
82
+ role="button"
83
+ tabindex="-1"
84
+ class="fixed inset-0 bg-background/80 backdrop-blur-sm transition-opacity"
85
+ onclick={guard.cancel}
86
+ aria-label="Dismiss warning"
87
+ ></div>
88
+
89
+ <!-- Alert Modal Box -->
90
+ <div
91
+ class="relative z-50 w-full max-w-md rounded-2xl border border-border bg-card p-6 text-card-foreground shadow-2xl transition-all animate-in fade-in zoom-in-95 duration-150"
92
+ >
93
+ <div class="flex items-start gap-4">
94
+ <div class="flex h-11 w-11 shrink-0 items-center justify-center rounded-xl bg-warning/15 text-warning border border-warning/20">
95
+ <AlertTriangle class="h-6 w-6" />
96
+ </div>
97
+
98
+ <div class="flex-1 space-y-1.5">
99
+ <h3 id="unsaved-changes-title" class="text-base font-semibold text-foreground">
100
+ {title}
101
+ </h3>
102
+ <p id="unsaved-changes-desc" class="text-xs text-muted-foreground leading-relaxed">
103
+ {message}
104
+ </p>
105
+ </div>
106
+
107
+ <button
108
+ type="button"
109
+ onclick={guard.cancel}
110
+ class="rounded-lg p-1 text-muted-foreground hover:bg-muted hover:text-foreground transition-colors"
111
+ aria-label="Close"
112
+ >
113
+ <X class="h-4 w-4" />
114
+ </button>
115
+ </div>
116
+
117
+ <div class="mt-6 flex items-center justify-end gap-2.5">
118
+ <button
119
+ type="button"
120
+ onclick={guard.cancel}
121
+ class="rounded-lg border border-border bg-background px-4 py-2 text-xs font-medium text-foreground hover:bg-muted transition-colors"
122
+ >
123
+ {stayText}
124
+ </button>
125
+
126
+ <button
127
+ type="button"
128
+ onclick={guard.proceed}
129
+ class="rounded-lg bg-destructive px-4 py-2 text-xs font-medium text-destructive-foreground hover:bg-destructive/90 transition-colors shadow-sm"
130
+ >
131
+ {leaveText}
132
+ </button>
133
+ </div>
134
+ </div>
135
+ </div>
136
+ {/if}
137
+ {/if}
138
+ </div>
@@ -0,0 +1,32 @@
1
+ import { type Snippet } from 'svelte';
2
+ export interface UnsavedChangesGuardProps {
3
+ /** Controlled dirty flag indicating whether current form has unsaved modifications */
4
+ isDirty?: boolean | undefined;
5
+ /** Whether protection is actively enabled (default: true) */
6
+ enabled?: boolean | undefined;
7
+ /** Modal dialog title (default: 'Unsaved Changes') */
8
+ title?: string | undefined;
9
+ /** Modal dialog description / warning text */
10
+ message?: string | undefined;
11
+ /** Stay button label (default: 'Stay on Page') */
12
+ stayText?: string | undefined;
13
+ /** Leave button label (default: 'Discard & Leave') */
14
+ leaveText?: string | undefined;
15
+ /** Callback when user confirms discard */
16
+ onleave?: (() => void) | undefined;
17
+ /** Callback when user cancels and stays */
18
+ onstay?: (() => void) | undefined;
19
+ /** Extra classes for wrapper */
20
+ class?: string | undefined;
21
+ /** Page or form content */
22
+ children?: Snippet | undefined;
23
+ /** Custom modal replacement snippet */
24
+ modal?: Snippet<[{
25
+ proceed: () => void;
26
+ cancel: () => void;
27
+ isBlocked: boolean;
28
+ }]> | undefined;
29
+ }
30
+ declare const UnsavedChangesGuard: import("svelte").Component<UnsavedChangesGuardProps, {}, "">;
31
+ type UnsavedChangesGuard = ReturnType<typeof UnsavedChangesGuard>;
32
+ export default UnsavedChangesGuard;
@@ -0,0 +1,196 @@
1
+ <script lang="ts">
2
+ import { onMount, onDestroy, type Snippet } from 'svelte';
3
+ import { cn } from '../utils.js';
4
+
5
+ export interface WatermarkContainerProps {
6
+ content?: string | string[];
7
+ image?: string;
8
+ width?: number;
9
+ height?: number;
10
+ rotate?: number;
11
+ fontSize?: number;
12
+ fontFamily?: string;
13
+ color?: string;
14
+ gapX?: number;
15
+ gapY?: number;
16
+ zIndex?: number;
17
+ antiTamper?: boolean;
18
+ class?: string;
19
+ children?: Snippet;
20
+ }
21
+
22
+ let {
23
+ content = 'CONFIDENTIAL',
24
+ image,
25
+ width = 240,
26
+ height = 140,
27
+ rotate = -22,
28
+ fontSize = 14,
29
+ fontFamily = 'sans-serif',
30
+ color = 'rgba(128, 128, 128, 0.18)',
31
+ gapX = 48,
32
+ gapY = 48,
33
+ zIndex = 9999,
34
+ antiTamper = true,
35
+ class: className = '',
36
+ children,
37
+ }: WatermarkContainerProps = $props();
38
+
39
+ let containerEl = $state<HTMLDivElement | null>(null);
40
+ let overlayEl = $state<HTMLDivElement | null>(null);
41
+ let watermarkDataUrl = $state<string>('');
42
+
43
+ let observer: MutationObserver | null = null;
44
+
45
+ function renderWatermarkCanvas(): string {
46
+ if (typeof document === 'undefined') return '';
47
+
48
+ try {
49
+ const canvas = document.createElement('canvas');
50
+ const totalWidth = width + gapX;
51
+ const totalHeight = height + gapY;
52
+
53
+ const dpr = typeof window !== 'undefined' ? (window.devicePixelRatio || 1) : 1;
54
+ canvas.width = totalWidth * dpr;
55
+ canvas.height = totalHeight * dpr;
56
+
57
+ const ctx = canvas.getContext('2d');
58
+ if (!ctx) return '';
59
+
60
+ ctx.scale(dpr, dpr);
61
+ ctx.translate(totalWidth / 2, totalHeight / 2);
62
+ ctx.rotate((rotate * Math.PI) / 180);
63
+
64
+ if (image) {
65
+ const img = new Image();
66
+ img.crossOrigin = 'anonymous';
67
+ img.src = image;
68
+ ctx.drawImage(img, -width / 2, -height / 2, width, height);
69
+ return typeof canvas.toDataURL === 'function' ? canvas.toDataURL() : '';
70
+ }
71
+
72
+ const lines = Array.isArray(content) ? content : [content];
73
+ ctx.font = `${fontSize}px ${fontFamily}`;
74
+ ctx.fillStyle = color;
75
+ ctx.textAlign = 'center';
76
+ ctx.textBaseline = 'middle';
77
+
78
+ const lineHeight = fontSize * 1.4;
79
+ const initialY = -((lines.length - 1) * lineHeight) / 2;
80
+
81
+ lines.forEach((line, index) => {
82
+ ctx.fillText(line, 0, initialY + index * lineHeight);
83
+ });
84
+
85
+ return typeof canvas.toDataURL === 'function' ? canvas.toDataURL() : '';
86
+ } catch {
87
+ return '';
88
+ }
89
+ }
90
+
91
+ function applyOverlayStyle() {
92
+ if (!overlayEl) return;
93
+ overlayEl.style.position = 'absolute';
94
+ overlayEl.style.top = '0';
95
+ overlayEl.style.left = '0';
96
+ overlayEl.style.width = '100%';
97
+ overlayEl.style.height = '100%';
98
+ overlayEl.style.pointerEvents = 'none';
99
+ overlayEl.style.zIndex = String(zIndex);
100
+ overlayEl.style.backgroundRepeat = 'repeat';
101
+ overlayEl.style.display = 'block';
102
+ overlayEl.style.visibility = 'visible';
103
+ overlayEl.style.opacity = '1';
104
+ if (watermarkDataUrl) {
105
+ overlayEl.style.backgroundImage = `url("${watermarkDataUrl}")`;
106
+ overlayEl.style.backgroundSize = `${width + gapX}px ${height + gapY}px`;
107
+ }
108
+ }
109
+
110
+ function reobserve() {
111
+ if (!observer || !containerEl || !overlayEl) return;
112
+ observer.observe(containerEl, {
113
+ childList: true,
114
+ subtree: false,
115
+ });
116
+ observer.observe(overlayEl, {
117
+ attributes: true,
118
+ attributeFilter: ['style', 'class', 'hidden'],
119
+ });
120
+ }
121
+
122
+ function setupAntiTamper() {
123
+ if (!antiTamper || typeof MutationObserver === 'undefined' || !containerEl || !overlayEl) return;
124
+
125
+ observer?.disconnect();
126
+ observer = new MutationObserver((mutations) => {
127
+ if (!containerEl || !overlayEl) return;
128
+
129
+ let needRestore = false;
130
+
131
+ for (const m of mutations) {
132
+ if (m.type === 'childList') {
133
+ if (!containerEl.contains(overlayEl)) {
134
+ needRestore = true;
135
+ break;
136
+ }
137
+ } else if (m.type === 'attributes' && m.target === overlayEl) {
138
+ const style = overlayEl.getAttribute('style') || '';
139
+ if (
140
+ style.includes('display: none') ||
141
+ style.includes('visibility: hidden') ||
142
+ style.includes('opacity: 0') ||
143
+ !style.includes('pointer-events: none')
144
+ ) {
145
+ needRestore = true;
146
+ break;
147
+ }
148
+ }
149
+ }
150
+
151
+ if (needRestore) {
152
+ observer?.disconnect();
153
+ if (!containerEl.contains(overlayEl)) {
154
+ // eslint-disable-next-line svelte/no-dom-manipulating -- Anti-tamper security restores overlay when removed by client
155
+ containerEl.appendChild(overlayEl);
156
+ }
157
+ applyOverlayStyle();
158
+ reobserve();
159
+ }
160
+ });
161
+
162
+ reobserve();
163
+ }
164
+
165
+ $effect(() => {
166
+ // Access props to track reactivity
167
+ void [content, image, width, height, rotate, fontSize, fontFamily, color, gapX, gapY];
168
+ watermarkDataUrl = renderWatermarkCanvas();
169
+ applyOverlayStyle();
170
+ });
171
+
172
+ onMount(() => {
173
+ watermarkDataUrl = renderWatermarkCanvas();
174
+ applyOverlayStyle();
175
+ setupAntiTamper();
176
+ });
177
+
178
+ onDestroy(() => {
179
+ observer?.disconnect();
180
+ observer = null;
181
+ });
182
+ </script>
183
+
184
+ <div
185
+ bind:this={containerEl}
186
+ class={cn('relative overflow-hidden', className)}
187
+ data-svadmin-component="WatermarkContainer"
188
+ >
189
+ {@render children?.()}
190
+ <div
191
+ bind:this={overlayEl}
192
+ class="pointer-events-none absolute inset-0 select-none"
193
+ data-svadmin-watermark-overlay="true"
194
+ aria-hidden="true"
195
+ ></div>
196
+ </div>
@@ -0,0 +1,20 @@
1
+ import { type Snippet } from 'svelte';
2
+ export interface WatermarkContainerProps {
3
+ content?: string | string[];
4
+ image?: string;
5
+ width?: number;
6
+ height?: number;
7
+ rotate?: number;
8
+ fontSize?: number;
9
+ fontFamily?: string;
10
+ color?: string;
11
+ gapX?: number;
12
+ gapY?: number;
13
+ zIndex?: number;
14
+ antiTamper?: boolean;
15
+ class?: string;
16
+ children?: Snippet;
17
+ }
18
+ declare const WatermarkContainer: import("svelte").Component<WatermarkContainerProps, {}, "">;
19
+ type WatermarkContainer = ReturnType<typeof WatermarkContainer>;
20
+ export default WatermarkContainer;
@@ -0,0 +1 @@
1
+ export * from './useUnsavedChanges.svelte.js';
@@ -0,0 +1,22 @@
1
+ export interface UseUnsavedChangesOptions {
2
+ /** Initial dirty state or getter function */
3
+ isDirty?: boolean | (() => boolean) | undefined;
4
+ /** Custom warning message for native browser dialog */
5
+ message?: string | (() => string) | undefined;
6
+ /** Whether the unsaved changes guard is actively enabled (default: true) */
7
+ enabled?: boolean | (() => boolean) | undefined;
8
+ /** Callback when user decides to leave/discard */
9
+ onLeave?: (() => void) | undefined;
10
+ /** Callback when user decides to stay and keep editing */
11
+ onStay?: (() => void) | undefined;
12
+ }
13
+ export declare function useUnsavedChanges(options?: UseUnsavedChangesOptions): {
14
+ readonly isDirty: boolean;
15
+ readonly isBlocked: boolean;
16
+ readonly pendingNavigationUrl: string | null;
17
+ setDirty: (value: boolean) => void;
18
+ setBlocked: (value: boolean) => void;
19
+ proceed: () => void;
20
+ cancel: () => void;
21
+ destroy: () => void;
22
+ };
@@ -0,0 +1,105 @@
1
+ export function useUnsavedChanges(options = {}) {
2
+ let dirtyState = $state(typeof options.isDirty === 'function' ? options.isDirty() : Boolean(options.isDirty));
3
+ let isBlocked = $state(false);
4
+ let pendingNavigationUrl = $state(null);
5
+ let allowLeave = false;
6
+ const isDirtyDerived = $derived(typeof options.isDirty === 'function' ? options.isDirty() : dirtyState);
7
+ const enabled = $derived(typeof options.enabled === 'function' ? options.enabled() : (options.enabled ?? true));
8
+ const warningMessage = $derived(typeof options.message === 'function'
9
+ ? options.message()
10
+ : (options.message ?? 'You have unsaved changes. Are you sure you want to leave?'));
11
+ function handleBeforeUnload(e) {
12
+ if (allowLeave || !enabled || !isDirtyDerived)
13
+ return;
14
+ e.preventDefault();
15
+ e.returnValue = warningMessage;
16
+ return warningMessage;
17
+ }
18
+ function handleDocumentClick(e) {
19
+ if (allowLeave || !enabled || !isDirtyDerived)
20
+ return;
21
+ if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey)
22
+ return;
23
+ const target = e.target?.closest?.('a');
24
+ if (!target || !target.href)
25
+ return;
26
+ if (target.target === '_blank' || target.hasAttribute('download'))
27
+ return;
28
+ try {
29
+ const url = new URL(target.href, window.location.href);
30
+ if (url.origin === window.location.origin &&
31
+ url.pathname === window.location.pathname &&
32
+ url.search === window.location.search) {
33
+ return;
34
+ }
35
+ }
36
+ catch {
37
+ return;
38
+ }
39
+ e.preventDefault();
40
+ e.stopPropagation();
41
+ pendingNavigationUrl = target.href;
42
+ isBlocked = true;
43
+ }
44
+ function handlePopState() {
45
+ if (allowLeave || !enabled || !isDirtyDerived)
46
+ return;
47
+ window.history.pushState(null, '', window.location.href);
48
+ isBlocked = true;
49
+ }
50
+ if (typeof window !== 'undefined') {
51
+ window.addEventListener('beforeunload', handleBeforeUnload);
52
+ document.addEventListener('click', handleDocumentClick, true);
53
+ window.addEventListener('popstate', handlePopState);
54
+ }
55
+ function proceed() {
56
+ const url = pendingNavigationUrl;
57
+ isBlocked = false;
58
+ dirtyState = false;
59
+ allowLeave = true;
60
+ pendingNavigationUrl = null;
61
+ options.onLeave?.();
62
+ if (url && typeof window !== 'undefined') {
63
+ window.location.href = url;
64
+ return;
65
+ }
66
+ // Reset the bypass only if no synchronous navigation happened, so an
67
+ // `onLeave` callback can still navigate without a second beforeunload prompt.
68
+ setTimeout(() => {
69
+ allowLeave = false;
70
+ }, 0);
71
+ }
72
+ function cancel() {
73
+ isBlocked = false;
74
+ pendingNavigationUrl = null;
75
+ allowLeave = false;
76
+ options.onStay?.();
77
+ }
78
+ function destroy() {
79
+ if (typeof window !== 'undefined') {
80
+ window.removeEventListener('beforeunload', handleBeforeUnload);
81
+ document.removeEventListener('click', handleDocumentClick, true);
82
+ window.removeEventListener('popstate', handlePopState);
83
+ }
84
+ }
85
+ return {
86
+ get isDirty() {
87
+ return isDirtyDerived;
88
+ },
89
+ get isBlocked() {
90
+ return isBlocked;
91
+ },
92
+ get pendingNavigationUrl() {
93
+ return pendingNavigationUrl;
94
+ },
95
+ setDirty: (value) => {
96
+ dirtyState = value;
97
+ },
98
+ setBlocked: (value) => {
99
+ isBlocked = value;
100
+ },
101
+ proceed,
102
+ cancel,
103
+ destroy,
104
+ };
105
+ }