From 5b8c43b9024961d567f358b05f3adb5a18ced799 Mon Sep 17 00:00:00 2001 From: Thomas Makin Date: Fri, 22 Nov 2024 10:12:48 -0500 Subject: [PATCH] meta: add basic serviceworker --- components/navbar.tsx | 13 +++++++++ components/primitives.ts | 3 -- public/sw.js | 63 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 76 insertions(+), 3 deletions(-) create mode 100644 public/sw.js diff --git a/components/navbar.tsx b/components/navbar.tsx index 8728d9e..243efd5 100644 --- a/components/navbar.tsx +++ b/components/navbar.tsx @@ -38,6 +38,19 @@ export const Navbar = (props: any) => { const { data: session, status } = useSession(); + useEffect(() => { + if ("serviceWorker" in navigator) { + registerServiceWorker(); + } + }, []); + + async function registerServiceWorker() { + await navigator.serviceWorker.register("/sw.js", { + scope: "/", + updateViaCache: "all", + }); + } + useEffect(() => { setIsMenuOpen(false); // Close the navigation panel }, [pathname]); diff --git a/components/primitives.ts b/components/primitives.ts index 6607a15..564e9b1 100644 --- a/components/primitives.ts +++ b/components/primitives.ts @@ -81,8 +81,5 @@ export function generateColorFromName(name: string) { hash += name.charCodeAt(i) * i; } - console.log("generated:"); - console.log(courseColors[hash % courseColors.length]); - return courseColors[hash % courseColors.length]; } diff --git a/public/sw.js b/public/sw.js new file mode 100644 index 0000000..76fe9c8 --- /dev/null +++ b/public/sw.js @@ -0,0 +1,63 @@ +/** + * SCCS Course Planner PWA service worker + * Adapted from PWABuilder "Offline copy of pages" template + * + * Functions: + * - offline page cache + * - push notif server + * - more to come! + */ + +const CACHE = "sccs-planner"; + +importScripts( + "https://storage.googleapis.com/workbox-cdn/releases/5.1.2/workbox-sw.js" +); + +/* Cache */ +self.addEventListener("message", (event) => { + if (event.data && event.data.type === "SKIP_WAITING") { + self.skipWaiting(); + } +}); + +workbox.routing.registerRoute( + new RegExp("/*"), + new workbox.strategies.StaleWhileRevalidate({ + cacheName: CACHE, + }) +); + +/* Push Notifs */ +self.addEventListener("push", function (event) { + if (event.data) { + let body; + try { + const data = event.data.json(); + body = data.body; + icon = data.icon || "/icon.png"; + } catch (e) { + console.log("clearly not a JSON notif"); + body = event.data; + icon = "/icon.png"; + } + + const options = { + body: body, + icon: icon, + badge: "/icon.png", + vibrate: [100, 50, 100], + data: { + dateOfArrival: Date.now(), + primaryKey: "2", + }, + }; + event.waitUntil(self.registration.showNotification(data.title, options)); + } +}); + +self.addEventListener("notificationclick", function (event) { + console.log("Notification click received."); + event.notification.close(); + event.waitUntil(clients.openWindow("")); +});