Skip to content
This repository has been archived by the owner on Dec 12, 2024. It is now read-only.

🔨[refactor] [Configure Vanilla.js app to be a PWA.] #383

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
8 changes: 6 additions & 2 deletions javascript/dwa-starter-vanillajs-vite/index.html
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<!-- index.html -->

<!doctype html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
Expand All @@ -11,7 +11,10 @@
name="description"
content="A Decentralized Web Application template"
/>
<link rel="stylesheet" href="dist/output.css" />
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this line is missing only

<link rel="icon" href="/favicon.ico" sizes="48x48" />
<link rel="icon" href="/favicon.svg" sizes="any" type="image/svg+xml" />
<link rel="apple-touch-icon" href="/apple-touch-icon-180x180.png" />
<link rel="manifest" href="/manifest.json" />
</head>
<body>
<nav>
Expand All @@ -21,6 +24,7 @@
<li><a href="/settings" data-link>Settings</a></li>
</ul>
</nav>
<button id="install-button" style="display: none">Install App</button>
<div id="app"></div>
<script type="module" src="/main.js"></script>
</body>
Expand Down
90 changes: 74 additions & 16 deletions javascript/dwa-starter-vanillajs-vite/main.js
Original file line number Diff line number Diff line change
@@ -1,37 +1,95 @@
// main.js

import { Home, About, Settings, NotFound } from './components.js';
import { Home, About, Settings, NotFound } from "./components.js";

// Define routes and their corresponding components
const routes = {
'/': Home,
'/about': About,
'/settings': Settings,
"/": Home,
"/about": About,
"/settings": Settings,
};

// Function to handle navigation
function navigateTo(url) {
history.pushState(null, null, url);
router();
history.pushState(null, null, url);
router();
}

// Router function to render components based on the current URL
function router() {
const path = window.location.pathname;
const route = routes[path] || NotFound;
route();
const path = window.location.pathname;
const route = routes[path] || NotFound;
route();
}

// Event delegation for link clicks
document.addEventListener('click', (e) => {
if (e.target.matches('[data-link]')) {
e.preventDefault();
navigateTo(e.target.href);
}
document.addEventListener("click", (e) => {
if (e.target.matches("[data-link]")) {
e.preventDefault();
navigateTo(e.target.href);
}
});

// Listen to popstate event (back/forward navigation)
window.addEventListener('popstate', router);
window.addEventListener("popstate", router);

// Initial call to router to render the correct component on page load
document.addEventListener('DOMContentLoaded', router);
Copy link
Contributor Author

@Ankitv003 Ankitv003 Oct 29, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

registered service worker

document.addEventListener("DOMContentLoaded", router);

if ("serviceWorker" in navigator) {
window.addEventListener("load", () => {
navigator.serviceWorker
.register("sw.js")
.then((reg) => {
console.log("Service Worker: Registered");

// Check if a new SW is waiting to activate
reg.onupdatefound = () => {
const newWorker = reg.installing;
newWorker.onstatechange = () => {
if (
newWorker.state === "installed" &&
navigator.serviceWorker.controller
) {
// Notify user about new version availability
if (
confirm(
"A new version of the app is available. Would you like to update?"
)
) {
newWorker.postMessage({ action: "skipWaiting" });
}
}
};
};
})
.catch((err) => console.log(`Service Worker Error: ${err}`));

// Listen for `controllerchange` to reload the page when the new SW takes control
navigator.serviceWorker.addEventListener("controllerchange", () => {
window.location.reload();
});
});
}

let deferredPrompt;

window.addEventListener("beforeinstallprompt", (e) => {
e.preventDefault();
deferredPrompt = e;

// Show custom install button or UI (ensure an element with id="install-button" exists in your HTML)
const addToHomeScreen = document.querySelector("#install-button");
addToHomeScreen.style.display = "block";

addToHomeScreen.addEventListener("click", () => {
// Show the install prompt
deferredPrompt.prompt();
deferredPrompt.userChoice.then((choiceResult) => {
if (choiceResult.outcome === "accepted") {
console.log("User accepted the install prompt");
}
deferredPrompt = null;
});
});
});
25 changes: 25 additions & 0 deletions javascript/dwa-starter-vanillajs-vite/manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"name": "dwa-starter-vanillajs-vite",
"display": "standalone",
"scope": "/",
"start_url": "/index.html",
"theme_color": "#ffffff",
"background_color": "#ffffff",
"icons": [
{
"purpose": "maskable",
"sizes": "512x512",
"src": "./public/maskable-icon-512x512.png",
"type": "image/png"
},
{
"purpose": "any",
"sizes": "512x512",
"src": "./public/pwa-512x512.png",
"type": "image/png"
}
],
"orientation": "any",
"dir": "auto",
"lang": "en-US"
}
Loading