feat: Added PWA features for offline support and faster loading

This commit is contained in:
Fechin committed 2025-06-18 15:51:52 +08:00
1 parent 172342c8a3
commit 80cd7559fc
16 files changed
+500

No files matched your search

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB

+4
View File
@@ -0,0 +1,4 @@
<svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" width="1em" height="1em">
<path d="M234.624 932.864a43.52 43.52 0 0 1-58.688-17.024 46.528 46.528 0 0 1-5.248-21.248V584.896c0 30.72 17.28 49.664 62.848 70.912l278.08 138.688-276.992 138.368z" fill="#6ad09d" opacity=".4"></path>
<path d="M642.944 85.312c115.584 0 209.28 45.504 210.368 161.92v647.36a44.992 44.992 0 0 1-5.248 20.864 43.328 43.328 0 0 1-59.84 17.408L511.616 794.496l-278.08-138.688c-45.568-21.248-62.848-40.192-62.848-70.912V247.168c0-116.352 93.696-161.856 208.832-161.856z m28.992 257.792H350.912a33.6 33.6 0 0 0-33.472 33.728c0 18.56 14.976 33.728 33.472 33.728H672a33.6 33.6 0 0 0 33.472-33.728A33.6 33.6 0 0 0 672 343.104z" fill="#6ad09d"></path>
</svg>

After

Width:  |  Height:  |  Size: 760 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

+105
View File
@@ -0,0 +1,105 @@
{
"name": "CheatSheets.zip - Ultimate Cheat Sheets for Developers",
"short_name": "CheatSheets",
"description": "Share quick reference and cheat sheet for developers",
"start_url": "/",
"display": "standalone",
"background_color": "#ffffff",
"theme_color": "#10b981",
"orientation": "portrait-primary",
"scope": "/",
"lang": "en",
"categories": ["productivity", "developer", "reference"],
"icons": [
{
"src": "/assets/logo/icon-72x72.png",
"sizes": "72x72",
"type": "image/png",
"purpose": "maskable any"
},
{
"src": "/assets/logo/icon-96x96.png",
"sizes": "96x96",
"type": "image/png",
"purpose": "maskable any"
},
{
"src": "/assets/logo/icon-128x128.png",
"sizes": "128x128",
"type": "image/png",
"purpose": "maskable any"
},
{
"src": "/assets/logo/icon-144x144.png",
"sizes": "144x144",
"type": "image/png",
"purpose": "maskable any"
},
{
"src": "/assets/logo/icon-152x152.png",
"sizes": "152x152",
"type": "image/png",
"purpose": "maskable any"
},
{
"src": "/assets/logo/icon-192x192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "maskable any"
},
{
"src": "/assets/logo/icon-384x384.png",
"sizes": "384x384",
"type": "image/png",
"purpose": "maskable any"
},
{
"src": "/assets/logo/icon-512x512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable any"
}
],
"screenshots": [
{
"src": "/assets/screenshots/desktop-1280x720.png",
"sizes": "1280x720",
"type": "image/png",
"form_factor": "wide",
"label": "Desktop view of CheatSheets.zip"
},
{
"src": "/assets/screenshots/mobile-390x844.png",
"sizes": "390x844",
"type": "image/png",
"form_factor": "narrow",
"label": "Mobile view of CheatSheets.zip"
}
],
"shortcuts": [
{
"name": "Search Cheat Sheets",
"short_name": "Search",
"description": "Quickly search through all cheat sheets",
"url": "/?q=",
"icons": [
{
"src": "/assets/logo/icon-96x96.png",
"sizes": "96x96"
}
]
},
{
"name": "Popular Cheat Sheets",
"short_name": "Popular",
"description": "View most popular cheat sheets",
"url": "/#popular",
"icons": [
{
"src": "/assets/logo/icon-96x96.png",
"sizes": "96x96"
}
]
}
]
}
+299
View File
@@ -0,0 +1,299 @@
// CheatSheets.zip Service Worker
const STATIC_CACHE = 'cheatsheets-static-v1';
const DYNAMIC_CACHE = 'cheatsheets-dynamic-v1';
// Static assets to cache
const STATIC_ASSETS = [
'/',
'/css/style.css',
'/js/main.js',
'/js/fuse_6.4.6.js',
'/manifest.json',
'/search.json'
];
// Page patterns to cache
const CACHE_PATTERNS = [
/^\/$/, // Home page
/^\/[a-z-]+\.html$/, // Cheat sheet pages
/^\/assets\//, // Static assets
/^\/css\//, // CSS files
/^\/js\//, // JavaScript files
/^\/images\// // Image files
];
// Service Worker installevent
self.addEventListener('install', (event) => {
// eslint-disable-next-line no-console
console.log('Service Worker: Installing...');
event.waitUntil(
caches
.open(STATIC_CACHE)
.then((cache) => {
// eslint-disable-next-line no-console
console.log('Service Worker: Caching static assets');
return cache.addAll(STATIC_ASSETS);
})
.then(() => {
// eslint-disable-next-line no-console
console.log('Service Worker: Static assets cached');
return self.skipWaiting();
})
.catch((error) => {
// eslint-disable-next-line no-console
console.error('Service Worker: Cache failed', error);
})
);
});
// Service Worker activate event
self.addEventListener('activate', (event) => {
// eslint-disable-next-line no-console
console.log('Service Worker: Activating...');
event.waitUntil(
caches
.keys()
.then((cacheNames) => {
return Promise.all(
cacheNames.map((cacheName) => {
// Delete old cache versions
if (cacheName !== STATIC_CACHE && cacheName !== DYNAMIC_CACHE) {
// eslint-disable-next-line no-console
console.log('Service Worker: Deleting old cache', cacheName);
return caches.delete(cacheName);
}
})
);
})
.then(() => {
// eslint-disable-next-line no-console
console.log('Service Worker: Activated');
return self.clients.claim();
})
);
});
// Network request interception
self.addEventListener('fetch', (event) => {
const { request } = event;
const url = new URL(request.url);
// Only handle same-origin requests
if (url.origin !== location.origin) {
return;
}
// Check if matches cache pattern
const shouldCache = CACHE_PATTERNS.some((pattern) => pattern.test(url.pathname));
if (shouldCache) {
event.respondWith(handleCacheRequest(request));
}
});
// Cache request handling strategy
async function handleCacheRequest(request) {
const url = new URL(request.url);
try {
// 1. Try to get from cache
const cachedResponse = await caches.match(request);
// 2. If it's a static asset and cached, return directly
if (cachedResponse && isStaticAsset(url.pathname)) {
return cachedResponse;
}
// 3. Try network request
const networkResponse = await fetch(request);
// 4. If network request succeeds, update cache
if (networkResponse.ok) {
const cache = await caches.open(DYNAMIC_CACHE);
cache.put(request, networkResponse.clone());
return networkResponse;
}
// 5. Network failed, return cache (if available)
if (cachedResponse) {
return cachedResponse;
}
// 6. Nothing available, return offline page
return createOfflineResponse(url.pathname);
} catch (error) {
// eslint-disable-next-line no-console
console.error('Service Worker: Fetch failed', error);
// Network error, try to return cache
const cachedResponse = await caches.match(request);
if (cachedResponse) {
return cachedResponse;
}
// Return offline page
return createOfflineResponse(url.pathname);
}
}
// Check if it's a static asset
function isStaticAsset(pathname) {
return /\.(css|js|png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$/.test(pathname);
}
// Create offline response
function createOfflineResponse(pathname) {
const isHtmlPage = pathname.endsWith('.html') || pathname === '/';
if (isHtmlPage) {
return new Response(
`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Offline - CheatSheets.zip</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background: #f8f9fa;
color: #333;
}
.offline-container {
text-align: center;
max-width: 400px;
padding: 2rem;
background: white;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}
.offline-icon {
font-size: 4rem;
margin-bottom: 1rem;
}
.offline-title {
font-size: 1.5rem;
margin-bottom: 1rem;
color: #10b981;
}
.offline-message {
margin-bottom: 1.5rem;
line-height: 1.6;
}
.retry-button {
background: #10b981;
color: white;
border: none;
padding: 0.75rem 1.5rem;
border-radius: 4px;
cursor: pointer;
font-size: 1rem;
}
.retry-button:hover {
background: #059669;
}
</style>
</head>
<body>
<div class="offline-container">
<div class="offline-icon">📚</div>
<h1 class="offline-title">You're Offline</h1>
<p class="offline-message">
This page isn't available offline yet. Please check your internet connection and try again.
</p>
<button class="retry-button" onclick="window.location.reload()">
Try Again
</button>
</div>
</body>
</html>
`,
{
status: 200,
headers: {
'Content-Type': 'text/html; charset=utf-8',
'Cache-Control': 'no-cache'
}
}
);
}
return new Response('Offline', {
status: 503,
statusText: 'Service Unavailable'
});
}
// Background sync (if supported)
if ('sync' in self.registration) {
self.addEventListener('sync', (event) => {
if (event.tag === 'background-sync') {
event.waitUntil(doBackgroundSync());
}
});
}
async function doBackgroundSync() {
try {
// Sync search data
const response = await fetch('/search.json');
if (response.ok) {
const cache = await caches.open(DYNAMIC_CACHE);
cache.put('/search.json', response);
}
} catch (error) {
// eslint-disable-next-line no-console
console.error('Background sync failed:', error);
}
}
// Push notifications (if needed)
self.addEventListener('push', (event) => {
if (event.data) {
const data = event.data.json();
const options = {
body: data.body,
icon: '/assets/icons/icon-192x192.png',
badge: '/assets/icons/icon-72x72.png',
vibrate: [100, 50, 100],
data: {
dateOfArrival: Date.now(),
primaryKey: data.primaryKey
},
actions: [
{
action: 'explore',
title: 'View Cheat Sheet',
icon: '/assets/icons/icon-96x96.png'
},
{
action: 'close',
title: 'Close',
icon: '/assets/icons/icon-96x96.png'
}
]
};
event.waitUntil(self.registration.showNotification(data.title, options));
}
});
// Notification click handling
self.addEventListener('notificationclick', (event) => {
event.notification.close();
if (event.action === 'explore') {
event.waitUntil(
// eslint-disable-next-line no-undef
clients.openWindow('/')
);
}
});
+12
View File
@@ -35,6 +35,18 @@
<link rel="icon" href="/images/favicon.png?v=1"/>
<link rel="icon shortcut" type="image/png" href="/images/favicon.png?v=1"/>
<!-- PWA -->
<link rel="manifest" href="/manifest.json"/>
<meta name="theme-color" content="#10b981"/>
<meta name="apple-mobile-web-app-capable" content="yes"/>
<meta name="apple-mobile-web-app-status-bar-style" content="default"/>
<meta name="apple-mobile-web-app-title" content="CheatSheets"/>
<link rel="apple-touch-icon" href="/assets/logo/icon-192x192.png"/>
<link rel="apple-touch-icon" sizes="152x152" href="/assets/logo/icon-152x152.png"/>
<link rel="apple-touch-icon" sizes="180x180" href="/assets/logo/icon-192x192.png"/>
<meta name="msapplication-TileImage" content="/assets/logo/icon-144x144.png"/>
<meta name="msapplication-TileColor" content="#10b981"/>
<!-- misc -->
<link rel="canonical" href="<%- url_for(url) %>"/>
<link rel="prefetch" href="<%- url_for(config.url) %>"/>
+80
View File
@@ -389,3 +389,83 @@
});
</script>
<% } %>
<!-- PWA Service Worker Registration -->
<script>
// Register Service Worker for PWA functionality
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js')
.then(registration => {
console.log('Service Worker registered successfully:', registration.scope);
// Check for updates
registration.addEventListener('updatefound', () => {
const newWorker = registration.installing;
if (newWorker) {
newWorker.addEventListener('statechange', () => {
if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
// New content is available, show update notification
showUpdateNotification();
}
});
}
});
})
.catch(error => {
console.log('Service Worker registration failed:', error);
});
});
}
// Show update notification
function showUpdateNotification() {
// Create a simple notification banner
const notification = document.createElement('div');
notification.innerHTML = `
<div style="
position: fixed;
top: 0;
left: 0;
right: 0;
background: #10b981;
color: white;
padding: 12px;
text-align: center;
z-index: 9999;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
">
<span>New content is available! </span>
<button onclick="window.location.reload()" style="
background: rgba(255,255,255,0.2);
border: 1px solid rgba(255,255,255,0.3);
color: white;
padding: 4px 12px;
border-radius: 4px;
margin-left: 8px;
cursor: pointer;
">Refresh</button>
<button onclick="this.parentElement.parentElement.remove()" style="
background: transparent;
border: none;
color: white;
padding: 4px 8px;
margin-left: 8px;
cursor: pointer;
font-size: 18px;
">&times;</button>
</div>
`;
document.body.appendChild(notification);
}
// Hide install button when app is installed
window.addEventListener('appinstalled', () => {
const installBtn = document.getElementById('pwa-install-btn');
if (installBtn) {
installBtn.remove();
}
console.log('PWA was installed');
});
</script>