|
| 1 | +'use client'; |
| 2 | + |
| 3 | +import { useTheme } from 'next-themes'; |
| 4 | +import { useEffect, useRef, useState } from 'react'; |
| 5 | + |
| 6 | +const EXPLORER_URL = 'https://explorer.agentuity.dev'; |
| 7 | + |
| 8 | +export function SDKExplorerIframe() { |
| 9 | + const { resolvedTheme } = useTheme(); |
| 10 | + const iframeRef = useRef<HTMLIFrameElement>(null); |
| 11 | + const [mounted, setMounted] = useState(false); |
| 12 | + const [iframeLoaded, setIframeLoaded] = useState(false); |
| 13 | + // Capture initial theme for iframe src (don't change src on theme updates) |
| 14 | + const [initialTheme] = useState(() => |
| 15 | + typeof window !== 'undefined' |
| 16 | + ? document.documentElement.classList.contains('dark') |
| 17 | + ? 'dark' |
| 18 | + : 'light' |
| 19 | + : 'dark' |
| 20 | + ); |
| 21 | + |
| 22 | + // Only render iframe after mount to avoid hydration mismatch |
| 23 | + useEffect(() => { |
| 24 | + setMounted(true); |
| 25 | + }, []); |
| 26 | + |
| 27 | + // Send theme changes to iframe via postMessage |
| 28 | + useEffect(() => { |
| 29 | + if (mounted && iframeRef.current?.contentWindow) { |
| 30 | + iframeRef.current.contentWindow.postMessage( |
| 31 | + { type: 'SET_THEME', theme: resolvedTheme }, |
| 32 | + EXPLORER_URL |
| 33 | + ); |
| 34 | + } |
| 35 | + }, [resolvedTheme, mounted]); |
| 36 | + |
| 37 | + // Listen for navigation requests from iframe |
| 38 | + useEffect(() => { |
| 39 | + const handleMessage = (event: MessageEvent) => { |
| 40 | + // Validate origin to prevent open redirect |
| 41 | + if (event.origin !== new URL(EXPLORER_URL).origin) { |
| 42 | + return; |
| 43 | + } |
| 44 | + if (event.data?.type === 'NAVIGATE' && event.data.path) { |
| 45 | + const path = event.data.path; |
| 46 | + // Only allow relative paths to prevent open redirects |
| 47 | + if ( |
| 48 | + typeof path === 'string' && |
| 49 | + path.startsWith('/') && |
| 50 | + !path.startsWith('//') |
| 51 | + ) { |
| 52 | + window.location.href = path; |
| 53 | + } |
| 54 | + } |
| 55 | + }; |
| 56 | + window.addEventListener('message', handleMessage); |
| 57 | + return () => window.removeEventListener('message', handleMessage); |
| 58 | + }, []); |
| 59 | + |
| 60 | + // Show placeholder until mounted to avoid hydration mismatch |
| 61 | + if (!mounted) { |
| 62 | + return <div className="size-full bg-fd-background" />; |
| 63 | + } |
| 64 | + |
| 65 | + return ( |
| 66 | + <div className="sdk-explorer-wrapper"> |
| 67 | + <iframe |
| 68 | + ref={iframeRef} |
| 69 | + src={`${EXPLORER_URL}?theme=${initialTheme}`} |
| 70 | + title="SDK Explorer" |
| 71 | + allow="clipboard-read; clipboard-write" |
| 72 | + onLoad={() => setIframeLoaded(true)} |
| 73 | + className={`transition-opacity duration-300 ${iframeLoaded ? 'opacity-100' : 'opacity-0'}`} |
| 74 | + /> |
| 75 | + </div> |
| 76 | + ); |
| 77 | +} |
0 commit comments