mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Add offline support
This commit is contained in:
12 files changed
+4328
-89
No files matched your search
@@ -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,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user