Dough Git

clove/pkviewer

web/src/lib/unsavedGuard.svelte.ts

back to web/src/lib

/* web/src/lib/unsavedGuard.svelte.ts */
import { beforeNavigate } from "$app/navigation";

/**
 * Warns before leaving a page with unsaved edits.
 *
 * beforeunload covers closing and reloading. beforeNavigate covers in-app links,
 * which SvelteKit's router would otherwise follow without a word.
 */
export function useUnsavedGuard(isDirty: () => boolean): void {
  $effect(() => {
    if (!isDirty()) return;
    const handler = (event: BeforeUnloadEvent) => {
      event.preventDefault();
      // Required by some browsers for the prompt to appear at all
      event.returnValue = "";
    };
    window.addEventListener("beforeunload", handler);
    return () => window.removeEventListener("beforeunload", handler);
  });

  beforeNavigate((navigation) => {
    if (navigation.type === "leave" || !isDirty()) return;
    if (!confirm("You have unsaved changes. Leave this page?")) navigation.cancel();
  });
}