Add offline support

This commit is contained in:
Alex Gleason committed 2025-10-25 10:25:33 -05:00
1 parent d75bd386aa
commit cfa8f69ad5
12 files changed
+4328 -89

No files matched your search

+4
View File
@@ -22,6 +22,8 @@ import { ConsoleErrorProvider } from '@/components/ConsoleErrorProvider';
import { LightningFSAdapter } from '@/lib/LightningFSAdapter';
import { cleanupTmpDirectory } from '@/lib/tmpCleanup';
import { DynamicFavicon } from '@/components/DynamicFavicon';
import { OfflineIndicator } from '@/components/OfflineIndicator';
import { PWAUpdatePrompt } from '@/components/PWAUpdatePrompt';
import AppRouter from './AppRouter';
@@ -99,6 +101,8 @@ export function App() {
<TooltipProvider>
<Toaster />
<DynamicFavicon />
<OfflineIndicator />
<PWAUpdatePrompt />
<Suspense>
<AppRouter />
</Suspense>
+55
View File
@@ -0,0 +1,55 @@
import { WifiOff, Wifi } from 'lucide-react';
import { useEffect, useState } from 'react';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { useOffline } from '@/hooks/useOffline';
/**
* Component that displays an indicator when the app is offline
*/
export function OfflineIndicator() {
const { isOffline, isOnline } = useOffline();
const [showOnlineNotification, setShowOnlineNotification] = useState(false);
const [wasOffline, setWasOffline] = useState(false);
useEffect(() => {
if (isOffline) {
setWasOffline(true);
}
if (isOnline && wasOffline) {
// Show "back online" notification briefly
setShowOnlineNotification(true);
const timer = setTimeout(() => {
setShowOnlineNotification(false);
setWasOffline(false);
}, 3000);
return () => clearTimeout(timer);
}
}, [isOffline, isOnline, wasOffline]);
if (!isOffline && !showOnlineNotification) {
return null;
}
return (
<div className="fixed bottom-4 left-4 right-4 md:left-auto md:right-4 md:w-96 z-50 animate-in slide-in-from-bottom-4">
{isOffline ? (
<Alert variant="destructive" className="shadow-lg border-2">
<WifiOff className="h-4 w-4" />
<AlertDescription className="font-medium">
You're offline. Some features may be limited.
</AlertDescription>
</Alert>
) : (
<Alert className="shadow-lg border-2 border-green-500 bg-green-50 dark:bg-green-950">
<Wifi className="h-4 w-4 text-green-600 dark:text-green-400" />
<AlertDescription className="font-medium text-green-600 dark:text-green-400">
You're back online!
</AlertDescription>
</Alert>
)}
</div>
);
}
+89
View File
@@ -0,0 +1,89 @@
import { useEffect, useState } from 'react';
import { useRegisterSW } from 'virtual:pwa-register/react';
import { Button } from '@/components/ui/button';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Download, X } from 'lucide-react';
/**
* Component that prompts users to update when a new service worker is available
*/
export function PWAUpdatePrompt() {
const [showPrompt, setShowPrompt] = useState(false);
const {
offlineReady: [offlineReady],
needRefresh: [needRefresh, setNeedRefresh],
updateServiceWorker,
} = useRegisterSW({
onRegisteredSW(swUrl, registration) {
console.log('[PWA] Service worker registered:', swUrl);
// Check for updates periodically (every hour)
if (registration) {
setInterval(() => {
registration.update();
}, 60 * 60 * 1000);
}
},
onRegisterError(error) {
console.error('[PWA] Service worker registration error:', error);
},
});
useEffect(() => {
if (offlineReady) {
console.log('[PWA] App ready to work offline');
}
}, [offlineReady]);
useEffect(() => {
if (needRefresh) {
setShowPrompt(true);
}
}, [needRefresh]);
const handleUpdate = () => {
updateServiceWorker(true);
};
const handleDismiss = () => {
setShowPrompt(false);
setNeedRefresh(false);
};
if (!showPrompt) {
return null;
}
return (
<div className="fixed bottom-4 left-4 right-4 md:left-auto md:right-4 md:w-96 z-50 animate-in slide-in-from-bottom-4">
<Alert className="shadow-lg border-2 border-primary">
<Download className="h-4 w-4" />
<AlertTitle className="flex items-center justify-between">
New Version Available
<Button
variant="ghost"
size="icon"
className="h-6 w-6"
onClick={handleDismiss}
>
<X className="h-4 w-4" />
</Button>
</AlertTitle>
<AlertDescription className="space-y-3">
<p className="text-sm">
A new version of Shakespeare is available. Update now to get the latest features and improvements.
</p>
<div className="flex gap-2">
<Button onClick={handleUpdate} size="sm" className="flex-1">
Update Now
</Button>
<Button onClick={handleDismiss} size="sm" variant="outline">
Later
</Button>
</div>
</AlertDescription>
</Alert>
</div>
);
}
+57
View File
@@ -0,0 +1,57 @@
import { useEffect, useState } from 'react';
/**
* Hook to detect offline status and provide cache management utilities
*/
export function useOffline() {
const [isOnline, setIsOnline] = useState(navigator.onLine);
const [serviceWorkerRegistration, setServiceWorkerRegistration] = useState<ServiceWorkerRegistration | null>(null);
useEffect(() => {
const handleOnline = () => setIsOnline(true);
const handleOffline = () => setIsOnline(false);
window.addEventListener('online', handleOnline);
window.addEventListener('offline', handleOffline);
// Get service worker registration
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then((registration) => {
setServiceWorkerRegistration(registration);
}).catch((error) => {
console.error('[ServiceWorker] Failed to get registration:', error);
});
}
return () => {
window.removeEventListener('online', handleOnline);
window.removeEventListener('offline', handleOffline);
};
}, []);
const clearCache = async () => {
if ('caches' in window) {
const cacheNames = await caches.keys();
await Promise.all(
cacheNames
.filter(name => name.startsWith('workbox-') || name.includes('shakespeare'))
.map(name => caches.delete(name))
);
console.log('[Cache] Cleared all caches');
}
};
const updateServiceWorker = async () => {
if (serviceWorkerRegistration) {
await serviceWorkerRegistration.update();
}
};
return {
isOnline,
isOffline: !isOnline,
serviceWorkerRegistration,
clearCache,
updateServiceWorker,
};
}
+21
View File
@@ -236,6 +236,13 @@ const resources = {
// Data Settings
dataSettingsDescriptionLong: 'Export files and manage local data.',
offlineCache: 'Offline Cache',
offlineCacheDescription: 'Shakespeare caches files locally to enable offline functionality. Clear the cache to free up space or troubleshoot issues.',
cacheSize: 'Cache size',
clearCache: 'Clear Cache',
cacheClearedSuccessfully: 'Cache Cleared',
cacheClearedDescription: 'Offline cache has been cleared successfully.',
failedToClearCache: 'Failed to Clear Cache',
exportFiles: 'Export Files',
exportFilesDescription: 'Download all your projects and files as a ZIP archive. This includes all project files, settings, and data stored locally.',
exportAllFiles: 'Export All Files',
@@ -563,6 +570,13 @@ const resources = {
// Data Settings
dataSettingsDescriptionLong: 'Exporte arquivos e gerencie dados locais.',
offlineCache: 'Cache Offline',
offlineCacheDescription: 'O Shakespeare armazena arquivos localmente para permitir funcionalidade offline. Limpe o cache para liberar espaço ou solucionar problemas.',
cacheSize: 'Tamanho do cache',
clearCache: 'Limpar Cache',
cacheClearedSuccessfully: 'Cache Limpo',
cacheClearedDescription: 'O cache offline foi limpo com sucesso.',
failedToClearCache: 'Falha ao Limpar Cache',
exportFiles: 'Exportar Arquivos',
exportFilesDescription: 'Baixe todos os seus projetos e arquivos como um arquivo ZIP. Isso inclui todos os arquivos de projeto, configurações e dados armazenados localmente.',
exportAllFiles: 'Exportar Todos os Arquivos',
@@ -899,6 +913,13 @@ const resources = {
// Data Settings
dataSettingsDescriptionLong: '导出文件和管理本地数据。',
offlineCache: '离线缓存',
offlineCacheDescription: 'Shakespeare在本地缓存文件以启用离线功能。清除缓存以释放空间或解决问题。',
cacheSize: '缓存大小',
clearCache: '清除缓存',
cacheClearedSuccessfully: '缓存已清除',
cacheClearedDescription: '离线缓存已成功清除。',
failedToClearCache: '清除缓存失败',
exportFiles: '导出文件',
exportFilesDescription: '将您的所有项目和文件下载为ZIP存档。这包括所有项目文件、设置和本地存储的数据。',
exportAllFiles: '导出所有文件',
-14
View File
@@ -16,17 +16,3 @@ import '@fontsource-variable/inter';
import 'prismjs/themes/prism.css';
createRoot(document.getElementById("root")!).render(<App />);
// Register service worker
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker
.register('/sw.js')
.then((registration) => {
console.log('[ServiceWorker] Registered:', registration);
})
.catch((error) => {
console.error('[ServiceWorker] Registration failed:', error);
});
});
}
+91 -2
View File
@@ -1,7 +1,7 @@
import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Download, Trash2, AlertTriangle, Loader2, Database, Info, ArrowLeft, Shield } from 'lucide-react';
import { Download, Trash2, AlertTriangle, Loader2, Database, Info, ArrowLeft, Shield, HardDrive } 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';
@@ -10,6 +10,7 @@ import { Switch } from '@/components/ui/switch';
import { useToast } from '@/hooks/useToast';
import { useFS } from '@/hooks/useFS';
import { useIsMobile } from '@/hooks/useIsMobile';
import { useOffline } from '@/hooks/useOffline';
import {
isPersistentStorageSupported,
isPersistentStorageGranted,
@@ -35,14 +36,17 @@ export function StorageSettings() {
const { t } = useTranslation();
const [isExporting, setIsExporting] = useState(false);
const [isClearing, setIsClearing] = useState(false);
const [isClearingCache, setIsClearingCache] = 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 [cacheSize, setCacheSize] = useState<number>(0);
const { toast } = useToast();
const { fs } = useFS();
const navigate = useNavigate();
const isMobile = useIsMobile();
const { clearCache } = useOffline();
// Format bytes to human readable format
const formatBytes = (bytes: number): string => {
@@ -76,6 +80,30 @@ export function StorageSettings() {
// Check if storage is persistent
const persistent = await isPersistentStorageGranted();
setIsPersistent(persistent);
// Calculate cache size
if ('caches' in window) {
const cacheNames = await caches.keys();
let totalSize = 0;
for (const cacheName of cacheNames) {
// Include both workbox and shakespeare caches
if (cacheName.startsWith('workbox-') || cacheName.includes('shakespeare')) {
const cache = await caches.open(cacheName);
const requests = await cache.keys();
for (const request of requests) {
const response = await cache.match(request);
if (response) {
const blob = await response.blob();
totalSize += blob.size;
}
}
}
}
setCacheSize(totalSize);
}
} catch (error) {
console.error('Failed to get storage information:', error);
setStorageError(error instanceof Error ? error.message : 'Failed to get storage information');
@@ -83,7 +111,7 @@ export function StorageSettings() {
};
loadStorageInfo();
}, []);
}, [isClearingCache]);
const exportFilesAsZip = async () => {
const zip = new JSZip();
@@ -217,12 +245,37 @@ export function StorageSettings() {
}
};
const handleClearCache = async () => {
setIsClearingCache(true);
try {
await clearCache();
setCacheSize(0);
toast({
title: t('cacheClearedSuccessfully'),
description: t('cacheClearedDescription'),
});
} catch (error) {
console.error('Failed to clear cache:', error);
toast({
title: t('failedToClearCache'),
description: error instanceof Error ? error.message : t('error'),
variant: "destructive",
});
} finally {
setIsClearingCache(false);
}
};
const handleClearAllData = async () => {
setIsClearing(true);
try {
// Clear localStorage
localStorage.clear();
// Clear caches
await clearCache();
// Clear IndexedDB databases
const databases = await indexedDB.databases();
const deletePromises = databases.map(db => {
@@ -359,6 +412,42 @@ export function StorageSettings() {
</CardContent>
</Card>
{/* Clear Cache */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<HardDrive className="h-5 w-5" />
{t('offlineCache')}
</CardTitle>
<CardDescription>
{t('offlineCacheDescription')}
</CardDescription>
</CardHeader>
<CardContent className="space-y-3">
<div className="text-sm text-muted-foreground">
{t('cacheSize')}: {formatBytes(cacheSize)}
</div>
<Button
onClick={handleClearCache}
disabled={isClearingCache}
variant="outline"
className="w-full sm:w-auto"
>
{isClearingCache ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
{t('clearing')}
</>
) : (
<>
<Trash2 className="h-4 w-4 mr-2" />
{t('clearCache')}
</>
)}
</Button>
</CardContent>
</Card>
{/* Export Files */}
<Card>
<CardHeader>
+1
View File
@@ -1,4 +1,5 @@
/// <reference types="vite/client" />
/// <reference types="vite-plugin-pwa/client" />
interface ImportMetaEnv {
readonly VITE_GITHUB_OAUTH_CLIENT_ID?: string;