Skip to content

Commit

Permalink
Refactor PWA functionality and file structure (#7)
Browse files Browse the repository at this point in the history
This pull request refactors the PWA functionality by moving the Service Worker loading script to a separate file called register-sw.js. It also fixes the PWA scope registration to be more universal. Additionally, it adds new PWA functionality for periodicSync.
  • Loading branch information
mistermatt1337 authored Apr 26, 2024
1 parent 82ace57 commit 4d7ca5a
Show file tree
Hide file tree
Showing 5 changed files with 83 additions and 52 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# RSI-Waves2Epochs
![Static Badge](https://img.shields.io/badge/RSI_Waves2Epochs-SC_Open_dev-gold?style=for-the-badge&logo=github&link=https%3A%2F%2Fsc-open.github.io%2FRSI-Waves2Epochs%2F)
![Static Badge](https://img.shields.io/badge/RSI_Waves2Epochs-SC_Open_dev-gold?logo=github&link=https%3A%2F%2Fsc-open.github.io%2FRSI-Waves2Epochs%2F)

Convert RSI Waves from UTC datetime to Discord Epochs

This is a simple javascript function that runs in the browser and accepts pasted text input, matches to a regular expression, and outputs the results in converted epoch timestamps compatible with Discord.
This is a simple JavaScript function that runs in the browser and accepts pasted text input, matches to a regular expression, and outputs the results in converted epoch timestamps compatible with Discord.

[Click Here to Begin](https://sc-open.github.io/RSI-Waves2Epochs/)
25 changes: 3 additions & 22 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@
<object class="w3-center w3-margin w3-hover-shadow" title="GitHub Repo Badge" data="https://img.shields.io/badge/waves2epochs-by_sc--open-gold?style=for-the-badge&logo=github&link=https%3A%2F%2Fgithub.com%2FSC-Open%2FRSI-Waves2Epochs" type="image/svg+xml"></object>
<p class="w3-margin" id="label">Paste your copied wave schedule here:</p>
<div class="w3-col " id="inputArea">
<textarea class="w3-grey" rows="4" cols="30" id="inputData" name="input" placeholder="Wave # HHMM UTC - Month DD&#10;Wave # HHMM UTC - Month DD&#10;Wave # HHMM UTC - Month DD"></textarea>
<textarea class="w3-auto" rows="4" cols="30" id="inputData" name="input" placeholder="Wave # HHMM UTC - Month DD&#10;Wave # HHMM UTC - Month DD&#10;Wave # HHMM UTC - Month DD"></textarea>
</div>
<div class="w3-col" id="outputArea">
<pre class="w3-grey" id="outputData"></pre>
<pre class="w3-auto" id="outputData"></pre>
</div>
<button class="w3-btn w3-blue-grey" type="button" id="actionButton">Convert</button>
</div>
Expand All @@ -51,25 +51,6 @@ <h2 class="w3-margin-top">Like what we're doing?</h2>
<button class="w3-btn w3-blue-grey w3-margin-bottom" id="aboutButton" type="button">About</button>
</footer>
<script src="js/content.js"></script>
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
const scope = location.hostname === 'sc-open.github.io' ? '/RSI-Waves2Epochs/' : '/';
navigator.serviceWorker.register(scope + 'sw.js', {scope: scope}).then(function(registration) {
console.log('ServiceWorker registration successful with scope: ', registration.scope);

// Register background sync
registration.sync.register('fetch-new-content').then(() => {
console.log('Background Sync registered');
}, function(err) {
console.log('Background Sync registration failed: ', err);
});

}, function(err) {
console.log('ServiceWorker registration failed: ', err);
});
});
}
</script>
<script src="register-sw.js"></script>
</body>
</html>
16 changes: 8 additions & 8 deletions manifest.webmanifest
Original file line number Diff line number Diff line change
Expand Up @@ -4,39 +4,39 @@
"name": "Waves2Epochs by SC-Open.dev",
"short_name": "Waves2Epochs",
"description": "An SC-Open.dev project Waves2Epochs is a simple JavaScript tool to convert RSI Waves Schedules into Discord compatible epochs.",
"start_url": "/RSI-Waves2Epochs/",
"start_url": "/RSI-Waves2Epochs/index.html",
"background_color": "#000000",
"theme_color": "#2f3d58",
"orientation": "any",
"display": "standalone",
"scope": "/RSI-Waves2Epochs/",
"icons": [
{
"src": "/RSI-Waves2Epochs/img/16.png",
"src": "img/16.png",
"sizes": "16x16"
},
{
"src": "/RSI-Waves2Epochs/img/32.png",
"src": "img/32.png",
"sizes": "32x32"
},
{
"src": "/RSI-Waves2Epochs/img/48.png",
"src": "img/48.png",
"sizes": "48x48"
},
{
"src": "/RSI-Waves2Epochs/img/64.png",
"src": "img/64.png",
"sizes": "64x64"
},
{
"src": "/RSI-Waves2Epochs/img/128.png",
"src": "img/128.png",
"sizes": "128x128"
},
{
"src": "/RSI-Waves2Epochs/img/256.png",
"src": "img/256.png",
"sizes": "256x256"
},
{
"src": "/RSI-Waves2Epochs/img/512.png",
"src": "img/512.png",
"sizes": "512x512"
}
]
Expand Down
27 changes: 27 additions & 0 deletions register-sw.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// register-sw.js
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
const scope = window.location.pathname;
navigator.serviceWorker.register(scope + 'sw.js', {scope: scope}).then(function(registration) {
console.log('ServiceWorker registration successful with scope: ', registration.scope);
// Register backgroundSync
registration.sync.register('fetch-new-content').then(() => {
console.log('Background Sync registered');
}, function(err) {
console.log('Background Sync registration failed: ', err);
});
// Check support for periodicSync and register
if ('periodicSync' in registration) {
registration.periodicSync.register('fetch-new-content', {
minInterval: 24 * 60 * 60 * 1000, // 1 day
}).then(() => {
console.log('Periodic Sync registered');
}, function(err) {
console.log('Periodic Sync registration failed: ', err);
});
}
}, function(err) {
console.log('ServiceWorker registration failed: ', err);
});
});
}
63 changes: 43 additions & 20 deletions sw.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,20 @@
const CACHE_NAME = `rsi-waves2epochs`;
// PWA Service Worker
const CACHE_NAME = `${self.location.pathname}`;

// Use the install event to pre-cache all initial resources.
// PWA Install Functionality
self.addEventListener('install', event => {
event.waitUntil((async () => {
try {
// Fetch the manifest file
const response = await fetch('./manifest.webmanifest');
const manifest = await response.json();
const manifestResponse = await fetch('./manifest.webmanifest');
const manifest = await manifestResponse.json();

// Extract the resources you want to cache from the manifest
const resources = [manifest.start_url, ...manifest.icons.map(icon => icon.src)];

const cache = await caches.open(CACHE_NAME);
await cache.addAll([
'./index.html',
await cache.addAll([...resources,
'./js/content.js',
'./css/styles.css',
'./css/footer.css',
'./img/16.png',
'./img/32.png',
'./img/48.png',
'./img/64.png',
'./img/128.png',
'./img/192.png',
'./img/256.png',
'./img/512.png',
'https://img.shields.io/badge/SC--Open-gold?style=for-the-badge&link=https%3A%2F%2Fgithub.com%2FSC-Open',
'https://img.shields.io/badge/RSI--Waves2Epochs-blue?style=for-the-badge&logo=github&link=https%3A%2F%2Fgithub.com%2FSC-Open%2FRSI-Waves2Epochs',
'https://img.shields.io/github/license/sc-open/RSI-Waves2Epochs?style=for-the-badge',
Expand All @@ -37,6 +30,9 @@ self.addEventListener('install', event => {
});

async function evaluateAndCache(request, event) {
// Fetch and parse the manifest.json file
const manifestResponse = await fetch('./manifest.webmanifest');
const manifest = await manifestResponse.json();
// Use event if provided, otherwise use the global event
event = event || self;
// Try to get the response from the network
Expand Down Expand Up @@ -78,6 +74,12 @@ async function evaluateAndCache(request, event) {
case 'png':
contentType = 'image/png';
break;
case 'json':
contentType = 'application/json';
break;
case 'webmanifest':
contentType = 'application/manifest+json';
break;
// Add more cases as needed
}
// This code seeks to solve some content header issues
Expand All @@ -90,6 +92,7 @@ async function evaluateAndCache(request, event) {
return newResponse;
}

// PWA Offline Functionality
self.addEventListener('fetch', event => {
event.respondWith((async () => {
try {
Expand All @@ -113,10 +116,10 @@ self.addEventListener('fetch', event => {
})());
});

// Background Sync Functionality
// Use with Sync Functionality
async function fetchNewContent(event) {
// Fetch and parse the manifest.json file
const manifestResponse = await fetch('./manifest.json');
const manifestResponse = await fetch('./manifest.webmanifest');
const manifest = await manifestResponse.json();

// Extract the resources you want to fetch from the manifest
Expand All @@ -127,16 +130,36 @@ async function fetchNewContent(event) {
// Fetch all resources in parallel
await Promise.all(resources.map(async resource => {
try {
const request = new Request(resource);
const request = new Request(self.location.pathname + resource);
await evaluateAndCache(request, event);
} catch (e) {
console.error(`Failed to fetch ${resource}: ${e}`);
}
}));
}

// PWA Background Sync Functionality
self.addEventListener('sync', (event) => {
if (event.tag === 'fetch-new-content') {
event.waitUntil(fetchNewContent(event));
}
});
// PWA Periodic Sync Functionality
self.addEventListener('periodicsync', (event) => {
if (event.tag === 'fetch-new-content') {
event.waitUntil(fetchNewContent(event));
}
});
// Cleanup old caches
self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
if (CACHE_NAME !== cacheName) {
return caches.delete(cacheName);
}
})
);
}).then(() => self.clients.claim()) // Claim the clients to make sure the active service worker is used
);
});

0 comments on commit 4d7ca5a

Please sign in to comment.