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

testing adding service workers to have static pmtiles #2

Open
wants to merge 2 commits into
base: main
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
89 changes: 68 additions & 21 deletions app/components/map.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,25 @@ import layers, { layersWithPartialCustomTheme } from "protomaps-themes-base";

import { Theme } from "../lib/theme";

export const MapComponent = ({ customTheme }: { customTheme: Partial<Theme> }) => {
if ("serviceWorker" in navigator) {
const registration = navigator.serviceWorker.register("/sw2.js").then(
function (registration) {
console.log(
"Service Worker registration successful with scope: ",
registration.scope
);
},
function (err) {
console.log("Service Worker registration failed: ", err);
}
);
}

export const MapComponent = ({
customTheme,
}: {
customTheme: Partial<Theme>;
}) => {
useEffect(() => {
let protocol = new Protocol();
maplibregl.addProtocol("pmtiles", protocol.tile);
Expand All @@ -17,6 +35,30 @@ export const MapComponent = ({ customTheme }: { customTheme: Partial<Theme> }) =
};
}, []);

useEffect(() => {
if ("serviceWorker" in navigator) {
window.addEventListener("load", () => {
navigator.serviceWorker
.getRegistrations()
.then((registrations) => {
const sw2Registered = registrations.some((registration) =>
registration.active?.scriptURL.endsWith("/sw2.js")
);

if (!sw2Registered) {
window.location.reload();
}
})
.catch((error) => {
console.error(
"Error checking service worker registrations:",
error
);
});
});
}
}, []);

return (
<>
<Map
Expand All @@ -31,20 +73,25 @@ export const MapComponent = ({ customTheme }: { customTheme: Partial<Theme> }) =
protomaps: {
type: "vector",
// url: "pmtiles://http://localhost:8080/world.pmtiles",
// tiles: ["http://localhost:8787/world/{z}/{x}/{y}.mvt"],
tiles: [
"https://protomaps-host.tomsprojects.workers.dev/world/{z}/{x}/{y}.mvt",
],
// tiles: [
// "https://pmtiles-cloudflare.tomsprojects.workers.dev/world/{z}/{x}/{y}.mvt",
// ],
// tiles: [
// "https://protomaps-host.tomsprojects.workers.dev/world/{z}/{x}/{y}.mvt",
// ],
// url: "pmtiles://http://localhost:8787/world/{z}/{x}/{y}.mvt",
// url: "pmtiles://world.pmtiles",
url: "pmtiles://world.pmtiles",
},
protomaps2: {
type: "vector",
// url: "pmtiles://http://localhost:8080/nyc.pmtiles",
// url: "pmtiles://http://localhost:8787/nyc/{z}/{x}/{y}.mvt",
// tiles: ["http://localhost:8787/nyc/{z}/{x}/{y}.mvt"],
url: "pmtiles://nyc.pmtiles",
// tiles: [
// "https://pmtiles-cloudflare.tomsprojects.workers.dev/nyc/{z}/{x}/{y}.mvt",
// ],
},
// protomaps2: {
// type: "vector",
// // url: "pmtiles://http://localhost:8080/nyc.pmtiles",
// // url: "pmtiles://http://localhost:8787/nyc/{z}/{x}/{y}.mvt",
// // tiles: ["http://localhost:8787/nyc/{z}/{x}/{y}.mvt"],
// url: "pmtiles://test/nyc.pmtiles",
// },
},
glyphs:
"https://protomaps.github.io/basemaps-assets/fonts/{fontstack}/{range}.pbf",
Expand All @@ -56,14 +103,14 @@ export const MapComponent = ({ customTheme }: { customTheme: Partial<Theme> }) =
).filter((e) => {
return !e.id.includes("background");
}),
// ...layersWithPartialCustomTheme("protomaps2", "light", customTheme)
// .filter((e) => {
// return !e.id.includes("background");
// })
// .map((e) => {
// e.id = e.id + "2";
// return e;
// }),
...layersWithPartialCustomTheme("protomaps2", "light", customTheme)
.filter((e) => {
return !e.id.includes("background");
})
.map((e) => {
e.id = e.id + "2";
return e;
}),
],
}}
mapLib={maplibregl}
Expand Down
25 changes: 24 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@
"react": "^18",
"react-dom": "^18",
"react-map-gl": "^7.1.7",
"react-markdown": "^9.0.1"
"react-markdown": "^9.0.1",
"workbox-routing": "^7.1.0",
"workbox-strategies": "^7.1.0"
},
"devDependencies": {
"@cloudflare/next-on-pages": "^1.12.1",
Expand Down
87 changes: 87 additions & 0 deletions public/sw2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
// public/service-worker.js

// import { registerRoute } from "workbox-routing";
// import { CacheFirst } from "workbox-strategies";

const cacheAssets = [
'world.pmtiles',
'nyc.pmtiles'
]

self.addEventListener('install', (e) => {
console.log("service worker installed")

e.waitUntil(
caches
.open("pmtiles-cache")
.then((cache) => {
return cache.addAll(cacheAssets)
})
.catch((err) => {
console.log("error caching assets")
})
.then(() => {
self.skipWaiting()
})
)
})

self.addEventListener('activate', (e) => {
console.log("service worker activated")
})

self.addEventListener('fetch', (e) => {
console.log("service worker fetching 2")

if(e.request.url.endsWith(".pmtiles")) {
console.log('service worker fetching pmtiles')
async ({ request }) => {
try {
// Use CacheFirst strategy
const cacheStrategy = new CacheFirst({
cacheName: "pmtiles-cache",
plugins: [
{
// Ensure the entire response is cached
cacheWillUpdate: async ({ response }) => {
if (response && response.ok) {
return response;
}
return null;
},
},
],
});

// Attempt to serve from cache first
let response = await cacheStrategy.handle({ request });

// If not found in cache, fetch the full file from the network
if (!response) {
const headers = new Headers(request.headers);
headers.delete("range"); // Remove range request headers

const fullRequest = new Request(request.url, {
headers: headers,
method: "GET", // Ensure it's a GET request
});

console.log("fetching full request from network");

response = await fetch(fullRequest);

// Ensure the response is valid before caching
if (response.ok) {
const cache = await caches.open("pmtiles-cache");
await cache.put(request, response.clone());
}
}

return response;
} catch (error) {
console.error("Error in service worker:", error);
throw error;
}
}
}
})