This commit is contained in:
Chad Curtis committed 2025-09-21 06:08:18 +00:00
1 parent 53cf844fd6
commit 2ed44e43f7
4 files changed
+116 -53

No files matched your search

+22 -25
View File
@@ -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
+61 -17
View File
@@ -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) {
</div>
<iframe
ref={iframeRef}
src={`https://${projectId}.${IFRAME_DOMAIN}${currentPath}`}
src={`https://${projectId}.${IFRAME_DOMAIN}/`}
className="w-full flex-1 border-0"
title="Project Preview"
sandbox="allow-scripts allow-same-origin allow-popups allow-forms allow-top-navigation"
+27 -10
View File
@@ -5,7 +5,7 @@ import { BrowserAddressBar } from './browser-address-bar';
describe('BrowserAddressBar', () => {
it('renders navigation buttons and address input', () => {
render(<BrowserAddressBar />);
expect(screen.getByTitle('Go back')).toBeInTheDocument();
expect(screen.getByTitle('Go forward')).toBeInTheDocument();
expect(screen.getByTitle('Refresh')).toBeInTheDocument();
@@ -15,22 +15,22 @@ describe('BrowserAddressBar', () => {
it('calls onNavigate with proper path when form is submitted', () => {
const onNavigate = vi.fn();
render(<BrowserAddressBar onNavigate={onNavigate} />);
const input = screen.getByPlaceholderText('Enter path (e.g., /, /about)');
fireEvent.change(input, { target: { value: 'about' } });
fireEvent.submit(input.closest('form')!);
expect(onNavigate).toHaveBeenCalledWith('/about');
});
it('disables back/forward buttons based on canGoBack/canGoForward props', () => {
render(
<BrowserAddressBar
canGoBack={false}
<BrowserAddressBar
canGoBack={false}
canGoForward={true}
/>
);
expect(screen.getByTitle('Go back')).toBeDisabled();
expect(screen.getByTitle('Go forward')).not.toBeDisabled();
});
@@ -39,9 +39,9 @@ describe('BrowserAddressBar', () => {
const onBack = vi.fn();
const onForward = vi.fn();
const onRefresh = vi.fn();
render(
<BrowserAddressBar
<BrowserAddressBar
onBack={onBack}
onForward={onForward}
onRefresh={onRefresh}
@@ -49,13 +49,30 @@ describe('BrowserAddressBar', () => {
canGoForward={true}
/>
);
fireEvent.click(screen.getByTitle('Go back'));
fireEvent.click(screen.getByTitle('Go forward'));
fireEvent.click(screen.getByTitle('Refresh'));
expect(onBack).toHaveBeenCalled();
expect(onForward).toHaveBeenCalled();
expect(onRefresh).toHaveBeenCalled();
});
it('updates input value when currentPath prop changes', () => {
const { rerender } = render(<BrowserAddressBar currentPath="/" />);
const input = screen.getByPlaceholderText('Enter path (e.g., /, /about)');
expect(input).toHaveValue('/');
// Re-render with new currentPath
rerender(<BrowserAddressBar currentPath="/about" />);
expect(input).toHaveValue('/about');
// Re-render with another path
rerender(<BrowserAddressBar currentPath="/contact" />);
expect(input).toHaveValue('/contact');
});
});
+6 -1
View File
@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { ChevronLeft, ChevronRight, RefreshCw } from 'lucide-react';
@@ -30,6 +30,11 @@ export function BrowserAddressBar({
}: BrowserAddressBarProps) {
const [inputValue, setInputValue] = useState(currentPath);
// Update input value when currentPath changes (e.g., when iframe navigates)
useEffect(() => {
setInputValue(currentPath);
}, [currentPath]);
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
let path = inputValue.trim();