|
| 1 | +"use client"; |
| 2 | + |
| 3 | +import { useEffect } from "react"; |
| 4 | +import { UNSAVED_CHANGE_WARNING_MESSAGE } from "@/app/(sidebar)/dashboard/_constants/messages"; |
| 5 | + |
| 6 | +/** |
| 7 | + * 미저장 변경사항이 있을 때 페이지 이탈을 경고하는 훅 |
| 8 | + * - 브라우저 새로고침/탭 닫기: beforeunload |
| 9 | + * - 클라이언트 라우팅(Link 클릭): anchor click 인터셉트 |
| 10 | + * - 브라우저 뒤로가기/앞으로가기: popstate 인터셉트 |
| 11 | + */ |
| 12 | +export function useUnsavedChangesWarning(hasUnsavedChanges: boolean) { |
| 13 | + // 브라우저 새로고침 / 탭 닫기 |
| 14 | + useEffect(() => { |
| 15 | + if (!hasUnsavedChanges) return; |
| 16 | + |
| 17 | + const handleBeforeUnload = (e: BeforeUnloadEvent) => { |
| 18 | + e.preventDefault(); |
| 19 | + }; |
| 20 | + |
| 21 | + window.addEventListener("beforeunload", handleBeforeUnload); |
| 22 | + return () => window.removeEventListener("beforeunload", handleBeforeUnload); |
| 23 | + }, [hasUnsavedChanges]); |
| 24 | + |
| 25 | + // Next.js Link 클릭 (클라이언트 라우팅) 인터셉트 |
| 26 | + useEffect(() => { |
| 27 | + if (!hasUnsavedChanges) return; |
| 28 | + |
| 29 | + const handleClick = (e: MouseEvent) => { |
| 30 | + const anchor = (e.target as HTMLElement).closest("a"); |
| 31 | + if (!anchor) return; |
| 32 | + |
| 33 | + const href = anchor.getAttribute("href"); |
| 34 | + if (!href || href.startsWith("#")) return; |
| 35 | + |
| 36 | + // 외부 링크는 beforeunload가 처리 |
| 37 | + if (anchor.target === "_blank" || anchor.origin !== window.location.origin) return; |
| 38 | + |
| 39 | + if (!window.confirm(UNSAVED_CHANGE_WARNING_MESSAGE)) { |
| 40 | + e.preventDefault(); |
| 41 | + e.stopPropagation(); |
| 42 | + } |
| 43 | + }; |
| 44 | + |
| 45 | + document.addEventListener("click", handleClick, true); |
| 46 | + return () => document.removeEventListener("click", handleClick, true); |
| 47 | + }, [hasUnsavedChanges]); |
| 48 | + |
| 49 | + // 브라우저 뒤로가기 / 앞으로가기 |
| 50 | + useEffect(() => { |
| 51 | + if (!hasUnsavedChanges) return; |
| 52 | + |
| 53 | + const handlePopState = () => { |
| 54 | + if (!window.confirm(UNSAVED_CHANGE_WARNING_MESSAGE)) { |
| 55 | + window.history.pushState(null, "", window.location.href); |
| 56 | + } |
| 57 | + }; |
| 58 | + |
| 59 | + window.history.pushState(null, "", window.location.href); |
| 60 | + window.addEventListener("popstate", handlePopState); |
| 61 | + return () => window.removeEventListener("popstate", handlePopState); |
| 62 | + }, [hasUnsavedChanges]); |
| 63 | +} |
0 commit comments