Skip to content

Commit

Permalink
make it installable as a pwa
Browse files Browse the repository at this point in the history
  • Loading branch information
brettfo committed Feb 16, 2024
1 parent f059531 commit 5e90d77
Show file tree
Hide file tree
Showing 5 changed files with 71 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { Expression } from "./expression.js";

function main() {
installServiceWorker();

const results = <HTMLTextAreaElement>document.getElementById('results')!;
const input = <HTMLInputElement>document.getElementById('input')!;
const evalButton = <HTMLButtonElement>document.getElementById('eval')!;
Expand All @@ -25,4 +27,10 @@ function main() {
});
}

function installServiceWorker() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('service-worker.js');
}
}

window.addEventListener('DOMContentLoaded', main);
4 changes: 4 additions & 0 deletions src/resources/icon.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 2 additions & 0 deletions src/resources/index.html
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
<html>

<head>
<link rel="manifest" href="manifest.json.webmanifest" />
<script type="text/javascript" src="app.js"></script>
<script type="text/javascript" src="service-worker.js"></script>
</head>

<body>
Expand Down
12 changes: 12 additions & 0 deletions src/resources/manifest.json.webmanifest
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"name": "IxMilia Calculator",
"icons": [
{
"src": "icon.svg",
"type": "image/svg+xml",
"sizes": "128x128"
}
],
"start_url": "/",
"display": "standalone"
}
45 changes: 45 additions & 0 deletions src/resources/service-worker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
const cacheName = 'ixmilia.calc.cache';
const filesToCache = [
'/',
'index.html',
'app.js',
'icon.svg',
];

self.addEventListener('install', (e) => {
e.waitUntil(() => {
caches.open(cacheName)
.then(cache => cache.addAll(filesToCache))
.then(self.skipWaiting());
});
});

self.addEventListener('activate', (e) => {
e.waitUntil(() => {
caches.keys().then(keys => {
return keys.filter(key => key !== cacheName);
}).then(cachesToDelete => {
return Promise.all(cachesToDelete.map(cacheToDelete => {
return caches.delete(cacheToDelete);
}));
}).then(() => self.clients.claim());
});
});

self.addEventListener('fetch', (e) => {
e.respondWith(() => {
const response = caches.match(e.request);
if (response) {
return response;
}

console.log(`Cache miss: ${e.request.url}`);
return fetch(e.request).then(response => {
cache.put(e.request, response.clone())
.then(() => {
console.log(`Cached: ${e.request.url}`);
return response;
});
});
});
});

0 comments on commit 5e90d77

Please sign in to comment.