refactor(unsaved): extract createUnsavedWarning hook and UnsavedWarningBanner
Move the identical isDirty / beforeNavigate / discard pattern out of the three admin detail pages (groups, tags, users) into a reusable createUnsavedWarning() hook and a UnsavedWarningBanner presentational component. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
46
frontend/src/lib/hooks/useUnsavedWarning.svelte.ts
Normal file
46
frontend/src/lib/hooks/useUnsavedWarning.svelte.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import { beforeNavigate, goto } from '$app/navigation';
|
||||
|
||||
export function createUnsavedWarning() {
|
||||
let isDirty = $state(false);
|
||||
let showUnsavedWarning = $state(false);
|
||||
let discardTarget: string | null = $state(null);
|
||||
|
||||
beforeNavigate(({ cancel, to }) => {
|
||||
if (isDirty) {
|
||||
cancel();
|
||||
showUnsavedWarning = true;
|
||||
discardTarget = to?.url.href ?? null;
|
||||
}
|
||||
});
|
||||
|
||||
function markDirty() {
|
||||
isDirty = true;
|
||||
showUnsavedWarning = false;
|
||||
}
|
||||
|
||||
function discard() {
|
||||
isDirty = false;
|
||||
showUnsavedWarning = false;
|
||||
if (discardTarget) goto(discardTarget);
|
||||
}
|
||||
|
||||
function clearOnSuccess() {
|
||||
isDirty = false;
|
||||
showUnsavedWarning = false;
|
||||
}
|
||||
|
||||
return {
|
||||
get isDirty() {
|
||||
return isDirty;
|
||||
},
|
||||
get showUnsavedWarning() {
|
||||
return showUnsavedWarning;
|
||||
},
|
||||
get discardTarget() {
|
||||
return discardTarget;
|
||||
},
|
||||
markDirty,
|
||||
discard,
|
||||
clearOnSuccess
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user