Skip to content

Commit

Permalink
meta: add basic serviceworker
Browse files Browse the repository at this point in the history
  • Loading branch information
makinbacon21 committed Nov 22, 2024
1 parent 0573cdb commit 5b8c43b
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 3 deletions.
13 changes: 13 additions & 0 deletions components/navbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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]);
Expand Down
3 changes: 0 additions & 3 deletions components/primitives.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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];
}
63 changes: 63 additions & 0 deletions public/sw.js
Original file line number Diff line number Diff line change
@@ -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("<https://your-website.com>"));
});

0 comments on commit 5b8c43b

Please sign in to comment.