import { useEffect } from 'react'; import { App } from '@capacitor/app'; const OAUTH_DOMAIN = 'foxsky.app'; const DEEP_LINK_HOST: string = `${OAUTH_DOMAIN}`; export function useAndroidBackButton() { useEffect(() => { if (typeof window === 'undefined') return; const listeners: Awaited>[] = []; App.addListener('backButton', ({ canGoBack }) => { if (canGoBack) { window.history.back(); } else { App.minimizeApp(); } }).then((handle) => { listeners.push(handle); }); App.addListener('appUrlOpen', (data) => { if (data?.url) { navigateToPath(data.url); } }).then((handle) => { listeners.push(handle); }); App.getLaunchUrl().then((result) => { if (result?.url) { navigateToPath(result.url); } }); return () => { for (const l of listeners) { l.remove(); } }; }, []); } function navigateToPath(fullUrl: string) { try { const url = new URL(fullUrl); const allowedHosts = [DEEP_LINK_HOST, 'localhost']; if (!allowedHosts.includes(url.hostname)) return; const path = url.pathname + url.search + url.hash; if ( path.startsWith('/profile/') || path.startsWith('/post/') || path.startsWith('/search') || path.startsWith('/notifications') || path.startsWith('/settings') ) { window.history.pushState(null, '', path); window.dispatchEvent(new PopStateEvent('popstate', { state: null })); } } catch { // Invalid URL – ignore } }