Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

set up service worker for compa pwa #57

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion client/.env
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ DATABASE_URL="file:./dev.db"
SCHOOL=knust
COOKIE_SECRET=secret1,secret2
SECRET_KEY=secret1
RESEND_API_KEY=
RESEND_API_KEY=123
AWS_UPLOAD_ENDPOINT="eu-central-1.linodeobjects.com"
AWS_REGION="eu-central-1"
AWS_ACCESS_KEY_ID=
Expand Down
19 changes: 14 additions & 5 deletions client/app/entry.client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,28 @@ import { RemixBrowser } from "@remix-run/react";
import { startTransition, StrictMode } from "react";
import { hydrateRoot } from "react-dom/client";
import posthog from "posthog-js";
import AudioRecorder from 'audio-recorder-polyfill'
import mpegEncoder from 'audio-recorder-polyfill/mpeg-encoder'
import AudioRecorder from "audio-recorder-polyfill";
import mpegEncoder from "audio-recorder-polyfill/mpeg-encoder";

AudioRecorder.encoder = mpegEncoder
AudioRecorder.prototype.mimeType = 'audio/mpeg'
window.MediaRecorder = AudioRecorder
AudioRecorder.encoder = mpegEncoder;
AudioRecorder.prototype.mimeType = "audio/mpeg";
window.MediaRecorder = AudioRecorder;

if (process.env.NODE_ENV === "production") {
posthog.init("phc_qmxF7NTz6XUnYUDoMpkTign6mujS8F8VqR75wb0Bsl7", {
api_host: "https://eu.posthog.com",
});
}

if ("serviceWorker" in navigator) {
try {
navigator.serviceWorker.register("/service-worker.js", {
scope: "/",
});
} catch (error) {
console.error(`Registration failed with ${error}`);
}
}

startTransition(() => {
hydrateRoot(
Expand Down
90 changes: 89 additions & 1 deletion client/app/root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,11 @@ import {
Outlet,
Scripts,
ScrollRestoration,
UIMatch,
json,
useLoaderData,
useLocation,
useMatches,
} from "@remix-run/react";
import { BottomNav, Navbar } from "./components/navbar";
import { Footer } from "./components/footer";
Expand All @@ -21,6 +24,8 @@ import { prisma } from "./lib/prisma.server";
import { GlobalCtx } from "./lib/global-ctx";
import { User } from "@prisma/client";
import { CommonHead } from "./components/common-head";
import { useRef } from "react";
import React from "react";

export const loader = async ({ request }: LoaderFunctionArgs) => {
let user: User | undefined | null;
Expand All @@ -43,6 +48,89 @@ export { ErrorBoundary } from "./components/error-boundary";
export default function App() {
const { user } = useLoaderData<typeof loader>();

const location = useLocation();
const isMount = useRef(true);
const matches = useMatches();

function isPromise(p: any): boolean {
if (p && typeof p === "object" && typeof p.then === "function") {
return true;
}
return false;
}

function isFunction(p: any): boolean {
if (typeof p === "function") {
return true;
}
return false;
}

React.useEffect(() => {
const mounted = isMount;
isMount.current = false;

if ("serviceWorker" in navigator) {
if (navigator.serviceWorker.controller) {
navigator.serviceWorker.controller?.postMessage({
action: "clearCache",
});
navigator.serviceWorker.controller?.postMessage({
type: "REMIX_NAVIGATION",
isMount: mounted,
location,
manifest: window.__remixManifest,
matches: matches.filter(filteredMatches).map(sanitizeHandleObject),
});
} else {
const listener = async () => {
await navigator.serviceWorker.ready;
navigator.serviceWorker.controller?.postMessage({
action: "clearCache",
});
navigator.serviceWorker.controller?.postMessage({
type: "REMIX_NAVIGATION",
isMount: mounted,
location,
manifest: window.__remixManifest,
matches: matches.filter(filteredMatches).map(sanitizeHandleObject),
});
};
navigator.serviceWorker.addEventListener("controllerchange", listener);
return () => {
navigator.serviceWorker.removeEventListener(
"controllerchange",
listener,
);
};
}
}

function filteredMatches(route: UIMatch) {
if (route.data) {
return (
Object.values(route.data).filter((elem) => {
return isPromise(elem);
}).length === 0
);
}
return true;
}

function sanitizeHandleObject(route: UIMatch) {
let handle = route.handle;

if (handle) {
const filterInvalidTypes = ([, value]: any) =>
!isPromise(value) && !isFunction(value);
handle = Object.fromEntries(
Object.entries(route.handle!).filter(filterInvalidTypes),
);
}
return { ...route, handle };
}
}, [location, matches]);

return (
<html lang="en">
<head>
Expand All @@ -60,7 +148,7 @@ export default function App() {

<ScrollRestoration />
<Scripts />
<LiveReload />
<LiveReload timeoutMs={1000} />
<Footer />
<BottomNav />
</body>
Expand Down
61 changes: 61 additions & 0 deletions client/app/routes/offline.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import React from 'react'

export default function Offline() {
const getBrowsingHistory = async () => {
const browsingHistory: Array<unknown> = []
const parser = new DOMParser()

const cache = await caches.open(
await caches.keys().then((res) => {
return res.filter((word) => word.includes('pages'))[0]
})
)

const keys = await cache.keys()

console.log(keys)

for (const request of keys) {
const data: Record<string, unknown> = {}
data.url = request.url
browsingHistory.push(data)
}

if (browsingHistory?.length) {
const markup = document.getElementById('browsing-history')
if (!markup) return
markup.innerHTML =
'<p class="mb-1">In the meantime, you still have things you can access: </p>'
browsingHistory.forEach((data) => {
if (!data) return
markup.innerHTML += `
<ul class="list-disc pl-4">
<li>
<a class="block text-blue-600" href="${data.url}">${data.url}</a>
</li>
</ul>
`
})
document
.getElementById('browsing-history')
?.insertAdjacentElement('beforeend', markup)
}
}

React.useEffect(() => {
getBrowsingHistory()
})

return (
<div className='container mx-auto min-h-[70vh] pt-8'>
<h1 className='font-bold text-3xl mb-8'>
Oops, you are currently offline
</h1>
<h2 className='font-medium text-xl mb-4'>
Please check your internet connection and try again
</h2>

<div id='browsing-history' />
</div>
)
}
Loading