diff --git a/app/javascript/application.js b/app/javascript/application.js index 8404008..c022df5 100644 --- a/app/javascript/application.js +++ b/app/javascript/application.js @@ -19,3 +19,8 @@ styleCharts() // Charts can be created before this module runs, so restyle after each page load too. document.addEventListener("turbo:load", restyleCharts) window.addEventListener("theme:change", restyleCharts) + +// Installable app (PWA): the service worker adds an offline page and caches static assets. +if ("serviceWorker" in navigator) { + window.addEventListener("load", () => navigator.serviceWorker.register("/service-worker.js", { scope: "/" }).catch(() => {})) +} diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb index 176e0d2..830cb6a 100644 --- a/app/views/layouts/application.html.erb +++ b/app/views/layouts/application.html.erb @@ -9,9 +9,13 @@ <%= csrf_meta_tags %> <%= csp_meta_tag %> <%= yield :head %> + + + + - + <%= stylesheet_link_tag :app, "data-turbo-track": "reload" %> <%= javascript_importmap_tags %> diff --git a/app/views/layouts/public.html.erb b/app/views/layouts/public.html.erb index a20e594..cb8d589 100644 --- a/app/views/layouts/public.html.erb +++ b/app/views/layouts/public.html.erb @@ -7,7 +7,13 @@ <%= csrf_meta_tags %> <%= csp_meta_tag %> + + + + + + <%= stylesheet_link_tag :app, "data-turbo-track": "reload" %> <%= javascript_importmap_tags %> diff --git a/app/views/pwa/manifest.json.erb b/app/views/pwa/manifest.json.erb index 2d8f973..985b26d 100644 --- a/app/views/pwa/manifest.json.erb +++ b/app/views/pwa/manifest.json.erb @@ -1,22 +1,19 @@ { - "name": "SimpleAircraftManager", - "icons": [ - { - "src": "/icon.png", - "type": "image/png", - "sizes": "512x512" - }, - { - "src": "/icon.png", - "type": "image/png", - "sizes": "512x512", - "purpose": "maskable" - } - ], + "id": "/", + "name": "Simple Aircraft Manager", + "short_name": "SAM", + "description": "Maintenance, inspections, ADs, squawks and flight logs for your aircraft.", "start_url": "/", - "display": "standalone", "scope": "/", - "description": "SimpleAircraftManager.", - "theme_color": "red", - "background_color": "red" + "display": "standalone", + "orientation": "any", + "theme_color": "#0f172a", + "background_color": "#0f172a", + "categories": ["productivity", "utilities"], + "icons": [ + { "src": "/icon-192.png", "type": "image/png", "sizes": "192x192", "purpose": "any" }, + { "src": "/icon.png", "type": "image/png", "sizes": "512x512", "purpose": "any" }, + { "src": "/icon-maskable.png", "type": "image/png", "sizes": "512x512", "purpose": "maskable" }, + { "src": "/icon.svg", "type": "image/svg+xml", "sizes": "any", "purpose": "any" } + ] } diff --git a/app/views/pwa/service-worker.js b/app/views/pwa/service-worker.js index b3a13fb..a608e83 100644 --- a/app/views/pwa/service-worker.js +++ b/app/views/pwa/service-worker.js @@ -1,26 +1,53 @@ -// Add a service worker for processing Web Push notifications: -// -// self.addEventListener("push", async (event) => { -// const { title, options } = await event.data.json() -// event.waitUntil(self.registration.showNotification(title, options)) -// }) -// -// self.addEventListener("notificationclick", function(event) { -// event.notification.close() -// event.waitUntil( -// clients.matchAll({ type: "window" }).then((clientList) => { -// for (let i = 0; i < clientList.length; i++) { -// let client = clientList[i] -// let clientPath = (new URL(client.url)).pathname -// -// if (clientPath == event.notification.data.path && "focus" in client) { -// return client.focus() -// } -// } -// -// if (clients.openWindow) { -// return clients.openWindow(event.notification.data.path) -// } -// }) -// ) -// }) +// Makes the app installable and gives it an offline page. Only public, static +// files are cached (the offline page, icons and fingerprinted /assets/), never +// aircraft pages, so no private data is stored on the device. +const VERSION = "v1" +const SHELL_CACHE = `sam-shell-${VERSION}` +const ASSET_CACHE = "sam-assets" +const MAX_ASSETS = 80 +const SHELL = [ "/offline.html", "/icon.svg", "/icon-192.png" ] + +self.addEventListener("install", (event) => { + event.waitUntil(caches.open(SHELL_CACHE).then((cache) => cache.addAll(SHELL)).then(() => self.skipWaiting())) +}) + +self.addEventListener("activate", (event) => { + event.waitUntil( + caches.keys() + .then((keys) => Promise.all(keys.filter((k) => k.startsWith("sam-shell-") && k !== SHELL_CACHE).map((k) => caches.delete(k)))) + .then(() => self.clients.claim()) + ) +}) + +self.addEventListener("fetch", (event) => { + const request = event.request + if (request.method !== "GET") return + const url = new URL(request.url) + if (url.origin !== self.location.origin) return + + if (request.mode === "navigate") { + // Always go to the network for pages; show the offline page if it's unreachable. + event.respondWith(fetch(request).catch(() => caches.match("/offline.html"))) + } else if (url.pathname.startsWith("/assets/")) { + event.respondWith(cachedAsset(request)) + } +}) + +// Fingerprinted assets never change, so serve them from cache once fetched. +async function cachedAsset(request) { + const cache = await caches.open(ASSET_CACHE) + const hit = await cache.match(request) + if (hit) return hit + const response = await fetch(request) + if (response.ok) { + await cache.put(request, response.clone()) + trim(cache) + } + return response +} + +// Old deploys' assets pile up; keep only the most recent entries. +async function trim(cache) { + const keys = await cache.keys() + await Promise.all(keys.slice(0, Math.max(0, keys.length - MAX_ASSETS)).map((k) => cache.delete(k))) +} diff --git a/config/routes.rb b/config/routes.rb index c3000e8..3c51b1c 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -72,5 +72,7 @@ Rails.application.routes.draw do end get "up" => "rails/health#show", as: :rails_health_check + get "manifest" => "rails/pwa#manifest", as: :pwa_manifest + get "service-worker" => "rails/pwa#service_worker", as: :pwa_service_worker root "aircraft#index" end diff --git a/public/apple-touch-icon.png b/public/apple-touch-icon.png new file mode 100644 index 0000000..ed7c5cf Binary files /dev/null and b/public/apple-touch-icon.png differ diff --git a/public/icon-192.png b/public/icon-192.png new file mode 100644 index 0000000..e3f0801 Binary files /dev/null and b/public/icon-192.png differ diff --git a/public/icon-maskable.png b/public/icon-maskable.png new file mode 100644 index 0000000..db7b7d5 Binary files /dev/null and b/public/icon-maskable.png differ diff --git a/public/icon.png b/public/icon.png index c4c9dbf..8dc4bae 100644 Binary files a/public/icon.png and b/public/icon.png differ diff --git a/public/icon.svg b/public/icon.svg index 04b34bf..0997366 100644 --- a/public/icon.svg +++ b/public/icon.svg @@ -1,3 +1,5 @@ - - + + + + diff --git a/public/offline.html b/public/offline.html new file mode 100644 index 0000000..d4936c3 --- /dev/null +++ b/public/offline.html @@ -0,0 +1,34 @@ + + + + + + + Offline ยท Simple Aircraft Manager + + + + +
+ +

You're offline

+

Simple Aircraft Manager needs a connection to load your aircraft. Check your signal and try again.

+ +
+ + + diff --git a/test/integration/pwa_test.rb b/test/integration/pwa_test.rb new file mode 100644 index 0000000..953eefc --- /dev/null +++ b/test/integration/pwa_test.rb @@ -0,0 +1,34 @@ +require "test_helper" + +class PwaTest < ActionDispatch::IntegrationTest + test "manifest is public and points at icons that exist" do + get pwa_manifest_path(format: :json) + assert_response :success + manifest = JSON.parse(response.body) + assert_equal "Simple Aircraft Manager", manifest["name"] + assert_equal "standalone", manifest["display"] + assert_includes manifest["icons"].map { _1["purpose"] }, "maskable" + manifest["icons"].each { |icon| assert Rails.public_path.join(icon["src"].delete_prefix("/")).exist?, icon["src"] } + end + + test "service worker is public and precaches files that exist" do + get pwa_service_worker_path(format: :js) + assert_response :success + assert_match "javascript", response.media_type + shell = response.body[/const SHELL = \[(.*?)\]/, 1].scan(/"([^"]+)"/).flatten + assert_includes shell, "/offline.html" + shell.each { |path| assert Rails.public_path.join(path.delete_prefix("/")).exist?, path } + end + + test "signed-in and shared pages link the manifest and register the worker" do + sign_in create_user + get root_path + assert_select "link[rel=manifest][href='/manifest.json']" + assert_select "meta[name=theme-color]" + assert_select "link[rel=apple-touch-icon][href='/apple-touch-icon.png']" + + token = create_aircraft(owner: create_user("o2@example.com")).share_tokens.create!(privilege: "status") + get shared_path(token.token) + assert_select "link[rel=manifest]" + end +end