Skip to content

Commit

Permalink
test sw
Browse files Browse the repository at this point in the history
  • Loading branch information
Yusef Almamari committed Aug 13, 2024
1 parent 10588a4 commit da2b27d
Show file tree
Hide file tree
Showing 6 changed files with 164 additions and 14 deletions.
2 changes: 2 additions & 0 deletions .env.development
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
VITE_PUBLIC_URL=http://localhost:3000/citeease
VITE_NODE_ENV=development
2 changes: 2 additions & 0 deletions .env.production
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
VITE_PUBLIC_URL=https://discontinuedlabs.github.io/citeease
VITE_NODE_ENV=production
18 changes: 15 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,20 @@
"react-redux": "^9.1.2",
"react-router-dom": "^6.21.1",
"react-window": "^1.8.10",
"tailwindcss": "^3.4.6"
"tailwindcss": "^3.4.6",
"web-vitals": "^2.1.4",
"workbox-background-sync": "^6.6.0",
"workbox-broadcast-update": "^6.6.0",
"workbox-cacheable-response": "^6.6.0",
"workbox-core": "^6.6.0",
"workbox-expiration": "^6.6.0",
"workbox-google-analytics": "^6.6.1",
"workbox-navigation-preload": "^6.6.0",
"workbox-precaching": "^6.6.0",
"workbox-range-requests": "^6.6.0",
"workbox-routing": "^6.6.0",
"workbox-strategies": "^6.6.0",
"workbox-streams": "^6.6.0"
},
"devDependencies": {
"@eslint/js": "^9.6.0",
Expand Down Expand Up @@ -69,8 +82,7 @@
"react-dom": "^18.3.1",
"typescript": "^5.5.3",
"vite": "^5.3.4",
"vite-plugin-eslint": "^1.8.1",
"vite-plugin-pwa": "^0.20.0"
"vite-plugin-eslint": "^1.8.1"
},
"overrides": {
"typescript": "^5.5.3"
Expand Down
44 changes: 44 additions & 0 deletions src/service-worker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/* eslint-disable no-restricted-globals, no-underscore-dangle */

import { clientsClaim } from "workbox-core";
import { ExpirationPlugin } from "workbox-expiration";
import { precacheAndRoute, createHandlerBoundToURL } from "workbox-precaching";
import { registerRoute } from "workbox-routing";
import { StaleWhileRevalidate } from "workbox-strategies";

clientsClaim();

precacheAndRoute([...self.__WB_MANIFEST]);

const fileExtensionRegexp = /[^?/]+\.[^/]+$/;

registerRoute(
({ request, url }) => {
if (request.mode !== "navigate") return false;

if (url.pathname.startsWith("/_")) return false;

if (url.pathname.match(fileExtensionRegexp)) return false;

return true;
},
createHandlerBoundToURL(`${import.meta.env.VITE_PUBLIC_URL}/index.html`)
);

registerRoute(
({ url }) => {
const path = url.pathname.split("/");
const lastSegment = path[path.length - 1];
return url.origin === self.location.origin && ["png", "jpg", "jpeg", "svg"].includes(lastSegment);
},
new StaleWhileRevalidate({
cacheName: "images",
plugins: [new ExpirationPlugin({ maxEntries: 50 })],
})
);

self.addEventListener("message", (event) => {
if (event.data && event.data.type === "SKIP_WAITING") {
self.skipWaiting();
}
});
100 changes: 100 additions & 0 deletions src/serviceWorkerRegistration.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
const isLocalhost = Boolean(
window.location.hostname === "localhost" ||
window.location.hostname === "[::1]" ||
window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)
);

function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then((registration) => {
// eslint-disable-next-line no-param-reassign
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === "installed") {
if (navigator.serviceWorker.controller) {
console.log(
"New content is available and will be used when all " +
"tabs for this page are closed. See https://cra.link/PWA."
);

if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
console.log("Content is cached for offline use.");

if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch((error) => {
console.error("Error during service worker registration:", error);
});
}

function checkValidServiceWorker(swUrl, config) {
fetch(swUrl, {
headers: { "Service-Worker": "script" },
})
.then((response) => {
const contentType = response.headers.get("content-type");
if (response.status === 404 || (contentType != null && contentType.indexOf("javascript") === -1)) {
navigator.serviceWorker.ready.then((registration) => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log("No internet connection found. App is running in offline mode.");
});
}

export function register(config) {
if (import.meta.env.VITE_NODE_ENV === "production" && "serviceWorker" in navigator) {
const publicUrl = new URL(import.meta.env.VITE_PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
return;
}

window.addEventListener("load", () => {
const swUrl = `${import.meta.env.VITE_PUBLIC_URL}/service-worker.js`;

if (isLocalhost) {
checkValidServiceWorker(swUrl, config);

navigator.serviceWorker.ready.then(() => {
console.log(
"This web app is being served cache-first by a service worker. To learn more, visit https://cra.link/PWA"
);
});
} else {
registerValidSW(swUrl, config);
}
});
}
}

export function unregister() {
if ("serviceWorker" in navigator) {
navigator.serviceWorker.ready
.then((registration) => {
registration.unregister();
})
.catch((error) => {
console.error(error.message);
});
}
}
12 changes: 1 addition & 11 deletions vite.config.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import eslint from "vite-plugin-eslint";
import { VitePWA } from "vite-plugin-pwa";

export default defineConfig(() => {
return {
Expand All @@ -16,15 +15,6 @@ export default defineConfig(() => {
assetsDir: ".",
},

plugins: [
react(),
eslint(),
VitePWA({
registerType: "autoUpdate",
devOptions: {
enabled: true,
},
}),
],
plugins: [react(), eslint()],
};
});

0 comments on commit da2b27d

Please sign in to comment.