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>
47 lines
861 B
TypeScript
47 lines
861 B
TypeScript
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
|
|
};
|
|
}
|