import { Workbox } from "workbox-window" ; import { animate } from "@okikio/animate" ; export const ENABLE_SW = true ; export default ( ) => { ( async ( ) => { if ( "serviceWorker" in navigator && ENABLE_SW ) { let reloadDialog = document . querySelector ( ".info-prompt.reload" ) as HTMLElement ; let offlineDialog = document . querySelector ( ".info-prompt.offline-ready" ) as HTMLElement ; const dialog = ( type = "confirm" ) => { let dialogEl = type == "confirm" ? reloadDialog : offlineDialog ; return new Promise < void > ( ( resolve , reject ) => { let dismissBtn = dialogEl ?. querySelector ( ".dismiss" ) as HTMLElement ; let acceptBtn = dialogEl ?. querySelector ( ".accept" ) as HTMLElement ; let animateIn = { target : dialogEl , translateY : [ 200 , 0 ] , visibility : [ "visible" , "visible" ] , fillMode : "both" , easing : "ease" , duration : 350 } ; let animateOut = { ... animateIn , translateY : [ 0 , 200 ] , visibility : [ "visible" , "hidden" ] , delay : 3000 , } ; animate ( animateIn ) . then ( ( ) => type != "confirm" ? animate ( animateOut ) : null ) ; if ( dismissBtn ) { dismissBtn . onclick = ( ) => { animate ( { ... animateOut , delay : 0 , } ) ; reject ( ) ; } ; } if ( acceptBtn ) { acceptBtn . onclick = ( ) => { animate ( { ... animateOut , delay : 0 , } ) ; resolve ( ) ; } ; } } ) ; } ; window . addEventListener ( "load" , ( ) => { const wb = new Workbox ( "/sw.js" ) ; wb . addEventListener ( "waiting" , ( event ) => { dialog ( "confirm" ) . then ( ( ) => { wb . messageSkipWaiting ( ) ; } ) . catch ( ( ) => { } ) ; } ) ; wb . addEventListener ( "controlling" , ( event ) => { window . location . reload ( ) ; } ) ; wb . addEventListener ( "activated" , ( event ) => { if ( ! event . isUpdate ) { console . log ( "Service worker activated for the first time!" ) ; dialog ( "alert" ) . catch ( ( ) => { } ) ; } } ) ; wb . register ( ) ; } ) ; } } ) ( ) ; } ;