diff --git a/iframe-fetch-client/_iframe-client/main.js b/iframe-fetch-client/_iframe-client/main.js index 1ce3d80e..3b6212ce 100644 --- a/iframe-fetch-client/_iframe-client/main.js +++ b/iframe-fetch-client/_iframe-client/main.js @@ -185,20 +185,16 @@ class NavigationHandler { setupHistoryListeners() { // Listen for popstate events (back/forward navigation) window.addEventListener('popstate', (event) => { - // When user goes back, we need to update our tracking + // When user navigates (back or forward), we need to update our tracking // The state object can help us determine our position - if (event.state !== null) { - // If there's state, we assume we're navigating within our app - this.historyIndex = Math.max(0, this.historyIndex - 1); - } else { - // If no state, we might be going back to the initial page - this.historyIndex = 0; - } + // Update current semantic path based on actual URL + this.currentSemanticPath = window.location.pathname + window.location.search + window.location.hash; this.updateNavigationState(); }); // Listen for hash changes window.addEventListener('hashchange', () => { + this.currentSemanticPath = window.location.pathname + window.location.search + window.location.hash; this.updateNavigationState(); }); } @@ -226,9 +222,7 @@ class NavigationHandler { semanticPath = window.location.pathname + window.location.search + window.location.hash; } - // When pushState is called, we're adding a new history entry - this.historyIndex++; - this.historyLength = this.historyIndex + 1; + // pushState was called, update semantic path this.currentSemanticPath = semanticPath; this.updateNavigationState(); return result; @@ -250,7 +244,7 @@ class NavigationHandler { semanticPath = window.location.pathname + window.location.search + window.location.hash; } - // replaceState doesn't change history length, just updates current entry + // replaceState was called, update semantic path this.currentSemanticPath = semanticPath; this.updateNavigationState(); return result; @@ -269,21 +263,22 @@ class NavigationHandler { // Extract the semantic path (pathname + search + hash) const semanticPath = targetUrl.pathname + targetUrl.search + targetUrl.hash; - // IMPORTANT: Don't change the iframe's actual URL - keep it on the base path - // Only communicate the semantic path to the parent for display + // Use browser's history API to trigger SPA navigation + // This triggers SPA router navigation the semantic path to the parent for display // The SPA's router will handle the navigation internally - // Update our navigation state to reflect the semantic path + // Use history.pushState to trigger SPA navigation this.currentSemanticPath = semanticPath; - - // Immediately send navigation state update to parent this.updateNavigationState(); - // Dispatch a custom event to notify the SPA of the navigation intent - // SPAs can listen for this event and trigger their own navigation - window.dispatchEvent(new CustomEvent('spa-navigate', { - detail: { path: semanticPath } - })); + // Use browser's history.pushState to trigger SPA navigation the SPA of the navigation intent + // This is what most SPAs (React Router, Vue Router, etc.) listen for + window.history.pushState({}, '', semanticPath); + + // URL change - Many SPAs listen for popstate events + window.dispatchEvent(new PopStateEvent('popstate', { state: {} })); + + // Update navigation state to parent } catch (error) { console.error('Invalid navigation URL:', url, error); @@ -291,7 +286,9 @@ class NavigationHandler { } handleRefresh() { - window.location.reload(); + // Reload the iframe by going back to base URL and then reloading + // This prevents trying to fetch non-existent SPA routes + window.location.replace('/'); } handleGoBack() { @@ -313,8 +310,8 @@ class NavigationHandler { const state = { currentUrl: semanticPath, - canGoBack: this.historyIndex > 0, - canGoForward: this.historyIndex < this.historyLength - 1 + canGoBack: false, // Let parent handle history tracking + canGoForward: false // Let parent handle history tracking }; // Send navigation state to parent diff --git a/src/components/Shakespeare/PreviewPane.tsx b/src/components/Shakespeare/PreviewPane.tsx index 9561e71a..2856a146 100644 --- a/src/components/Shakespeare/PreviewPane.tsx +++ b/src/components/Shakespeare/PreviewPane.tsx @@ -199,12 +199,13 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { const { params } = message; try { - const url = new URL(params.currentUrl); - const path = url.pathname + url.search + url.hash; + // 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); @@ -212,7 +213,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { setHistoryIndex(newHistory.length - 1); } } catch (error) { - console.error('Failed to parse navigation URL:', params.currentUrl, error); + console.error('Failed to handle navigation state:', params.currentUrl, error); } }, [historyIndex, navigationHistory]); @@ -230,22 +231,42 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { }, [projectId]); const navigateIframe = useCallback((url: string) => { - // Convert path to full URL - const fullUrl = `https://${projectId}.${IFRAME_DOMAIN}${url}`; - sendNavigationCommand('navigate', { url: fullUrl }); - }, [projectId, sendNavigationCommand]); + // 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(() => { - sendNavigationCommand('goBack'); - }, [sendNavigationCommand]); + 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(() => { - sendNavigationCommand('goForward'); - }, [sendNavigationCommand]); + 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; @@ -275,6 +296,9 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { 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); @@ -294,12 +318,32 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { id }); return; - } catch { - // File not found, try SPA fallback to index.html - console.log(`File not found: ${filePath}, trying index.html fallback`); + } catch (error) { + console.log(`File not found: ${filePath}, error: ${error.message}`); + + // For static assets, return 404 immediately + if (isStaticAsset) { + console.log(`Static asset not found: ${filePath}, returning 404`); + 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 + console.log(`Trying SPA fallback to index.html for: ${path}`); } - // 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}`); @@ -319,7 +363,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { }); } catch { // Even index.html doesn't exist - console.log(`No files found, returning 404 for: ${path}`); + console.log(`No index.html found, returning 404 for: ${path}`); sendResponse({ jsonrpc: '2.0', @@ -532,7 +576,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {