@serwist/turbopack
Version:
A module that integrates Serwist into your Next.js / Turbopack application.
50 lines (46 loc) • 1.5 kB
JavaScript
import { jsx } from 'react/jsx-runtime';
import { Serwist } from '@serwist/window';
import { isCurrentPageOutOfScope } from '@serwist/window/internal';
import { createContext, useState, useEffect } from 'react';
const SerwistContext = createContext(null);
function SerwistProvider({ swUrl, register = true, reloadOnOnline = true, options, children }) {
const [serwist] = useState(()=>{
if (typeof window === "undefined") return null;
if (!(window.serwist && window.serwist instanceof Serwist) && "serviceWorker" in navigator) {
window.serwist = new Serwist(swUrl, {
...options,
type: options?.type || "module",
scope: options?.scope || "/"
});
}
return window.serwist ?? null;
});
useEffect(()=>{
const scope = options?.scope || "/";
if (register && !isCurrentPageOutOfScope(scope)) {
void serwist?.register();
}
}, [
register,
options?.scope,
serwist?.register
]);
useEffect(()=>{
const reload = ()=>location.reload();
if (reloadOnOnline) {
window.addEventListener("online", reload);
}
return ()=>{
window.removeEventListener("online", reload);
};
}, [
reloadOnOnline
]);
return jsx(SerwistContext.Provider, {
value: {
serwist
},
children: children
});
}
export { SerwistProvider };