-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsw.js
More file actions
331 lines (280 loc) · 9.5 KB
/
Copy pathsw.js
File metadata and controls
331 lines (280 loc) · 9.5 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
327
328
329
330
331
/**
* Funky Frame Service Worker
*
* Provides offline support and desktop notifications for the Funky Framework playground.
*
* Features:
* - Caching strategies for different asset types
* - Push notification handling
* - Client-SW messaging
* - Cache versioning and cleanup
*
* @version 1.0.4
*/
// Import FunkySW utilities
importScripts('./js/sw/strategies.js');
importScripts('./js/sw/cache-manager.js');
importScripts('./js/sw/notifications.js');
importScripts('./js/sw/messaging.js');
// =============================================================================
// CONFIGURATION
// =============================================================================
var CACHE_VERSION = '1.0.4';
var CACHE_NAME = 'funky-frame-' + CACHE_VERSION;
/**
* Static assets to precache on install
*/
var STATIC_ASSETS = [
'/playground/',
'/playground/index',
'/playground/canvas'
];
/**
* Caching strategy routes
* Maps URL path prefixes to caching strategies
*/
var ROUTES = {
// Static assets - cache first (rarely change)
'/css/': 'cacheFirst',
'/core/': 'cacheFirst',
'/components/': 'cacheFirst',
'/icons/': 'cacheFirst',
// Test files - cache first for fast reloads (330+ files)
'/js/dev/': 'cacheFirst',
// Component demos - stale while revalidate (may change, but show cached quickly)
'/playground/components/': 'staleWhileRevalidate',
// External CDN resources
'cdn.jsdelivr.net': 'cacheFirst',
'cdnjs.cloudflare.com': 'cacheFirst'
};
/**
* Default notification options
*/
var NOTIFICATION_DEFAULTS = {
icon: '/icons/icon-192.png',
badge: '/icons/badge-72.png',
vibrate: [200, 100, 200]
};
// =============================================================================
// INSTALL EVENT
// =============================================================================
self.addEventListener('install', function(event) {
console.log('[FunkyFrame SW] Installing v' + CACHE_VERSION);
event.waitUntil(
FunkySW.CacheManager.precache(CACHE_NAME, STATIC_ASSETS)
.then(function() {
console.log('[FunkyFrame SW] Static assets cached');
// Activate immediately without waiting for clients to close
return self.skipWaiting();
})
.catch(function(error) {
console.warn('[FunkyFrame SW] Precache failed:', error);
// Still skip waiting even if precache fails
return self.skipWaiting();
})
);
});
// =============================================================================
// ACTIVATE EVENT
// =============================================================================
self.addEventListener('activate', function(event) {
console.log('[FunkyFrame SW] Activating v' + CACHE_VERSION);
event.waitUntil(
// Clean up old caches
FunkySW.CacheManager.cleanup(CACHE_VERSION, 'funky-frame-')
.then(function() {
// Take control of all clients immediately
return self.clients.claim();
})
.then(function() {
// Notify clients that SW is ready
return FunkySW.Messaging.notifyReady(CACHE_VERSION);
})
);
});
// =============================================================================
// FETCH EVENT
// =============================================================================
self.addEventListener('fetch', function(event) {
var request = event.request;
// Only handle GET requests
if (request.method !== 'GET') {
return;
}
// Skip non-http(s) requests
if (!request.url.startsWith('http')) {
return;
}
// Determine strategy based on URL
var strategy = FunkySW.matchRoute(request.url, ROUTES, 'networkFirst');
event.respondWith(
FunkySW.strategies[strategy](request, { cacheName: CACHE_NAME })
.catch(function(error) {
console.warn('[FunkyFrame SW] Fetch failed:', request.url, error);
// Return offline fallback for navigation requests
if (request.mode === 'navigate') {
return caches.match('/playground/')
.then(function(cached) {
if (cached) return cached;
return new Response('Offline - Please check your connection', {
status: 503,
statusText: 'Service Unavailable',
headers: { 'Content-Type': 'text/plain' }
});
});
}
throw error;
})
);
});
// =============================================================================
// PUSH NOTIFICATIONS
// =============================================================================
self.addEventListener('push', function(event) {
// If no data, show a default notification for testing
if (!event.data) {
event.waitUntil(
self.registration.showNotification('Funky Frame Test', {
body: 'Push notification is working!',
icon: NOTIFICATION_DEFAULTS.icon,
badge: NOTIFICATION_DEFAULTS.badge,
vibrate: NOTIFICATION_DEFAULTS.vibrate,
tag: 'test-push'
})
);
return;
}
event.waitUntil(
FunkySW.Notifications.handlePush(event, NOTIFICATION_DEFAULTS)
);
});
// =============================================================================
// NOTIFICATION CLICK
// =============================================================================
self.addEventListener('notificationclick', function(event) {
console.log('[FunkyFrame SW] Notification clicked:', event.action);
event.waitUntil(
FunkySW.Notifications.handleClick(event, {
// Handle 'view' action - open the URL from notification data
'view': function(data) {
var url = data.url || '/playground/';
return self.clients.openWindow(url);
},
// Handle 'dismiss' action - just close the notification (already done)
'dismiss': function() {
return Promise.resolve();
},
// Default action when clicking notification body (not an action button)
'default': function(data) {
var url = data.url || '/playground/';
// Try to focus existing window first
return self.clients.matchAll({ type: 'window', includeUncontrolled: true })
.then(function(clientList) {
for (var i = 0; i < clientList.length; i++) {
var client = clientList[i];
if ('focus' in client) {
return client.focus();
}
}
// No existing window, open new one
return self.clients.openWindow(url);
});
}
})
);
});
// =============================================================================
// NOTIFICATION CLOSE
// =============================================================================
self.addEventListener('notificationclose', function(event) {
FunkySW.Notifications.handleClose(event, function(data) {
console.log('[FunkyFrame SW] Notification dismissed:', data.tag || 'untagged');
});
});
// =============================================================================
// MESSAGE HANDLING
// =============================================================================
self.addEventListener('message', function(event) {
// Use standard handlers plus custom ones for funky-frame
var handlers = FunkySW.Messaging.createHandlers({
// Playground: Show notification with optional delay (matches public/sw.js)
'SHOW_NOTIFICATION': function(data) {
var title = data.title || 'Funky Notification';
var body = data.body || 'Hello from the Playground!';
var icon = data.icon || NOTIFICATION_DEFAULTS.icon;
var delayMs = (data.delay || 0) * 1000;
var showNotif = function() {
return self.registration.showNotification(title, {
body: body,
icon: icon,
badge: NOTIFICATION_DEFAULTS.badge,
vibrate: NOTIFICATION_DEFAULTS.vibrate,
tag: 'playground-demo-' + Date.now(),
renotify: true,
data: { url: '/playground/' }
});
};
if (delayMs > 0) {
setTimeout(showNotif, delayMs);
console.log('[FunkyFrame SW] Notification scheduled in', data.delay, 'seconds');
return Promise.resolve();
}
return showNotif();
},
// Custom: Show desktop notification from client
'FUNKY_SHOW_NOTIFICATION': function(data, event) {
if (!data || !data.title) {
console.warn('[FunkyFrame SW] SHOW_NOTIFICATION: No title provided');
return Promise.resolve();
}
var options = Object.assign({}, NOTIFICATION_DEFAULTS, data.options || {});
return FunkySW.Notifications.show(data.title, options)
.then(function() {
// Notify the client that notification was shown
if (event.source) {
FunkySW.Messaging.send(event.source, 'FUNKY_NOTIFICATION_SHOWN', {
title: data.title,
tag: options.tag
});
}
});
},
// Custom: Get SW version
'FUNKY_GET_VERSION': function(data, event) {
if (event.source) {
FunkySW.Messaging.send(event.source, 'FUNKY_VERSION', {
version: CACHE_VERSION
});
}
}
});
FunkySW.Messaging.handleMessage(event, handlers);
});
// =============================================================================
// BACKGROUND SYNC (if supported)
// =============================================================================
self.addEventListener('sync', function(event) {
console.log('[FunkyFrame SW] Background sync:', event.tag);
// Handle sync events if needed
if (event.tag === 'playground-sync') {
event.waitUntil(
// Placeholder for background sync logic
Promise.resolve()
);
}
});
// =============================================================================
// PERIODIC SYNC (if supported)
// =============================================================================
self.addEventListener('periodicsync', function(event) {
console.log('[FunkyFrame SW] Periodic sync:', event.tag);
if (event.tag === 'content-update') {
event.waitUntil(
// Refresh cached content periodically
caches.open(CACHE_NAME).then(function(cache) {
return cache.addAll(STATIC_ASSETS);
})
);
}
});
console.log('[FunkyFrame SW] Service Worker loaded v' + CACHE_VERSION);