mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Merge branch 'main' of gitlab.com:soapbox-pub/act2 into consoleFramev2
This commit is contained in:
commit
6296fc4366
12 files changed
+802
-92
No files matched your search
@@ -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');
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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>
|
||||
|
||||
Reference in new issue
Block a user