-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsw.js
More file actions
326 lines (278 loc) · 9.06 KB
/
sw.js
File metadata and controls
326 lines (278 loc) · 9.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
// Service Worker for ProjectControl App
// Handles caching, offline functionality, and performance optimization
const CACHE_NAME = 'projectcontrol-v1';
const STATIC_CACHE = 'projectcontrol-static-v1';
const DYNAMIC_CACHE = 'projectcontrol-dynamic-v1';
// Files to cache immediately
const STATIC_FILES = [
'/css/common/critical.css',
'/css/common/base.css',
'/css/common/colors.css',
'/css/common/typography.css',
'/js/common/index.js',
'/js/common/utils.js',
'/js/common/layout.js',
'/js/common/components.js',
'/js/common/theme.js',
'/js/common/validation.js',
'/js/common/messaging.js',
'/js/common/performance.js',
'/js/common/cache.js',
'/img/placeholder.png',
'/img/logo.png',
'/img/icons/',
'/templates/common/layout.php',
'/templates/common/header.php',
'/templates/common/footer.php',
'/templates/common/navigation.php'
];
// API endpoints to cache
const API_CACHE_PATTERNS = [
'/api/projects',
'/api/customers',
'/api/time-entries',
'/api/dashboard',
'/api/settings'
];
// Install event - cache static files
self.addEventListener('install', event => {
console.log('Service Worker installing...');
event.waitUntil(
caches.open(STATIC_CACHE)
.then(cache => {
console.log('Caching static files');
return cache.addAll(STATIC_FILES);
})
.then(() => {
console.log('Static files cached successfully');
return self.skipWaiting();
})
.catch(error => {
console.error('Failed to cache static files:', error);
})
);
});
// Activate event - clean up old caches
self.addEventListener('activate', event => {
console.log('Service Worker activating...');
event.waitUntil(
caches.keys()
.then(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
if (cacheName !== STATIC_CACHE &&
cacheName !== DYNAMIC_CACHE &&
cacheName.startsWith('projectcontrol-')) {
console.log('Deleting old cache:', cacheName);
return caches.delete(cacheName);
}
})
);
})
.then(() => {
console.log('Service Worker activated');
return self.clients.claim();
})
);
});
// Fetch event - handle requests
self.addEventListener('fetch', event => {
const { request } = event;
const url = new URL(request.url);
// Skip non-GET requests
if (request.method !== 'GET') {
return;
}
// Handle different types of requests
if (isStaticFile(url.pathname)) {
event.respondWith(cacheFirst(request, STATIC_CACHE));
} else if (isAPIRequest(url.pathname)) {
event.respondWith(networkFirst(request, DYNAMIC_CACHE));
} else if (isHTMLRequest(request)) {
event.respondWith(networkFirst(request, DYNAMIC_CACHE));
} else {
event.respondWith(networkOnly(request));
}
});
// Check if request is for a static file
function isStaticFile(pathname) {
return pathname.match(/\.(css|js|png|jpg|jpeg|gif|svg|woff|woff2|eot|ttf|otf|ico)$/);
}
// Check if request is for an API endpoint
function isAPIRequest(pathname) {
return API_CACHE_PATTERNS.some(pattern => pathname.startsWith(pattern));
}
// Check if request is for HTML content
function isHTMLRequest(request) {
return request.headers.get('accept').includes('text/html');
}
// Cache-first strategy for static files
async function cacheFirst(request, cacheName) {
try {
const cachedResponse = await caches.match(request);
if (cachedResponse) {
return cachedResponse;
}
const networkResponse = await fetch(request);
if (networkResponse.ok) {
const cache = await caches.open(cacheName);
cache.put(request, networkResponse.clone());
}
return networkResponse;
} catch (error) {
console.error('Cache-first strategy failed:', error);
// Return offline page for HTML requests
if (isHTMLRequest(request)) {
return caches.match('/offline.html');
}
throw error;
}
}
// Network-first strategy for dynamic content
async function networkFirst(request, cacheName) {
try {
const networkResponse = await fetch(request);
if (networkResponse.ok) {
const cache = await caches.open(cacheName);
cache.put(request, networkResponse.clone());
}
return networkResponse;
} catch (error) {
console.error('Network-first strategy failed:', error);
const cachedResponse = await caches.match(request);
if (cachedResponse) {
return cachedResponse;
}
// Return offline page for HTML requests
if (isHTMLRequest(request)) {
return caches.match('/offline.html');
}
throw error;
}
}
// Network-only strategy
async function networkOnly(request) {
try {
return await fetch(request);
} catch (error) {
console.error('Network-only strategy failed:', error);
// Return offline page for HTML requests
if (isHTMLRequest(request)) {
return caches.match('/offline.html');
}
throw error;
}
}
// Background sync for offline actions
self.addEventListener('sync', event => {
console.log('Background sync triggered:', event.tag);
if (event.tag === 'background-sync') {
event.waitUntil(performBackgroundSync());
}
});
// Perform background sync
async function performBackgroundSync() {
try {
// Get pending offline actions from IndexedDB
const pendingActions = await getPendingActions();
for (const action of pendingActions) {
try {
await performAction(action);
await removePendingAction(action.id);
} catch (error) {
console.error('Failed to perform background action:', error);
}
}
} catch (error) {
console.error('Background sync failed:', error);
}
}
// Get pending actions from IndexedDB
async function getPendingActions() {
// This would typically use IndexedDB to store pending actions
// For now, return empty array
return [];
}
// Perform a pending action
async function performAction(action) {
const response = await fetch(action.url, {
method: action.method,
headers: action.headers,
body: action.body
});
if (!response.ok) {
throw new Error(`Action failed: ${response.status}`);
}
return response;
}
// Remove pending action from IndexedDB
async function removePendingAction(actionId) {
// This would typically remove the action from IndexedDB
console.log('Removing pending action:', actionId);
}
// Push notification handling
self.addEventListener('push', event => {
console.log('Push notification received');
const options = {
body: event.data ? event.data.text() : 'New notification',
icon: '/img/notification-icon.png',
badge: '/img/badge-icon.png',
vibrate: [100, 50, 100],
data: {
dateOfArrival: Date.now(),
primaryKey: 1
},
actions: [
{
action: 'explore',
title: 'View',
icon: '/img/checkmark.png'
},
{
action: 'close',
title: 'Close',
icon: '/img/xmark.png'
}
]
};
event.waitUntil(
self.registration.showNotification('ProjectControl', options)
);
});
// Notification click handling
self.addEventListener('notificationclick', event => {
console.log('Notification clicked:', event.action);
event.notification.close();
if (event.action === 'explore') {
event.waitUntil(
clients.openWindow('/')
);
}
});
// Message handling from main thread
self.addEventListener('message', event => {
console.log('Service Worker received message:', event.data);
if (event.data && event.data.type === 'SKIP_WAITING') {
self.skipWaiting();
}
if (event.data && event.data.type === 'CACHE_URLS') {
event.waitUntil(
caches.open(DYNAMIC_CACHE)
.then(cache => {
return cache.addAll(event.data.urls);
})
);
}
if (event.data && event.data.type === 'DELETE_CACHE') {
event.waitUntil(
caches.delete(event.data.cacheName)
);
}
});
// Error handling
self.addEventListener('error', event => {
console.error('Service Worker error:', event.error);
});
self.addEventListener('unhandledrejection', event => {
console.error('Service Worker unhandled rejection:', event.reason);
});