diff --git a/src/app/questions-list/page.tsx b/src/app/questions-list/page.tsx index 4727aef..566a75d 100644 --- a/src/app/questions-list/page.tsx +++ b/src/app/questions-list/page.tsx @@ -30,8 +30,10 @@ import { useI18n } from "@/translations/provider"; import { toFrontendSlug } from "@/data/section-slug-map"; import SectionsRequest from "./sections-request"; import { getStoredAge, getLocalSectionProgress } from "@/components/questions/progress-helper"; +import { useCloseServiceOnBack } from "@/hooks/use-close-service-on-back"; export default function QuestionsListPage() { + useCloseServiceOnBack(); const { dictionary: t, locale } = useI18n(); const router = useRouter(); const { data: profile } = useMarriageProfileQuery(); diff --git a/src/hooks/use-close-service-on-back.ts b/src/hooks/use-close-service-on-back.ts new file mode 100644 index 0000000..34a0dd5 --- /dev/null +++ b/src/hooks/use-close-service-on-back.ts @@ -0,0 +1,41 @@ +"use client"; + +import { useEffect } from "react"; + +/** + * Hook to intercept browser/hardware back button (popstate) and trigger + * Flutter's `close_service` action when running inside Flutter WebView. + */ +export function useCloseServiceOnBack(enabled: boolean = true) { + useEffect(() => { + if (!enabled || typeof window === "undefined") { + return; + } + + const app = (window as any).HabibApp; + if (!app?.postMessage) { + return; + } + + // Push a dummy history state so hardware back triggers popstate instead of navigating away + window.history.pushState({ closeOnBack: true }, "", window.location.href); + + const handlePopState = () => { + if ((window as any).HabibApp?.postMessage) { + // Keep the state pinned in webview and notify Flutter to close the webview + window.history.pushState({ closeOnBack: true }, "", window.location.href); + (window as any).HabibApp.postMessage( + JSON.stringify({ action: "close_service" }), + ); + } + }; + + window.addEventListener("popstate", handlePopState); + + return () => { + window.removeEventListener("popstate", handlePopState); + }; + }, [enabled]); +} + +export default useCloseServiceOnBack;