Duffer Derek

Current Path : /var/www/sitesecurity.bitkit.dk/httpdocs/src/hooks/
Upload File :
Current File : /var/www/sitesecurity.bitkit.dk/httpdocs/src/hooks/useKeepInternalNavInline.ts

"use client";

import { useEffect } from 'react';
import { useRouter } from 'next/navigation';

/**
 * Hook to force internal links to stay in one view (catches hidden _blank/window.open)
 * 
 * This is particularly useful for iOS Chrome PWAs where internal links with target="_blank"
 * or window.open() calls can open in an overlay instead of proper in-app navigation.
 * 
 * It preserves external links and popups, but collapses internal "new windows" to normal in-app navigation.
 */
export function useKeepInternalNavInline() {
  const router = useRouter();

  useEffect(() => {
    // 1) Collapse internal <a target="_blank"> into router nav
    const onClick = (e: MouseEvent) => {
      const a = (e.target as HTMLElement)?.closest?.('a[href]') as HTMLAnchorElement | null;
      
      if (!a) return;

      // Ignore modified clicks (Cmd/Ctrl+Click, Shift+Click, etc.)
      if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || a.download) return;

      try {
        const url = new URL(a.href, location.href);
        const sameOrigin = url.origin === location.origin;

        if (sameOrigin) {
          // If any library set target=_blank (or Chrome tries a new context), keep it inline
          if (a.target === '_blank') {
            e.preventDefault();
            router.push(url.pathname + url.search + url.hash);
          }
        }
      } catch (error) {
        // Invalid URL, let browser handle it
        console.warn('Invalid URL in link:', a.href, error);
      }
    };

    // 2) Tame window.open for same-origin routes (libraries/auth)
    const originalOpen = window.open;
    
    (window as any).open = function (url?: string | URL, target?: string, features?: string) {
      if (url) {
        try {
          const u = new URL(String(url), location.href);
          const sameOrigin = u.origin === location.origin;

          if (sameOrigin && (!target || target === '_blank' || target === '_self')) {
            // Keep it inside the PWA view
            router.push(u.pathname + u.search + u.hash);
            return null;
          }
        } catch (error) {
          // Invalid URL or external link, fallthrough to original open
          console.warn('Invalid URL in window.open:', url, error);
        }
      }

      return originalOpen ? originalOpen.apply(window, [url as any, target as any, features as any]) : null;
    };

    document.addEventListener('click', onClick);

    return () => {
      document.removeEventListener('click', onClick);
      (window as any).open = originalOpen;
    };
  }, [router]);
}


Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists