diff --git a/iframe-fetch-client/MESSAGING_PROTOCOL.md b/iframe-fetch-client/MESSAGING_PROTOCOL.md index 150486ae..91cd5cfe 100644 --- a/iframe-fetch-client/MESSAGING_PROTOCOL.md +++ b/iframe-fetch-client/MESSAGING_PROTOCOL.md @@ -148,6 +148,36 @@ consistent handling of both text and binary data across the messaging protocol. **Result:** None (notification only, no response expected) +### Navigation Methods + +#### `navigate` +**Purpose:** Navigate iframe to a new URL within the same origin +**Parameters:** `url` (string) - Target URL (must be same origin) +**Result:** None (notification only) + +#### `refresh` +**Purpose:** Refresh/reload the current page in the iframe +**Parameters:** None +**Result:** None (notification only) + +#### `goBack` +**Purpose:** Navigate back in the iframe's history +**Parameters:** None +**Result:** None (notification only) + +#### `goForward` +**Purpose:** Navigate forward in the iframe's history +**Parameters:** None +**Result:** None (notification only) + +#### `updateNavigationState` +**Purpose:** Update parent about iframe's current navigation state +**Parameters:** +- `currentUrl` (string) - Current URL of the iframe +- `canGoBack` (boolean) - Whether iframe can go back in history +- `canGoForward` (boolean) - Whether iframe can go forward in history +**Result:** None (notification only) + ## Implementation ### Parent Page diff --git a/iframe-fetch-client/README.md b/iframe-fetch-client/README.md index a7d2910e..2116ef62 100644 --- a/iframe-fetch-client/README.md +++ b/iframe-fetch-client/README.md @@ -136,7 +136,27 @@ The system now uses a simplified JSON-RPC 2.0 protocol with two methods: - Parent responds with serialized HTTP responses - ServiceWorker creates Response objects and returns them to the client app -3. **Content Replacement:** +3. **SPA Routing Support:** + - ServiceWorker detects navigation requests (HTML page requests with `mode: "navigate"`) + - For SPA routes like `/about`, `/contact`, etc., the ServiceWorker serves the site's `index.html` + - This allows the SPA's client-side router to handle the route properly + - All other requests (assets, API calls, etc.) are handled normally via JSON-RPC + +4. **Semantic Path Navigation:** + - **Key Concept**: iframe stays on base URL (`/`) while communicating semantic paths to parent + - When user navigates to `/about` in address bar, iframe doesn't actually change URL + - Instead, NavigationHandler tracks semantic path (`/about`) and communicates it to parent + - Parent displays semantic path while iframe remains on base URL + - SPA's client-side router handles navigation internally without page reloads + - This prevents 404 errors from literal path navigation + +5. **SPA Navigation Tracking:** + - NavigationHandler overrides `history.pushState()` and `history.replaceState()` to detect SPA navigation + - When SPAs change URLs via history methods, NavigationHandler detects the change and sends navigation state to parent + - Navigation state includes semantic path, back/forward capability, and history tracking + - Parent can display current semantic path and enable proper back/forward navigation controls + +6. **Content Replacement:** - Main thread requests `/` from parent via JSON-RPC fetch - Replaces its own content with the site index - Site runs normally, with all requests handled by SW via JSON-RPC @@ -322,6 +342,14 @@ function handleRequest(fetchRequest) { - Check that JSON-RPC messages are properly formatted - Ensure iframe has appropriate sandbox permissions +### SPA routes don't work + +- Ensure the parent page serves the correct `index.html` for the root path `/` +- Check that the SPA's client-side router is properly configured +- Verify that navigation requests are being detected correctly by the ServiceWorker +- Make sure the parent page returns the same `index.html` content for SPA routes as it does for the root path +- **Important**: iframe should stay on base URL (`/`) while semantic paths are communicated to parent. If you see literal path navigation (iframe URL changing to `/about`), this indicates a configuration issue. + ## Development To modify the system: diff --git a/iframe-fetch-client/_iframe-client/main.js b/iframe-fetch-client/_iframe-client/main.js index 151c70d0..ee42e970 100644 --- a/iframe-fetch-client/_iframe-client/main.js +++ b/iframe-fetch-client/_iframe-client/main.js @@ -13,6 +13,11 @@ class JSONRPCClient { setupMessageListener() { window.addEventListener("message", (event) => { + // Only accept messages from parent window for security + if (event.source !== window.parent) { + return; + } + const message = event.data; // Check if this is a response to our own request or a ServiceWorker request if (message.jsonrpc === "2.0" && message.id !== undefined) { @@ -148,19 +153,202 @@ class ConsoleInterceptor { } } +// Navigation Handler - manages iframe navigation and history +class NavigationHandler { + constructor() { + // Get initial path from window property or default to root + this.currentSemanticPath = window.__IFRAME_INITIAL_PATH__ || '/'; + + this.setupMessageListener(); + this.setupHistoryListeners(); + this.overrideHistoryMethods(); + this.updateNavigationState(); + } + + // Extract semantic path from URL or string + extractSemanticPath(urlOrString) { + try { + const url = typeof urlOrString === 'string' + ? new URL(urlOrString, window.location.origin) + : urlOrString; + return url.pathname + url.search + url.hash; + } catch { + return window.location.pathname + window.location.search + window.location.hash; + } + } + + setupMessageListener() { + window.addEventListener("message", (event) => { + // Only accept messages from parent window for security + if (event.source !== window.parent) { + return; + } + + const message = event.data; + if (message.jsonrpc === "2.0") { + switch (message.method) { + case "navigate": + this.handleNavigate(message.params.url); + break; + case "refresh": + this.handleRefresh(); + break; + case "goBack": + this.handleGoBack(); + break; + case "goForward": + this.handleGoForward(); + break; + } + } + }); + } + + setupHistoryListeners() { + // Listen for popstate events (back/forward navigation) + window.addEventListener('popstate', () => { + this.currentSemanticPath = this.extractSemanticPath(window.location); + this.updateNavigationState(); + }); + + // Listen for hash changes + window.addEventListener('hashchange', () => { + this.currentSemanticPath = this.extractSemanticPath(window.location); + this.updateNavigationState(); + }); + } + + overrideHistoryMethods() { + // Override history.pushState and history.replaceState to detect SPA navigation + this.originalPushState = window.history.pushState; + this.originalReplaceState = window.history.replaceState; + + window.history.pushState = (...args) => { + const result = this.originalPushState.apply(window.history, args); + + // Extract semantic path from URL argument or use current location + const semanticPath = args[2] + ? this.extractSemanticPath(args[2]) + : this.extractSemanticPath(window.location); + + this.currentSemanticPath = semanticPath; + this.updateNavigationState(); + return result; + }; + + window.history.replaceState = (...args) => { + const result = this.originalReplaceState.apply(window.history, args); + + const semanticPath = args[2] + ? this.extractSemanticPath(args[2]) + : this.extractSemanticPath(window.location); + + this.currentSemanticPath = semanticPath; + this.updateNavigationState(); + return result; + }; + } + + handleNavigate(url) { + try { + // Validate URL - must be same origin + const targetUrl = new URL(url, window.location.origin); + if (targetUrl.origin !== window.location.origin) { + console.error('Navigation to different origin not allowed:', url); + return; + } + + const semanticPath = this.extractSemanticPath(targetUrl); + this.currentSemanticPath = semanticPath; + this.updateNavigationState(); + + // Trigger SPA navigation + window.history.pushState({}, '', semanticPath); + window.dispatchEvent(new PopStateEvent('popstate', { state: {} })); + + } catch (error) { + console.error('Invalid navigation URL:', url, error); + } + } + + handleRefresh() { + // Store current semantic path for reload + const currentPath = this.currentSemanticPath || '/'; + + // Save the current path to sessionStorage so it persists across reload + try { + sessionStorage.setItem('iframe_initial_path', currentPath); + } catch (error) { + console.warn('Failed to store initial path in sessionStorage:', error); + } + + // Actually reload the iframe to get a fresh SPA instance + window.location.reload(); + } + + handleGoBack() { + window.history.back(); + } + + handleGoForward() { + window.history.forward(); + } + + updateNavigationState() { + // Use tracked semantic path, fallback to current location if needed + const semanticPath = this.currentSemanticPath || this.extractSemanticPath(window.location); + + const state = { + currentUrl: semanticPath, + canGoBack: false, // Let parent handle history tracking + canGoForward: false // Let parent handle history tracking + }; + + // Send navigation state to parent + try { + window.parent.postMessage({ + jsonrpc: "2.0", + method: "updateNavigationState", + params: state + }, "*"); + } catch (error) { + console.error('Failed to send navigation state:', error); + } + } +} + // Main Fetch Client class FetchClient { constructor() { this.rpcClient = new JSONRPCClient(); this.consoleInterceptor = new ConsoleInterceptor(); + this.navigationHandler = new NavigationHandler(); this.init(); } + // Ensure SPA navigates to initial path after document is loaded + ensureInitialNavigation() { + // Wait for the SPA to initialize, then navigate to the initial path + setTimeout(() => { + const initialPath = window.__IFRAME_INITIAL_PATH__; + + if (initialPath && initialPath !== '/') { + const currentPath = window.location.pathname + window.location.search + window.location.hash; + + // If we're not already at the initial path, navigate there + if (currentPath !== initialPath) { + this.navigationHandler.handleNavigate(initialPath); + } + } + }, 150); // Give SPA more time to initialize + } + async init() { try { await this.setupServiceWorker(); await this.loadSiteIndex(); } catch (error) { + console.error("FetchClient: Initialization failed:", error); this.showError("Failed to initialize fetch client", error); } } @@ -212,6 +400,20 @@ class FetchClient { } async loadSiteIndex() { + // Check if we have a stored initial path from a refresh + let initialPath = '/'; + try { + const storedPath = sessionStorage.getItem('iframe_initial_path'); + if (storedPath) { + initialPath = storedPath; + // Clear the stored path after using it + sessionStorage.removeItem('iframe_initial_path'); + + } + } catch (error) { + console.warn('loadSiteIndex: Failed to read initial path from sessionStorage:', error); + } + const serializedRequest = { url: `${location.origin}/`, method: "GET", @@ -232,10 +434,33 @@ class FetchClient { const bytes = new Uint8Array(atob(response.body).split('').map(c => c.charCodeAt(0))); const text = new TextDecoder().decode(bytes); + // Set the initial path on window before replacing the document + // This will be available to the NavigationHandler when it initializes + if (initialPath && initialPath !== '/') { + window.__IFRAME_INITIAL_PATH__ = initialPath; + } + this.replaceDocument(text); } replaceDocument(htmlContent) { + console.log("replaceDocument: Starting..."); + + // Restore the initial path from sessionStorage before replacing document + let initialPath = '/'; + try { + const storedPath = sessionStorage.getItem('spa_initial_path'); + if (storedPath) { + initialPath = storedPath; + sessionStorage.removeItem('spa_initial_path'); + console.log('replaceDocument: Restored initial path:', initialPath); + // Set it on window for the new document + window.__IFRAME_INITIAL_PATH__ = initialPath; + } + } catch (error) { + console.warn('replaceDocument: Failed to restore initial path:', error); + } + // Create a new document from the HTML content const parser = new DOMParser(); const newDoc = parser.parseFromString(htmlContent, "text/html"); @@ -266,7 +491,8 @@ class FetchClient { document.body.appendChild(newScript); }); - console.log("Document replaced with site content"); + // Ensure initial navigation after document is loaded + this.ensureInitialNavigation(); } showError(message, error) { diff --git a/iframe-fetch-client/sw.js b/iframe-fetch-client/sw.js index 80ca4a43..4218af5c 100644 --- a/iframe-fetch-client/sw.js +++ b/iframe-fetch-client/sw.js @@ -68,23 +68,37 @@ async function requestViaJSONRPC(request) { return new Promise(async (resolve, reject) => { const id = ++requestIdCounter; - // Serialize the fetch request - let body = null; - if (request.body) { - try { - // Convert body to Uint8Array then base64 encode - const bytes = await request.bytes(); - body = btoa(String.fromCharCode(...bytes)); - } catch (error) { - reject(new Error(`Failed to serialize request body: ${error.message}`)); - return; + // Check if request is a plain object or Request object + let url, method, headers, body; + + if (request instanceof Request) { + // Handle Request object + url = request.url; + method = request.method; + headers = Object.fromEntries(request.headers.entries()); + + if (request.body) { + try { + // Convert body to Uint8Array then base64 encode + const bytes = await request.bytes(); + body = btoa(String.fromCharCode(...bytes)); + } catch (error) { + reject(new Error(`Failed to serialize request body: ${error.message}`)); + return; + } } + } else { + // Handle plain request object + url = request.url; + method = request.method || 'GET'; + headers = request.headers || {}; + body = request.body || null; } const serializedRequest = { - url: request.url, - method: request.method, - headers: Object.fromEntries(request.headers.entries()), + url: url, + method: method, + headers: headers, body: body, }; @@ -109,7 +123,7 @@ async function requestViaJSONRPC(request) { setTimeout(() => { if (pendingRequests.has(id)) { pendingRequests.delete(id); - reject(new Error(`Timeout requesting: ${request.url}`)); + reject(new Error(`Timeout requesting: ${url}`)); } }, 10000); }); @@ -134,6 +148,38 @@ self.addEventListener("fetch", (event) => { return; } + // Let iframe client assets be handled normally (anything in _iframe-client directory and common assets) + if (url.pathname.startsWith("/_iframe-client/") || + url.pathname === "/favicon.ico" || + url.pathname === "/manifest.webmanifest") { + return; + } + + // For SPA routes, check if this is a navigation request (HTML page request) + // But first check if we need to load the iframe client (this happens during refresh) + if (event.request.mode === "navigate" && + (event.request.headers.get("accept") || "").includes("text/html")) { + + // Check if this is a request for the iframe client itself + // We need to serve the iframe client HTML first, which will then load the SPA + if (url.pathname !== "/") { + // Redirect to root to load the iframe client, which will then navigate to the target path + const response = Response.redirect(new URL("/", event.request.url).href, 302); + event.respondWith(response); + return; + } + + // This is a request for the root path, serve the site's index.html via JSON-RPC + const rootRequest = { + url: new URL("/", event.request.url).href, + method: event.request.method, + headers: Object.fromEntries(event.request.headers.entries()), + body: event.request.body + }; + event.respondWith(handleRequest(rootRequest)); + return; + } + // Handle all other requests through JSON-RPC communication event.respondWith(handleRequest(event.request)); }); diff --git a/src/components/Shakespeare/PreviewPane.tsx b/src/components/Shakespeare/PreviewPane.tsx index a571bba5..b106df0d 100644 --- a/src/components/Shakespeare/PreviewPane.tsx +++ b/src/components/Shakespeare/PreviewPane.tsx @@ -166,67 +166,23 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o } }, [projectId, projectsManager]); - const refreshIframe = useCallback(() => { + // Legacy refresh function for build completion events + const refreshIframeLegacy = useCallback(() => { if (iframeRef.current) { // Force reload the iframe by updating its src iframeRef.current.src = '/'; // Use a small timeout to ensure the src is cleared before setting it back setTimeout(() => { if (iframeRef.current) { - iframeRef.current.src = `https://${projectId}.${IFRAME_DOMAIN}${currentPath}`; + iframeRef.current.src = `https://${projectId}.${IFRAME_DOMAIN}/`; } }, 10); } - }, [currentPath, projectId]); - - const navigateToPath = useCallback((path: string) => { - if (iframeRef.current) { - const baseUrl = `https://${projectId}.${IFRAME_DOMAIN}`; - const newUrl = `${baseUrl}${path}`; - iframeRef.current.src = newUrl; - setCurrentPath(path); - - // Update navigation history - const newHistory = navigationHistory.slice(0, historyIndex + 1); - newHistory.push(path); - setNavigationHistory(newHistory); - setHistoryIndex(newHistory.length - 1); - } - }, [projectId, navigationHistory, historyIndex]); - - const goBack = useCallback(() => { - if (historyIndex > 0) { - const newIndex = historyIndex - 1; - const path = navigationHistory[newIndex]; - setHistoryIndex(newIndex); - setCurrentPath(path); - - if (iframeRef.current) { - const baseUrl = `https://${projectId}.${IFRAME_DOMAIN}`; - const newUrl = `${baseUrl}${path}`; - iframeRef.current.src = newUrl; - } - } - }, [historyIndex, navigationHistory, projectId]); - - const goForward = useCallback(() => { - if (historyIndex < navigationHistory.length - 1) { - const newIndex = historyIndex + 1; - const path = navigationHistory[newIndex]; - setHistoryIndex(newIndex); - setCurrentPath(path); - - if (iframeRef.current) { - const baseUrl = `https://${projectId}.${IFRAME_DOMAIN}`; - const newUrl = `${baseUrl}${path}`; - iframeRef.current.src = newUrl; - } - } - }, [historyIndex, navigationHistory, projectId]); + }, [projectId]); const sendResponse = useCallback((message: JSONRPCResponse) => { if (iframeRef.current?.contentWindow) { - console.log(`Sending response to iframe:`, message); + const targetOrigin = `https://${projectId}.${IFRAME_DOMAIN}`; iframeRef.current.contentWindow.postMessage(message, targetOrigin); } @@ -262,11 +218,92 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o console[normalizedLevel](`[IFRAME ${params.level.toUpperCase()}] ${params.message}`); }, []); + const handleUpdateNavigationState = useCallback((message: { + jsonrpc: '2.0'; + method: 'updateNavigationState'; + params: { + currentUrl: string; + canGoBack: boolean; + canGoForward: boolean; + }; + }) => { + const { params } = message; + + try { + // params.currentUrl is now just a semantic path (e.g., "/about", "/contact?param=value#section") + const path = params.currentUrl; + + setCurrentPath(path); + + // Update navigation history if this is a new navigation + // But only if it's different from current path (avoid duplicates) + if (path !== navigationHistory[historyIndex]) { + const newHistory = navigationHistory.slice(0, historyIndex + 1); + newHistory.push(path); + setNavigationHistory(newHistory); + setHistoryIndex(newHistory.length - 1); + } + } catch (error) { + console.error('Failed to handle navigation state:', params.currentUrl, error); + } + }, [historyIndex, navigationHistory]); + + const sendNavigationCommand = useCallback((method: string, params?: Record) => { + if (iframeRef.current?.contentWindow) { + const message = { + jsonrpc: '2.0', + method, + params: params || {}, + id: Date.now() + }; + const targetOrigin = `https://${projectId}.${IFRAME_DOMAIN}`; + iframeRef.current.contentWindow.postMessage(message, targetOrigin); + } + }, [projectId]); + + const navigateIframe = useCallback((url: string) => { + // Send semantic path directly (e.g., "/about", "/contact") + // The iframe's NavigationHandler will handle this as semantic navigation + sendNavigationCommand('navigate', { url }); + }, [sendNavigationCommand]); + + const refreshIframe = useCallback(() => { + sendNavigationCommand('refresh'); + }, [sendNavigationCommand]); + + const goBackIframe = useCallback(() => { + if (historyIndex > 0) { + // Move back in history + const newIndex = historyIndex - 1; + const targetPath = navigationHistory[newIndex]; + + setHistoryIndex(newIndex); + setCurrentPath(targetPath); + + // Tell iframe to navigate to this path + sendNavigationCommand('navigate', { url: targetPath }); + } + }, [historyIndex, navigationHistory, sendNavigationCommand]); + + const goForwardIframe = useCallback(() => { + if (historyIndex < navigationHistory.length - 1) { + // Move forward in history + const newIndex = historyIndex + 1; + const targetPath = navigationHistory[newIndex]; + + setHistoryIndex(newIndex); + setCurrentPath(targetPath); + + // Tell iframe to navigate to this path + sendNavigationCommand('navigate', { url: targetPath }); + } + }, [historyIndex, navigationHistory, sendNavigationCommand]); + const handleFetch = useCallback(async (request: JSONRPCRequest) => { const { params, id } = request; const { request: fetchRequest } = params; - console.log(`Preview iframe requesting: ${fetchRequest.url}`); + try { // Parse the URL and validate origin @@ -290,6 +327,9 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o const path = url.pathname; const filePath = path; + // Skip SPA fallback for static assets (files with extensions) + const isStaticAsset = /\.[a-zA-Z0-9]+$/.test(path); + // SPA routing: try to serve the exact file first try { const bytes = await projectsManager.readFileBytes(projectId, 'dist' + filePath); @@ -310,11 +350,30 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o }); return; } catch { - // File not found, try SPA fallback to index.html - console.log(`File not found: ${filePath}, trying index.html fallback`); + + // For static assets, return 404 immediately + if (isStaticAsset) { + + sendResponse({ + jsonrpc: '2.0', + result: { + status: 404, + statusText: 'Not Found', + headers: { + 'Content-Type': 'text/plain', + }, + body: encodeBase64(`Static asset not found: ${path}`), + }, + id + }); + return; + } + + // For non-static assets, try SPA fallback to index.html + } - // SPA fallback: serve index.html for non-file requests + // SPA fallback: serve index.html for non-file requests (SPA routing) try { const bytes = await projectsManager.readFileBytes(projectId, 'dist/index.html'); console.log(`Serving index.html fallback for: ${path}`); @@ -334,7 +393,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o }); } catch { // Even index.html doesn't exist - console.log(`No files found, returning 404 for: ${path}`); + sendResponse({ jsonrpc: '2.0', @@ -379,12 +438,14 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o handleFetch(message); } else if (message.jsonrpc === '2.0' && message.method === 'console') { handleConsoleMessage(message); + } else if (message.jsonrpc === '2.0' && message.method === 'updateNavigationState') { + handleUpdateNavigationState(message); } }; window.addEventListener('message', handleMessage); return () => window.removeEventListener('message', handleMessage); - }, [handleFetch, handleConsoleMessage, projectId]); + }, [handleFetch, handleConsoleMessage, handleUpdateNavigationState, projectId]); useEffect(() => { if (selectedFile) { @@ -392,11 +453,16 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o } }, [selectedFile, loadFileContent]); - // Reset selected file when projectId changes + // Reset selected file and navigation history when projectId changes useEffect(() => { setSelectedFile(null); setFileContent(''); setMobileCodeView('explorer'); + + // Reset navigation history and state + setCurrentPath('/'); + setNavigationHistory(['/']); + setHistoryIndex(0); }, [projectId]); useEffect(() => { @@ -410,13 +476,13 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o console.log('Build completed for project, refreshing preview'); // Check for built project and refresh iframe checkForBuiltProject(); - refreshIframe(); + refreshIframeLegacy(); } }; window.addEventListener('buildComplete', handleBuildComplete as EventListener); return () => window.removeEventListener('buildComplete', handleBuildComplete as EventListener); - }, [projectId, checkForBuiltProject, refreshIframe]); + }, [projectId, checkForBuiltProject, refreshIframeLegacy]); const handleFileSelect = (filePath: string) => { setSelectedFile(filePath); @@ -583,10 +649,10 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
0} canGoForward={hasBuiltProject && historyIndex < navigationHistory.length - 1} extraContent={( @@ -613,7 +679,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o {hasBuiltProject ? (