Merge branch 'main' of gitlab.com:soapbox-pub/act2 into consoleFramev2

This commit is contained in:
Chad Curtis committed 2025-09-25 04:42:50 +00:00
commit 6296fc4366
12 files changed
+802 -92

No files matched your search

+30
View File
@@ -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
+29 -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,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:
+227 -1
View File
@@ -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) {
+60 -14
View File
@@ -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));
});
+128 -62
View File
@@ -181,67 +181,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);
}
@@ -278,11 +234,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<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) => {
// 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
@@ -306,6 +343,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);
@@ -326,11 +366,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}`);
@@ -350,7 +409,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',
@@ -395,12 +454,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) {
@@ -408,11 +469,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(() => {
@@ -426,13 +492,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);
@@ -611,10 +677,10 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
<div className="h-12 flex items-center w-full">
<BrowserAddressBar
currentPath={currentPath}
onNavigate={hasBuiltProject ? navigateToPath : undefined}
onNavigate={hasBuiltProject ? navigateIframe : undefined}
onRefresh={hasBuiltProject ? refreshIframe : undefined}
onBack={hasBuiltProject ? goBack : undefined}
onForward={hasBuiltProject ? goForward : undefined}
onBack={hasBuiltProject ? goBackIframe : undefined}
onForward={hasBuiltProject ? goForwardIframe : undefined}
canGoBack={hasBuiltProject && historyIndex > 0}
canGoForward={hasBuiltProject && historyIndex < navigationHistory.length - 1}
extraContent={(
@@ -641,7 +707,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
{hasBuiltProject ? (
<iframe
ref={iframeRef}
src={`https://${projectId}.${IFRAME_DOMAIN}${currentPath}`}
src={`https://${projectId}.${IFRAME_DOMAIN}/`}
className="w-full h-full border-0"
title="Project Preview"
sandbox="allow-scripts allow-same-origin"
@@ -81,4 +81,21 @@ describe('BrowserAddressBar', () => {
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();
if (!onNavigate) return;
+17
View File
@@ -1,6 +1,7 @@
import { Buffer } from 'buffer';
import type { Git } from '@/lib/git';
import type { JSRuntimeFS } from '@/lib/JSRuntime';
import { ensurePersistentStorage } from '@/lib/persistentStorage';
// Polyfill Buffer for browser
if (typeof window !== 'undefined') {
@@ -92,6 +93,14 @@ export class ProjectsManager {
},
});
// Automatically request persistent storage after project creation
try {
await ensurePersistentStorage();
} catch (error) {
// Don't fail project creation if persistent storage request fails
console.warn('Failed to request persistent storage after project creation:', error);
}
return project;
}
@@ -119,6 +128,14 @@ export class ProjectsManager {
const stats = await this.fs.stat(projectPath);
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
// Automatically request persistent storage after project cloning
try {
await ensurePersistentStorage();
} catch (error) {
// Don't fail project cloning if persistent storage request fails
console.warn('Failed to request persistent storage after project cloning:', error);
}
// Return the full project object with dynamically generated properties
return {
id,
+66
View File
@@ -242,6 +242,17 @@ const resources = {
dataClearedSuccessfully: 'Data cleared successfully',
dataClearedDescription: 'All local data has been removed. Redirecting to homepage...',
failedToClearData: 'Failed to clear data',
persistData: 'Persist Data',
persistDataDescription: 'Request persistent storage to prevent data loss when browser storage is low. This helps protect your projects and settings.',
persistentStorageGranted: 'Persistent storage granted',
persistentStorageGrantedDescription: 'Your browser will now protect your data from automatic cleanup.',
persistentStorageAlreadyGranted: 'Persistent storage already granted',
persistentStorageAlreadyGrantedDescription: 'Your data is already protected from automatic cleanup.',
persistentStorageDenied: 'Persistent storage request denied',
persistentStorageDeniedDescription: 'Your browser declined the request. Data may still be cleared automatically when storage is low.',
persistentStorageNotSupported: 'Persistent storage not supported',
persistentStorageNotSupportedDescription: 'Your browser does not support persistent storage requests.',
failedToRequestPersistentStorage: 'Failed to request persistent storage',
// 404 Page
pageNotFound: 'Oops! Page not found',
@@ -534,6 +545,17 @@ const resources = {
dataClearedSuccessfully: 'Dados limpos com sucesso',
dataClearedDescription: 'Todos os dados locais foram removidos. Redirecionando para a página inicial...',
failedToClearData: 'Falha ao limpar dados',
persistData: 'Persistir Dados',
persistDataDescription: 'Solicitar armazenamento persistente para evitar perda de dados quando o armazenamento do navegador estiver baixo. Isso ajuda a proteger seus projetos e configurações.',
persistentStorageGranted: 'Armazenamento persistente concedido',
persistentStorageGrantedDescription: 'Seu navegador agora protegerá seus dados da limpeza automática.',
persistentStorageAlreadyGranted: 'Armazenamento persistente já concedido',
persistentStorageAlreadyGrantedDescription: 'Seus dados já estão protegidos da limpeza automática.',
persistentStorageDenied: 'Solicitação de armazenamento persistente negada',
persistentStorageDeniedDescription: 'Seu navegador recusou a solicitação. Os dados ainda podem ser limpos automaticamente quando o armazenamento estiver baixo.',
persistentStorageNotSupported: 'Armazenamento persistente não suportado',
persistentStorageNotSupportedDescription: 'Seu navegador não suporta solicitações de armazenamento persistente.',
failedToRequestPersistentStorage: 'Falha ao solicitar armazenamento persistente',
// About Settings
aboutShakespeare: 'Sobre o Shakespeare',
@@ -836,6 +858,17 @@ const resources = {
dataClearedSuccessfully: '数据清除成功',
dataClearedDescription: '所有本地数据已删除。正在重定向到主页...',
failedToClearData: '清除数据失败',
persistData: '持久化数据',
persistDataDescription: '请求持久存储以防止浏览器存储不足时数据丢失。这有助于保护您的项目和设置。',
persistentStorageGranted: '已授予持久存储',
persistentStorageGrantedDescription: '您的浏览器现在将保护您的数据免受自动清理。',
persistentStorageAlreadyGranted: '已授予持久存储',
persistentStorageAlreadyGrantedDescription: '您的数据已受到保护,不会被自动清理。',
persistentStorageDenied: '持久存储请求被拒绝',
persistentStorageDeniedDescription: '您的浏览器拒绝了请求。当存储不足时,数据仍可能被自动清理。',
persistentStorageNotSupported: '不支持持久存储',
persistentStorageNotSupportedDescription: '您的浏览器不支持持久存储请求。',
failedToRequestPersistentStorage: '请求持久存储失败',
// About Settings
aboutShakespeare: '关于Shakespeare',
@@ -1138,6 +1171,17 @@ const resources = {
dataClearedSuccessfully: 'An share bayanai cikin nasara',
dataClearedDescription: 'An cire duk bayanan gida. Ana turawa zuwa shafin gida...',
failedToClearData: 'Ya gaza share bayanai',
persistData: 'Kiyaye Bayanai',
persistDataDescription: 'Nemi ajiyar bayanai ta dindindin don hana asarar bayanai lokacin da ajiyar burauzar ta ragu. Wannan yana taimakawa wajen kare ayyukan ku da saitunan.',
persistentStorageGranted: 'An ba da ajiyar ta dindindin',
persistentStorageGrantedDescription: 'Burauzar ku yanzu za ta kare bayananku daga share mai sarrafa kansa.',
persistentStorageAlreadyGranted: 'An riga an ba da ajiyar ta dindindin',
persistentStorageAlreadyGrantedDescription: 'An riga an kare bayananku daga share mai sarrafa kansa.',
persistentStorageDenied: 'An ki neman ajiyar ta dindindin',
persistentStorageDeniedDescription: 'Burauzar ku ta ki bukatar. Ana iya share bayanai ta atomatik lokacin da ajiya ta ragu.',
persistentStorageNotSupported: 'Ba a goyan bayan ajiyar ta dindindin ba',
persistentStorageNotSupportedDescription: 'Burauzar ku ba ta goyan bayan bukatun ajiyar ta dindindin ba.',
failedToRequestPersistentStorage: 'Ya gaza neman ajiyar ta dindindin',
// About Settings
aboutShakespeare: 'Game da Shakespeare',
@@ -1440,6 +1484,17 @@ const resources = {
dataClearedSuccessfully: 'Data ti nu ni aṣeyọri',
dataClearedDescription: 'Gbogbo data agbegbe ti yọ kuro. N ṣe atunṣe si oju-iwe ile...',
failedToClearData: 'O kuna lati nu data',
persistData: 'Fi Data Pamọ',
persistDataDescription: 'Beere ibi ipamọ ti o wa nigbagbogbo lati yago fun isonu data nigbati ibi ipamọ aṣawakiri ba kere. Eyi ṣe iranlọwọ lati daabobo awọn iṣẹ akanṣe ati awọn eto rẹ.',
persistentStorageGranted: 'Ibi ipamọ ti o wa nigbagbogbo ti funni',
persistentStorageGrantedDescription: 'Aṣawakiri rẹ yoo daabobo data rẹ lati imukuro adaṣe.',
persistentStorageAlreadyGranted: 'Ibi ipamọ ti o wa nigbagbogbo ti funni tẹlẹ',
persistentStorageAlreadyGrantedDescription: 'Data rẹ ti wa ni aabo lati imukuro adaṣe.',
persistentStorageDenied: 'Ibeere ibi ipamọ ti o wa nigbagbogbo ti kọ',
persistentStorageDeniedDescription: 'Aṣawakiri rẹ ti kọ ibeere naa. Data le tun jẹ imukuro adaṣe nigbati ibi ipamọ ba kere.',
persistentStorageNotSupported: 'Ibi ipamọ ti o wa nigbagbogbo ko ni atilẹyin',
persistentStorageNotSupportedDescription: 'Aṣawakiri rẹ ko ni atilẹyin awọn ibeere ibi ipamọ ti o wa nigbagbogbo.',
failedToRequestPersistentStorage: 'O kuna lati beere ibi ipamọ ti o wa nigbagbogbo',
// About Settings
aboutShakespeare: 'Nipa Shakespeare',
@@ -1737,6 +1792,17 @@ const resources = {
dataClearedSuccessfully: 'Ehichapụrụ data nke ọma',
dataClearedDescription: 'Ewepụrụ data mpaghara niile. Na-atụgharị gaa na ibe ụlọ...',
failedToClearData: 'O dara ihichapụ data',
persistData: 'Chekwaa Data Ogologo Oge',
persistDataDescription: 'Rịọ nchekwa na-adịgide adịgide iji gbochie mfu data mgbe nchekwa browser dị ala. Nke a na-enyere aka ichebe ọrụ gị na ntọala.',
persistentStorageGranted: 'Enyere nchekwa na-adịgide adịgide',
persistentStorageGrantedDescription: 'Browser gị ga-echebe data gị ugbu a site na nhicha akpaaka.',
persistentStorageAlreadyGranted: 'Enyerela nchekwa na-adịgide adịgide',
persistentStorageAlreadyGrantedDescription: 'Echebeela data gị site na nhicha akpaaka.',
persistentStorageDenied: 'Ajụrụ arịrịọ nchekwa na-adịgide adịgide',
persistentStorageDeniedDescription: 'Browser gị jụrụ arịrịọ ahụ. Enwere ike ihichapụ data akpaaka mgbe nchekwa dị ala.',
persistentStorageNotSupported: 'Akwadoghị nchekwa na-adịgide adịgide',
persistentStorageNotSupportedDescription: 'Browser gị akwadoghị arịrịọ nchekwa na-adịgide adịgide.',
failedToRequestPersistentStorage: 'O dara ịrịọ nchekwa na-adịgide adịgide',
// About Settings
aboutShakespeare: 'Gbasara Shakespeare',
+111
View File
@@ -0,0 +1,111 @@
/**
* Utility functions for managing persistent storage in the browser
*/
/**
* Checks if persistent storage is supported by the browser
*/
export function isPersistentStorageSupported(): boolean {
return 'storage' in navigator && 'persist' in navigator.storage;
}
/**
* Checks if persistent storage is already granted
*/
export async function isPersistentStorageGranted(): Promise<boolean> {
if (!isPersistentStorageSupported()) {
return false;
}
try {
return await navigator.storage.persisted();
} catch (error) {
console.warn('Failed to check persistent storage status:', error);
return false;
}
}
/**
* Requests persistent storage from the browser
* Returns true if granted, false if denied or not supported
*/
export async function requestPersistentStorage(): Promise<boolean> {
if (!isPersistentStorageSupported()) {
console.warn('Persistent storage is not supported in this browser');
return false;
}
try {
// Check if already granted
const alreadyGranted = await isPersistentStorageGranted();
if (alreadyGranted) {
return true;
}
// Request persistent storage
const granted = await navigator.storage.persist();
return granted;
} catch (error) {
console.warn('Failed to request persistent storage:', error);
return false;
}
}
/**
* Automatically requests persistent storage if not already granted
* This is intended to be called silently after project creation/cloning
* Returns true if persistent storage is available (either already granted or newly granted)
*/
export async function ensurePersistentStorage(): Promise<boolean> {
try {
// Check if already granted
const alreadyGranted = await isPersistentStorageGranted();
if (alreadyGranted) {
return true;
}
// Only request if supported
if (!isPersistentStorageSupported()) {
return false;
}
// Silently request persistent storage
const granted = await requestPersistentStorage();
if (granted) {
console.log('Persistent storage granted automatically');
} else {
console.log('Persistent storage request denied or failed');
}
return granted;
} catch (error) {
console.warn('Failed to ensure persistent storage:', error);
return false;
}
}
/**
* Gets current storage usage information
*/
export async function getStorageInfo(): Promise<{
quota: number;
usage: number;
usageDetails?: Record<string, number>;
} | null> {
if (!('storage' in navigator)) {
return null;
}
try {
const estimate = await navigator.storage.estimate();
return {
quota: estimate.quota || 0,
usage: estimate.usage || 0,
usageDetails: (estimate as StorageEstimate & { usageDetails?: Record<string, number> }).usageDetails,
};
} catch (error) {
console.warn('Failed to get storage information:', error);
return null;
}
}
+8 -1
View File
@@ -17,6 +17,9 @@ describe('DataSettings', () => {
// Check for description
expect(screen.getByText('Export files and manage local data.')).toBeInTheDocument();
// Check for Persist Data section
expect(screen.getByText('Persist Data')).toBeInTheDocument();
// Check for Export Files section
expect(screen.getByText('Export Files')).toBeInTheDocument();
expect(screen.getByText('Export All Files')).toBeInTheDocument();
@@ -26,13 +29,17 @@ describe('DataSettings', () => {
expect(screen.getByRole('button', { name: /clear all data/i })).toBeInTheDocument();
});
it('shows export and clear buttons', () => {
it('shows persist data toggle, export and clear buttons', () => {
render(
<TestApp>
<DataSettings />
</TestApp>
);
// Persist storage toggle should be visible
const persistToggle = screen.getByRole('switch');
expect(persistToggle).toBeInTheDocument();
// Export button should be visible
const exportButton = screen.getByRole('button', { name: /export all files/i });
expect(exportButton).toBeInTheDocument();
+103 -12
View File
@@ -1,14 +1,21 @@
import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Download, Trash2, AlertTriangle, Loader2, Database, Info, ArrowLeft } from 'lucide-react';
import { Download, Trash2, AlertTriangle, Loader2, Database, Info, ArrowLeft, Shield } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';
import { Progress } from '@/components/ui/progress';
import { Switch } from '@/components/ui/switch';
import { useToast } from '@/hooks/useToast';
import { useFS } from '@/hooks/useFS';
import { useIsMobile } from '@/hooks/useIsMobile';
import {
isPersistentStorageSupported,
isPersistentStorageGranted,
requestPersistentStorage,
getStorageInfo
} from '@/lib/persistentStorage';
import JSZip from 'jszip';
interface StorageUsageDetails {
@@ -28,8 +35,10 @@ export function DataSettings() {
const { t } = useTranslation();
const [isExporting, setIsExporting] = useState(false);
const [isClearing, setIsClearing] = useState(false);
const [isRequestingPersistent, setIsRequestingPersistent] = useState(false);
const [storageInfo, setStorageInfo] = useState<StorageInfo | null>(null);
const [storageError, setStorageError] = useState<string | null>(null);
const [isPersistent, setIsPersistent] = useState<boolean | null>(null);
const { toast } = useToast();
const { fs } = useFS();
const navigate = useNavigate();
@@ -44,27 +53,29 @@ export function DataSettings() {
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};
// Load storage information
// Load storage information and persistent status
useEffect(() => {
const loadStorageInfo = async () => {
try {
// Check if StorageManager API is available
if (!('storage' in navigator)) {
if (!isPersistentStorageSupported()) {
setStorageError('StorageManager API is not available in this browser');
return;
}
// Get storage estimate
const estimate = await navigator.storage.estimate();
const info = await getStorageInfo();
if (info) {
setStorageInfo({
quota: info.quota,
usage: info.usage,
usageDetails: info.usageDetails as StorageUsageDetails,
});
}
// Extract usage details safely
const usageDetails: StorageUsageDetails | undefined = (estimate as StorageEstimate & { usageDetails?: StorageUsageDetails }).usageDetails;
setStorageInfo({
quota: estimate.quota || 0,
usage: estimate.usage || 0,
usageDetails,
});
// Check if storage is persistent
const persistent = await isPersistentStorageGranted();
setIsPersistent(persistent);
} catch (error) {
console.error('Failed to get storage information:', error);
setStorageError(error instanceof Error ? error.message : 'Failed to get storage information');
@@ -149,6 +160,63 @@ export function DataSettings() {
}
};
const handlePersistentStorageToggle = async (checked: boolean) => {
// If trying to turn off, we can't actually do that - just ignore
if (!checked) {
return;
}
setIsRequestingPersistent(true);
try {
// Check if persist method is available
if (!isPersistentStorageSupported()) {
toast({
title: t('persistentStorageNotSupported'),
description: t('persistentStorageNotSupportedDescription'),
variant: "destructive",
});
return;
}
// Check if already persistent
const alreadyPersistent = await isPersistentStorageGranted();
if (alreadyPersistent) {
setIsPersistent(true);
toast({
title: t('persistentStorageAlreadyGranted'),
description: t('persistentStorageAlreadyGrantedDescription'),
});
return;
}
// Request persistent storage
const granted = await requestPersistentStorage();
if (granted) {
setIsPersistent(true);
toast({
title: t('persistentStorageGranted'),
description: t('persistentStorageGrantedDescription'),
});
} else {
toast({
title: t('persistentStorageDenied'),
description: t('persistentStorageDeniedDescription'),
variant: "destructive",
});
}
} catch (error) {
console.error('Failed to request persistent storage:', error);
toast({
title: t('failedToRequestPersistentStorage'),
description: error instanceof Error ? error.message : t('error'),
variant: "destructive",
});
} finally {
setIsRequestingPersistent(false);
}
};
const handleClearAllData = async () => {
setIsClearing(true);
try {
@@ -268,6 +336,29 @@ export function DataSettings() {
</div>
)}
{/* Persist Data */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Shield className="h-5 w-5" />
{t('persistData')}
</CardTitle>
<CardDescription>
{t('persistDataDescription')}
</CardDescription>
</CardHeader>
<CardContent>
<div className="flex items-center justify-start">
<Switch
id="persistent-storage"
checked={isPersistent === true}
onCheckedChange={handlePersistentStorageToggle}
disabled={isRequestingPersistent || isPersistent === null}
/>
</div>
</CardContent>
</Card>
{/* Export Files */}
<Card>
<CardHeader>