v1 navigation

This commit is contained in:
Chad Curtis committed 2025-09-21 06:08:18 +00:00
1 parent 5cf19c61cc
commit 6aa36b6738
6 files changed
+349 -54

No files matched your search

+46
View File
@@ -148,6 +148,52 @@ consistent handling of both text and binary data across the messaging protocol.
**Result:** None (notification only, no response expected)
### `navigate`
**Purpose:** Navigate the iframe to a new URL within the same origin
**Parameters:**
- `url` (string): The URL to navigate to (must be same origin)
**Result:** None (notification only, no response expected)
### `refresh`
**Purpose:** Refresh/reload the current page in the iframe
**Parameters:** None
**Result:** None (notification only, no response expected)
### `goBack`
**Purpose:** Navigate back in the iframe's history
**Parameters:** None
**Result:** None (notification only, no response expected)
### `goForward`
**Purpose:** Navigate forward in the iframe's history
**Parameters:** None
**Result:** None (notification only, no response expected)
### `updateNavigationState`
**Purpose:** Update the parent about the iframe's current navigation state
**Parameters:**
- `currentUrl` (string): The current URL of the iframe
- `canGoBack` (boolean): Whether the iframe can go back in history
- `canGoForward` (boolean): Whether the iframe can go forward in history
**Result:** None (notification only, no response expected)
## Implementation
### Parent Page
+28 -1
View File
@@ -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,13 @@ 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
## Development
To modify the system:
+183
View File
@@ -148,11 +148,194 @@ class ConsoleInterceptor {
}
}
// Navigation Handler - manages iframe navigation and history
class NavigationHandler {
constructor() {
this.historyIndex = 0; // Track current position in history
this.historyLength = 1; // Track total history length
this.currentSemanticPath = '/'; // Always start with root path for SPAs
this.setupMessageListener();
this.setupHistoryListeners();
this.overrideHistoryMethods();
this.updateNavigationState();
}
setupMessageListener() {
window.addEventListener("message", (event) => {
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', (event) => {
// When user goes back, 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;
}
this.updateNavigationState();
});
// Listen for hash changes
window.addEventListener('hashchange', () => {
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 the URL argument or current location
let semanticPath;
if (args[2] && typeof args[2] === 'string') {
// If URL is provided as third argument, use it
try {
const url = new URL(args[2], window.location.origin);
semanticPath = url.pathname + url.search + url.hash;
} catch {
semanticPath = window.location.pathname + window.location.search + window.location.hash;
}
} else {
// Otherwise use current location
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;
this.currentSemanticPath = semanticPath;
this.updateNavigationState();
return result;
};
window.history.replaceState = (...args) => {
const result = this.originalReplaceState.apply(window.history, args);
// Extract semantic path for replaceState as well
let semanticPath;
if (args[2] && typeof args[2] === 'string') {
try {
const url = new URL(args[2], window.location.origin);
semanticPath = url.pathname + url.search + url.hash;
} catch {
semanticPath = window.location.pathname + window.location.search + window.location.hash;
}
} else {
semanticPath = window.location.pathname + window.location.search + window.location.hash;
}
// replaceState doesn't change history length, just updates current entry
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;
}
// 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
// The SPA's router will handle the navigation internally
// Update our navigation state to reflect the semantic path
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 }
}));
} catch (error) {
console.error('Invalid navigation URL:', url, error);
}
}
handleRefresh() {
window.location.reload();
}
handleGoBack() {
if (this.historyIndex > 0) {
window.history.back();
}
}
handleGoForward() {
if (this.historyIndex < this.historyLength - 1) {
window.history.forward();
}
}
updateNavigationState() {
// Use tracked semantic path instead of window.location
// This allows iframe to stay on base URL while showing semantic paths
const semanticPath = this.currentSemanticPath || (window.location.pathname + window.location.search + window.location.hash);
const state = {
currentUrl: semanticPath,
canGoBack: this.historyIndex > 0,
canGoForward: this.historyIndex < this.historyLength - 1
};
// 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();
}
+20
View File
@@ -134,6 +134,26 @@ self.addEventListener("fetch", (event) => {
return;
}
// For SPA routes, check if this is a navigation request (HTML page request)
// If it's a navigation request for an SPA route, serve the site's index.html via JSON-RPC
if (event.request.mode === "navigate" &&
(event.request.headers.get("accept") || "").includes("text/html")) {
// This is an SPA route navigation request, serve the site's index.html
// Create a new request for the root path to get the site's index.html
const rootRequest = new Request("/", {
method: "GET",
headers: event.request.headers,
mode: event.request.mode,
credentials: event.request.credentials,
cache: event.request.cache,
redirect: event.request.redirect,
referrer: event.request.referrer,
referrerPolicy: event.request.referrerPolicy,
});
event.respondWith(handleRequest(rootRequest));
return;
}
// Handle all other requests through JSON-RPC communication
event.respondWith(handleRequest(event.request));
});
+1
View File
@@ -24,6 +24,7 @@ export function AppRouter() {
<SessionMonitor />
<Routes>
<Route path="/" element={<Index />} />
<Route path="/about" element={<AboutSettings />} />
<Route path="/clone" element={<Clone />} />
<Route path="/oauth/github" element={<GitHubOAuth />} />
<Route path="/settings" element={<SettingsLayout />}>
+71 -53
View File
@@ -129,7 +129,8 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
}
}, [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
const currentSrc = iframeRef.current.src;
@@ -143,51 +144,6 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
}
}, []);
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]);
const sendResponse = useCallback((message: JSONRPCResponse) => {
if (iframeRef.current?.contentWindow) {
console.log(`Sending response to iframe:`, message);
@@ -231,6 +187,66 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
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 {
const url = new URL(params.currentUrl);
const path = url.pathname + url.search + url.hash;
setCurrentPath(path);
// Update navigation history if this is a new navigation
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 parse navigation URL:', params.currentUrl, error);
}
}, [historyIndex, navigationHistory]);
const sendNavigationCommand = useCallback((method: string, params?: Record<string, unknown>) => {
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) => {
// Convert path to full URL
const fullUrl = `https://${projectId}.${IFRAME_DOMAIN}${url}`;
sendNavigationCommand('navigate', { url: fullUrl });
}, [projectId, sendNavigationCommand]);
const refreshIframe = useCallback(() => {
sendNavigationCommand('refresh');
}, [sendNavigationCommand]);
const goBackIframe = useCallback(() => {
sendNavigationCommand('goBack');
}, [sendNavigationCommand]);
const goForwardIframe = useCallback(() => {
sendNavigationCommand('goForward');
}, [sendNavigationCommand]);
const handleFetch = useCallback(async (request: JSONRPCRequest) => {
const { params, id } = request;
const { request: fetchRequest } = params;
@@ -348,12 +364,14 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
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) {
@@ -372,13 +390,13 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
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);
@@ -503,10 +521,10 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
<div className="flex items-center border-b w-full">
<BrowserAddressBar
currentPath={currentPath}
onNavigate={navigateToPath}
onNavigate={navigateIframe}
onRefresh={refreshIframe}
onBack={goBack}
onForward={goForward}
onBack={goBackIframe}
onForward={goForwardIframe}
canGoBack={historyIndex > 0}
canGoForward={historyIndex < navigationHistory.length - 1}
extraContent={<ConsoleDropdown />}
@@ -517,7 +535,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
src={`https://${projectId}.${IFRAME_DOMAIN}${currentPath}`}
className="w-full flex-1 border-0"
title="Project Preview"
sandbox="allow-scripts allow-same-origin"
sandbox="allow-scripts allow-same-origin allow-popups allow-forms allow-top-navigation"
/>
</div>
) : (