From 40432a97178d47e9660a67511419cf440841994d Mon Sep 17 00:00:00 2001
From: Kacper Donat <kadet1090@gmail.com>
Date: Mon, 13 Jan 2020 15:40:31 +0100
Subject: [PATCH] Add prompt to reload page if new version came out

---
 package.json        |  4 +++-
 resources/ts/app.ts | 15 +++++++++++++--
 yarn.lock           |  5 +++++
 3 files changed, 21 insertions(+), 3 deletions(-)

diff --git a/package.json b/package.json
index 0f90b17..e2dc540 100644
--- a/package.json
+++ b/package.json
@@ -34,6 +34,7 @@
     "xpath": "^0.0.27"
   },
   "dependencies": {
+    "@types/workbox-window": "^4.3.3",
     "babel-minify-webpack-plugin": "^0.3.1",
     "clean-webpack-plugin": "^3.0.0",
     "copy-webpack-plugin": "^4.5.2",
@@ -42,6 +43,7 @@
     "vue2-leaflet": "^1.0.2",
     "vuex": "^3.0.1",
     "vuex-class": "^0.3.1",
-    "workbox-webpack-plugin": "^4.3.1"
+    "workbox-webpack-plugin": "^4.3.1",
+    "workbox-window": "^4.3.1"
   }
 }
diff --git a/resources/ts/app.ts b/resources/ts/app.ts
index 17e9d33..972ca93 100644
--- a/resources/ts/app.ts
+++ b/resources/ts/app.ts
@@ -13,6 +13,7 @@ window['Popper'] = Popper;
 // dependencies
 import Vue from "vue";
 import Vuex, { mapActions, mapMutations, mapState, Store } from 'vuex';
+import { Workbox } from "workbox-window";
 
 Vue.use(Vuex);
 
@@ -38,8 +39,18 @@ Vue.use(Vuex);
     store.dispatch('load', window['czydojade'].state);
 
     if ('serviceWorker' in navigator) {
-        window.addEventListener('load', function() {
-            navigator.serviceWorker.register('/service-worker.js');
+        const wb = new Workbox("/service-worker.js");
+
+        wb.addEventListener('waiting', event => {
+            if (window.confirm("Dostępna jest nowa wersja, przeładować?")) {
+                wb.addEventListener('controlling', event => {
+                    window.location.reload();
+                });
+
+                wb.messageSW({type: 'SKIP_WAITING'});
+            }
         });
+
+        wb.register();
     }
 })();
diff --git a/yarn.lock b/yarn.lock
index 9d7bb6c..c9daa65 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -268,6 +268,11 @@
     "@types/webpack-sources" "*"
     source-map "^0.6.0"
 
+"@types/workbox-window@^4.3.3":
+  version "4.3.3"
+  resolved "https://registry.yarnpkg.com/@types/workbox-window/-/workbox-window-4.3.3.tgz#47f91df7ce7eea5c151a6beb3e8398c7db8ee538"
+  integrity sha512-iIq2obSq3gvzhwFxg+/02v4VqfHjRg9hpEjoM68TKYcmCAe9QGlFsJ5qPZkJKUuZDVW7cUoR3iiA2jIALFU6Ag==
+
 "@webassemblyjs/ast@1.8.5":
   version "1.8.5"
   resolved "https://registry.yarnpkg.com/@webassemblyjs/ast/-/ast-1.8.5.tgz#51b1c5fe6576a34953bf4b253df9f0d490d9e359"