mirror of
https://github.com/rickbarrette/simple-aircraft-manager-rails.git
synced 2026-11-17 23:50:36 -05:00
Installed app: offline squawks and pre-flight pages, push notifications, shortcuts
Offline
- Flights and squawks saved offline are tagged with their user and only sent
while that user is signed in; storage is made persistent; Background Sync
sends them with the app closed (Chromium); unsent count on the app badge
- Report Squawk works offline (photos included, one-time key like flights)
- The Fleet page and, for each of your aircraft, the Overview, W&B, Log
Flight and Report Squawk pages and photo are saved ahead of time, so the
app opens and works without signal; copies say when they were saved
- Sign-out clears saved forms, pages and photos (asks first if items wait)
- Offline page rendered by Rails (localized, follows the theme, no inline
script); service worker version follows the build
Install and notify
- Web Push (web-push gem, VAPID keys from env or storage/vapid_keys.json):
grounding squawks, newly overdue items (daily, once each), signing
requests; per-device on/off and test in Profile -> This device; only
browser push service endpoints accepted
- Manifest shortcuts (Log Flight, Report Squawk via /go/...), lang and
localized description; install help on Profile; reload notice after a
release
Also
- Dockerfile: libssl-dev in the build stage (openssl gem); lockfile checksums
- Leftover English and %{_} interpolation names from the localization pass
- Guide and README updated
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
89ed0a76f9
commit
8d5f57da81
54 files changed
+1217
-203
No files matched your search
@@ -2,7 +2,7 @@
|
||||
<%= f.errors_summary %>
|
||||
<%= f.field :name %>
|
||||
<%= f.field :email_address, as: :email, label: t(".email"), required: true %>
|
||||
<%= f.field :password, as: :password, hint: (user.persisted? ? t(".leave_blank_to_keep_current") : t(".at_least_characters_not_one", _: (User::PASSWORD_MIN))), autocomplete: "new-password" %>
|
||||
<%= f.field :password, as: :password, hint: (user.persisted? ? t(".leave_blank_to_keep_current") : t(".at_least_characters_not_one", min: User::PASSWORD_MIN)), autocomplete: "new-password" %>
|
||||
<%= f.field :password_confirmation, as: :password %>
|
||||
<%= f.field :admin, as: :checkbox, label: t(".administrator"), hint: t(".admins_can_see_and_edit") %>
|
||||
<div class="flex gap-2"><%= f.submit t(".save") %><%= link_to t(".cancel"), admin_users_path, class: "btn-secondary" %></div>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<% content_for :title, @aircraft.tail_number %>
|
||||
<% content_for :head do %><meta name="aircraft-tail" content="<%= @aircraft.tail_number %>"><% end %>
|
||||
<%= render "shared/aircraft_header", aircraft: @aircraft %>
|
||||
|
||||
<div class="grid gap-5 lg:grid-cols-3">
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
<% content_for :title, t(".log_flight") %>
|
||||
<%= render "shared/aircraft_header", aircraft: @aircraft %>
|
||||
<%= form_with model: [@aircraft, @flight_log], class: "card card-body space-y-5 max-w-3xl",
|
||||
data: { controller: "offline-flight", offline_flight_tail_value: @aircraft.tail_number,
|
||||
action: "submit->offline-flight#submit turbo:submit-start->offline-flight#remember turbo:fetch-request-error->offline-flight#networkFailed turbo:before-fetch-response->offline-flight#gatewayFailed" } do |f| %>
|
||||
<%= f.hidden_field :client_key, data: { offline_flight_target: "key" } %>
|
||||
<div class="hidden rounded-md bg-sky-50 px-3 py-2 text-sm text-sky-900 ring-1 ring-sky-200" data-offline-flight-target="notice" role="status"></div>
|
||||
data: { controller: "offline-form", offline_form_kind_value: "flight", offline_form_tail_value: @aircraft.tail_number,
|
||||
action: "submit->offline-form#submit turbo:submit-start->offline-form#remember turbo:fetch-request-error->offline-form#networkFailed turbo:before-fetch-response->offline-form#gatewayFailed" } do |f| %>
|
||||
<%= f.hidden_field :client_key, data: { offline_form_target: "key" } %>
|
||||
<div class="hidden rounded-md bg-sky-50 px-3 py-2 text-sm text-sky-900 ring-1 ring-sky-200" data-offline-form-target="notice" role="status"></div>
|
||||
<%= f.errors_summary %>
|
||||
<div class="grid gap-4 sm:grid-cols-3">
|
||||
<%= f.field :date, as: :date, required: true %>
|
||||
|
||||
@@ -18,11 +18,17 @@
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
|
||||
<%= stylesheet_link_tag :app, "data-turbo-track": "reload" %>
|
||||
<%= javascript_importmap_tags %>
|
||||
<meta name="rendered-at" content="<%= Time.current.iso8601 %>">
|
||||
<% if current_user %><meta name="current-user" content="<%= current_user.id %>"><% end %>
|
||||
<script type="application/json" id="i18n" nonce="<%= content_security_policy_nonce %>"><%= json_escape(t("js").to_json).html_safe %></script>
|
||||
</head>
|
||||
|
||||
<body class="min-h-full text-slate-800" data-controller="offline-sync">
|
||||
<body class="min-h-full text-slate-800" data-controller="offline-sync page-age app-update<%= " offline-prep" if current_user %>"<% if current_user %> data-offline-prep-aircraft-value="<%= offline_pages.to_json %>"<% end %>>
|
||||
<%= t(".skip_to_content_html") %>
|
||||
<div class="hidden bg-sky-50 px-4 py-2 text-center text-sm text-sky-900 ring-1 ring-sky-200" data-page-age-target="banner" role="status"></div>
|
||||
<div class="hidden bg-sky-50 px-4 py-2 text-center text-sm text-sky-900 ring-1 ring-sky-200" data-app-update-target="banner" role="status">
|
||||
<%= t(".updated") %> <button type="button" class="btn-secondary btn-sm ml-1" data-action="app-update#reload"><%= t(".reload") %></button>
|
||||
</div>
|
||||
<div class="hidden space-y-1 bg-amber-50 px-4 py-2 text-center text-sm text-amber-900 ring-1 ring-amber-200" data-offline-sync-target="banner" role="status"></div>
|
||||
<header class="bg-header text-white">
|
||||
<div class="mx-auto flex max-w-7xl items-center justify-between gap-4 px-4 py-3">
|
||||
@@ -47,7 +53,7 @@
|
||||
<%= link_to label, path, class: "block px-4 py-2.5 hover:bg-slate-100" %>
|
||||
<% end %>
|
||||
<% end %>
|
||||
<div class="border-t border-slate-100"><%= button_to t(".sign_out"), session_path, method: :delete, class: "block w-full px-4 py-2.5 text-left hover:bg-slate-100" %></div>
|
||||
<div class="border-t border-slate-100"><%= button_to t(".sign_out"), session_path, method: :delete, class: "block w-full px-4 py-2.5 text-left hover:bg-slate-100", form: { data: { controller: "sign-out", action: "submit->sign-out#clean" } } %></div>
|
||||
</div>
|
||||
</details>
|
||||
</nav>
|
||||
@@ -73,7 +79,7 @@
|
||||
<%= link_to t(".help"), help_path, class: "hover:text-sky-300" %>
|
||||
<%= link_to current_user.display_name, edit_profile_path, class: "text-white/70 hover:text-sky-300 hidden sm:inline" %>
|
||||
<%= render "shared/theme_toggle" %>
|
||||
<%= button_to t(".sign_out"), session_path, method: :delete, class: "rounded bg-white/10 px-2 py-1 hover:bg-white/20" %>
|
||||
<%= button_to t(".sign_out"), session_path, method: :delete, class: "rounded bg-white/10 px-2 py-1 hover:bg-white/20", form: { data: { controller: "sign-out", action: "submit->sign-out#clean" } } %>
|
||||
</nav>
|
||||
<% end %>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="<%= I18n.locale %>">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<meta name="theme-color" content="#0f172a">
|
||||
<title><%= t(".title") %></title>
|
||||
<link rel="icon" href="/favicon.svg" type="image/svg+xml">
|
||||
<style>
|
||||
:root { --page: #f1f5f9; --surface: #fff; --text: #1e293b; --muted: #64748b; --accent: #0369a1; }
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root:not([data-theme="light"]) { --page: #0b1220; --surface: #0f172a; --text: #e2e8f0; --muted: #94a3b8; }
|
||||
}
|
||||
:root[data-theme="dark"] { --page: #0b1220; --surface: #0f172a; --text: #e2e8f0; --muted: #94a3b8; }
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 16px;
|
||||
background: var(--page); color: var(--text); font: 16px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; }
|
||||
main { max-width: 26rem; width: 100%; background: var(--surface); border-radius: 12px; padding: 32px 24px; text-align: center;
|
||||
box-shadow: 0 1px 3px rgb(0 0 0 / 0.1); }
|
||||
img { width: 72px; height: 72px; }
|
||||
h1 { font-size: 1.25rem; margin: 16px 0 8px; }
|
||||
p { margin: 0 0 24px; color: var(--muted); }
|
||||
#forms a, #pages a { display: block; margin-top: 8px; color: var(--accent); font-weight: 600; }
|
||||
button { font: inherit; font-weight: 600; color: #fff; background: var(--accent); border: 0; border-radius: 6px; padding: 10px 20px; cursor: pointer; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<img src="/icon.svg" alt="">
|
||||
<h1><%= t(".heading") %></h1>
|
||||
<p><%= t(".needs_connection") %></p>
|
||||
<button type="button" id="retry"><%= t(".try_again") %></button>
|
||||
<div id="forms" hidden data-flight="<%= t(".log_flight") %>" data-squawk="<%= t(".report_squawk") %>">
|
||||
<p style="margin:24px 0 8px"><%= t(".still_can") %></p>
|
||||
</div>
|
||||
<div id="pages" hidden data-label="<%= t(".saved_overview") %>">
|
||||
<p style="margin:24px 0 8px"><%= t(".saved_pages") %></p>
|
||||
</div>
|
||||
</main>
|
||||
<script src="/offline.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -88,6 +88,28 @@
|
||||
<% end %>
|
||||
</section>
|
||||
|
||||
<section class="card card-body mt-5 max-w-md space-y-4" id="device">
|
||||
<h2 class="card-title"><%= t(".this_device") %></h2>
|
||||
<div data-controller="install">
|
||||
<h3 class="text-sm font-semibold"><%= t(".install_heading") %></h3>
|
||||
<p class="hint"><%= t(".install_why") %></p>
|
||||
<p class="mt-2 text-sm text-emerald-700" data-install-target="installed" hidden><%= t(".installed") %></p>
|
||||
<button type="button" class="btn-secondary btn-sm mt-2" data-install-target="button" data-action="install#install" hidden><%= t(".install") %></button>
|
||||
<p class="mt-2 text-sm text-slate-600" data-install-target="ios" hidden><%= t(".install_ios_html") %></p>
|
||||
<p class="mt-2 text-sm text-slate-600" data-install-target="other" hidden><%= t(".install_other") %></p>
|
||||
</div>
|
||||
<div data-controller="push" data-push-key-value="<%= PushKeys.public_key %>" data-push-url-value="<%= push_subscription_path %>" data-push-test-url-value="<%= test_push_subscription_path %>">
|
||||
<h3 class="text-sm font-semibold"><%= t(".notifications_heading") %></h3>
|
||||
<p class="hint"><%= t(".notifications_what") %></p>
|
||||
<p class="mt-2 text-sm text-slate-600" data-push-target="status" role="status"></p>
|
||||
<div class="mt-2 flex flex-wrap gap-2">
|
||||
<button type="button" class="btn-secondary btn-sm" data-push-target="on" data-action="push#turnOn" hidden><%= t(".notifications_on") %></button>
|
||||
<button type="button" class="btn-secondary btn-sm" data-push-target="off" data-action="push#turnOff" hidden><%= t(".notifications_off") %></button>
|
||||
<button type="button" class="btn-secondary btn-sm" data-push-target="test" data-action="push#sendTest" hidden><%= t(".notifications_test") %></button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card card-body mt-5 max-w-md">
|
||||
<h2 class="card-title"><%= t(".sessions") %></h2>
|
||||
<% others = @user.sessions.where.not(id: Current.session.id).count %>
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
"id": "/",
|
||||
"name": "Simple Aircraft Manager",
|
||||
"short_name": "SAM",
|
||||
"description": "Maintenance, inspections, ADs, squawks and flight logs for your aircraft.",
|
||||
"description": <%= raw t("pwa.description").to_json %>,
|
||||
"lang": "<%= I18n.locale %>",
|
||||
"start_url": "/",
|
||||
"scope": "/",
|
||||
"display": "standalone",
|
||||
@@ -15,5 +16,9 @@
|
||||
{ "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" }
|
||||
],
|
||||
"shortcuts": [
|
||||
{ "name": <%= raw t("pwa.log_flight").to_json %>, "url": "/go/log-flight", "icons": [ { "src": "/icon-192.png", "sizes": "192x192" } ] },
|
||||
{ "name": <%= raw t("pwa.report_squawk").to_json %>, "url": "/go/report-squawk", "icons": [ { "src": "/icon-192.png", "sizes": "192x192" } ] }
|
||||
]
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
// Makes the app installable and gives it an offline page. Cached: public,
|
||||
// static files (the offline page, icons, fingerprinted /assets/) and, so a
|
||||
// flight can be logged without signal, the Log Flight forms you've opened
|
||||
// (tail number and meter readings only). Other aircraft pages are never cached.
|
||||
const VERSION = "v5"
|
||||
const FORM_CACHE = "sam-flight-forms"
|
||||
const FLIGHT_FORM = /^\/aircraft\/\d+\/flight_logs\/new$/
|
||||
const SHELL_CACHE = `sam-shell-${VERSION}`
|
||||
const ASSET_CACHE = "sam-assets"
|
||||
const MAX_ASSETS = 80
|
||||
// A proxy in front of the app (Traefik, Authentik) answers these when the app
|
||||
// itself can't be reached: treat them like no connection.
|
||||
const UNREACHABLE = [ 502, 503, 504 ]
|
||||
const SHELL = [ "/offline.html", "/offline.js", "/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
|
||||
|
||||
// Turbo opens pages with fetch(), not a navigation, so match those too or
|
||||
// the form is never kept when reached by tapping "Log Flight".
|
||||
const wantsHtml = request.mode === "navigate" || (request.headers.get("Accept") || "").includes("text/html")
|
||||
if (wantsHtml && FLIGHT_FORM.test(url.pathname)) {
|
||||
event.respondWith(flightForm(request))
|
||||
} else if (request.mode === "navigate") {
|
||||
// Always go to the network for pages; show the offline page if it's unreachable.
|
||||
event.respondWith(fetch(request)
|
||||
.then((response) => UNREACHABLE.includes(response.status) ? caches.match("/offline.html") : response)
|
||||
.catch(() => caches.match("/offline.html")))
|
||||
} else if (SHELL.includes(url.pathname)) {
|
||||
// The offline page's own script and icon: fresh when online, kept copy when not.
|
||||
event.respondWith(fetch(request).then((r) => r.ok ? r : caches.match(url.pathname).then((hit) => hit || r))
|
||||
.catch(() => caches.match(url.pathname)))
|
||||
} 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)))
|
||||
}
|
||||
|
||||
// The Log Flight form: fresh from the network when there is one (and kept),
|
||||
// the kept copy when there isn't.
|
||||
async function flightForm(request) {
|
||||
const cache = await caches.open(FORM_CACHE)
|
||||
const key = request.url.split("?")[0]
|
||||
try {
|
||||
const response = await fetch(request)
|
||||
if (UNREACHABLE.includes(response.status)) {
|
||||
const kept = await cache.match(key)
|
||||
if (kept) return kept
|
||||
return request.mode === "navigate" ? caches.match("/offline.html") : response
|
||||
}
|
||||
const html = (response.headers.get("Content-Type") || "").includes("text/html")
|
||||
if (response.ok && !response.redirected && html) await cache.put(key, response.clone())
|
||||
return response
|
||||
} catch (error) {
|
||||
const kept = await cache.match(key)
|
||||
if (kept) return kept
|
||||
// A Turbo fetch gets the error, so Turbo falls back to a full page load.
|
||||
if (request.mode !== "navigate") throw error
|
||||
return caches.match("/offline.html")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
// Makes the app installable and keeps what's needed to work without signal:
|
||||
// - the offline page (rendered in the app's language) and its script and icons;
|
||||
// - fingerprinted /assets/ once fetched;
|
||||
// - the Log Flight and Report Squawk forms you've opened (tail number and
|
||||
// meter readings only), so they can be filled in offline and sent later;
|
||||
// - the Fleet page and each aircraft's Overview and weight and balance page,
|
||||
// so the app opens and you can get around without signal (shown with the
|
||||
// time they were saved).
|
||||
// - each aircraft's photo (put in sam-images ahead of time), shown when offline.
|
||||
// The forms and pages are saved ahead of time for all your aircraft
|
||||
// (offline_prep_controller.js), not only the ones you've opened.
|
||||
// Nothing else is cached; signing out clears the forms and pages.
|
||||
// The version changes with every build, so a release refreshes the cached shell.
|
||||
const VERSION = "<%= j "#{SystemInfo.new.revision}-#{I18n.locale}" %>"
|
||||
const SHELL_CACHE = `sam-shell-${VERSION}`
|
||||
const FORM_CACHE = "sam-forms"
|
||||
const PAGE_CACHE = "sam-pages"
|
||||
const IMAGE_CACHE = "sam-images"
|
||||
const ASSET_CACHE = "sam-assets"
|
||||
const MAX_ASSETS = 80
|
||||
const FORMS = /^\/aircraft\/\d+\/(flight_logs|squawks)\/new$/
|
||||
const PAGES = /^\/$|^\/aircraft\/\d+(\/weight_balance)?$/
|
||||
const SHORTCUTS = { "/go/log-flight": "flight_logs", "/go/report-squawk": "squawks" }
|
||||
// A proxy in front of the app (Traefik, Authentik) answers these when the app
|
||||
// itself can't be reached: treat them like no connection.
|
||||
const UNREACHABLE = [ 502, 503, 504 ]
|
||||
const SHELL = [ "/offline", "/offline.js", "/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) || k === "sam-flight-forms").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
|
||||
|
||||
// Turbo opens pages with fetch(), not a navigation, so match those too or
|
||||
// the form is never kept when reached by tapping a link.
|
||||
const wantsHtml = request.mode === "navigate" || (request.headers.get("Accept") || "").includes("text/html")
|
||||
if (wantsHtml && FORMS.test(url.pathname)) {
|
||||
event.respondWith(keptPage(request, FORM_CACHE))
|
||||
} else if (wantsHtml && PAGES.test(url.pathname)) {
|
||||
event.respondWith(keptPage(request, PAGE_CACHE))
|
||||
} else if (request.mode === "navigate" && SHORTCUTS[url.pathname]) {
|
||||
event.respondWith(shortcut(request, SHORTCUTS[url.pathname]))
|
||||
} else if (request.mode === "navigate") {
|
||||
// Always go to the network for pages; show the offline page if it's unreachable.
|
||||
event.respondWith(fetch(request)
|
||||
.then((response) => UNREACHABLE.includes(response.status) ? offlinePage() : response)
|
||||
.catch(() => offlinePage()))
|
||||
} else if (SHELL.includes(url.pathname)) {
|
||||
// The offline page's own script and icon: fresh when online, kept copy when not.
|
||||
event.respondWith(fetch(request).then((r) => r.ok ? r : caches.match(url.pathname).then((hit) => hit || r))
|
||||
.catch(() => caches.match(url.pathname)))
|
||||
} else if (url.pathname.startsWith("/assets/")) {
|
||||
event.respondWith(cachedAsset(request))
|
||||
} else if (url.pathname.startsWith("/rails/active_storage/blobs/redirect/")) {
|
||||
// Uploaded files come from the network; an aircraft photo saved for
|
||||
// offline use stands in when there's none.
|
||||
event.respondWith(fetch(request)
|
||||
.then((response) => UNREACHABLE.includes(response.status) ? savedImage(request, response) : response)
|
||||
.catch(() => savedImage(request)))
|
||||
}
|
||||
})
|
||||
|
||||
const offlinePage = () => caches.match("/offline")
|
||||
const savedImage = async (request, response) => {
|
||||
const key = imageKey(request.url)
|
||||
return (key && await caches.open(IMAGE_CACHE).then((c) => c.match(key))) || response || Response.error()
|
||||
}
|
||||
|
||||
// Photo links carry an expiry, so they change with every page; the saved copy
|
||||
// is filed under the upload's id instead (same rule in offline_prep_controller.js).
|
||||
function imageKey(url) {
|
||||
try {
|
||||
const signed = new URL(url, self.location.origin).pathname.match(/\/blobs\/redirect\/([^/]+?)--/)[1]
|
||||
return `${self.location.origin}/offline-image/${JSON.parse(atob(decodeURIComponent(signed)))._rails.data}`
|
||||
} catch (_) { return null }
|
||||
}
|
||||
|
||||
// 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)))
|
||||
}
|
||||
|
||||
// A kept form or page: fresh from the network when there is one (and kept),
|
||||
// the kept copy when there isn't.
|
||||
async function keptPage(request, cacheName) {
|
||||
const cache = await caches.open(cacheName)
|
||||
const key = request.url.split("?")[0]
|
||||
try {
|
||||
const response = await fetch(request)
|
||||
if (UNREACHABLE.includes(response.status)) {
|
||||
const kept = await cache.match(key)
|
||||
if (kept) return kept
|
||||
return request.mode === "navigate" ? offlinePage() : response
|
||||
}
|
||||
const html = (response.headers.get("Content-Type") || "").includes("text/html")
|
||||
if (response.ok && !response.redirected && html) await cache.put(key, response.clone())
|
||||
return response
|
||||
} catch (error) {
|
||||
const kept = await cache.match(key)
|
||||
if (kept) return kept
|
||||
// A Turbo fetch gets the error, so Turbo falls back to a full page load.
|
||||
if (request.mode !== "navigate") throw error
|
||||
return offlinePage()
|
||||
}
|
||||
}
|
||||
|
||||
// The home-screen shortcuts: offline, open the kept form if there's only one
|
||||
// of that kind (one aircraft), otherwise the offline page, which lists them.
|
||||
async function shortcut(request, kind) {
|
||||
try {
|
||||
const response = await fetch(request)
|
||||
if (!UNREACHABLE.includes(response.status)) return response
|
||||
} catch (_) { /* offline */ }
|
||||
const cache = await caches.open(FORM_CACHE)
|
||||
const forms = (await cache.keys()).filter((r) => new URL(r.url).pathname.includes(`/${kind}/new`))
|
||||
return forms.length === 1 ? cache.match(forms[0]) : offlinePage()
|
||||
}
|
||||
|
||||
// ---- Sending saved items in the background (Chrome, Edge, Android) ----
|
||||
// The page normally sends them (offline_sync_controller); this also does it
|
||||
// when the app is closed. Anything the server doesn't accept is left for the
|
||||
// page to report.
|
||||
|
||||
self.addEventListener("sync", (event) => {
|
||||
if (event.tag === "sam-queue") event.waitUntil(sendQueued())
|
||||
})
|
||||
|
||||
function queueStore(mode) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = indexedDB.open("sam-offline", 1)
|
||||
req.onupgradeneeded = () => req.result.createObjectStore("flights", { keyPath: "id" })
|
||||
req.onsuccess = () => resolve(req.result.transaction("flights", mode).objectStore("flights"))
|
||||
req.onerror = () => reject(req.error)
|
||||
})
|
||||
}
|
||||
|
||||
const idb = (store, method, arg) => new Promise((resolve, reject) => {
|
||||
const req = store[method](arg)
|
||||
req.onsuccess = () => resolve(req.result)
|
||||
req.onerror = () => reject(req.error)
|
||||
})
|
||||
|
||||
async function sendQueued() {
|
||||
const items = ((await idb(await queueStore("readonly"), "getAll")) || []).filter((i) => !i.error)
|
||||
.sort((a, b) => a.savedAt.localeCompare(b.savedAt))
|
||||
if (!items.length) return
|
||||
// A page of the app gives the session's CSRF token and who's signed in.
|
||||
const page = await fetch("/profile/edit", { credentials: "same-origin", headers: { Accept: "text/html" } })
|
||||
if (!page.ok || page.redirected) return
|
||||
const html = await page.text()
|
||||
const token = (html.match(/<meta name="csrf-token" content="([^"]+)"/) || [])[1]
|
||||
const user = (html.match(/<meta name="current-user" content="([^"]+)"/) || [])[1]
|
||||
if (!token || !user) return
|
||||
let sent = 0
|
||||
for (const item of items) {
|
||||
if (item.user && item.user !== user) continue
|
||||
const body = new FormData()
|
||||
for (const [ name, value ] of item.fields) body.append(name, value)
|
||||
body.append("authenticity_token", token)
|
||||
const response = await fetch(item.url, { method: "POST", body, credentials: "same-origin", headers: { Accept: "text/html" } })
|
||||
if (UNREACHABLE.includes(response.status)) break
|
||||
if (!response.ok || response.url.includes("/session/new")) continue // left for the page to report
|
||||
await idb(await queueStore("readwrite"), "delete", item.id)
|
||||
sent++
|
||||
}
|
||||
if (sent) (await self.clients.matchAll()).forEach((client) => client.postMessage({ type: "queue-changed" }))
|
||||
}
|
||||
|
||||
// ---- Push notifications ----
|
||||
|
||||
self.addEventListener("push", (event) => {
|
||||
let data = {}
|
||||
try { data = event.data ? event.data.json() : {} } catch (_) { data = { title: event.data?.text() } }
|
||||
event.waitUntil(self.registration.showNotification(data.title || "Simple Aircraft Manager", {
|
||||
body: data.body, tag: data.tag, icon: "/icon-192.png", badge: "/icon-192.png", data: { path: data.path || "/" }
|
||||
}))
|
||||
})
|
||||
|
||||
self.addEventListener("notificationclick", (event) => {
|
||||
event.notification.close()
|
||||
const target = new URL(event.notification.data?.path || "/", self.location.origin).href
|
||||
event.waitUntil(self.clients.matchAll({ type: "window", includeUncontrolled: true }).then((windows) => {
|
||||
const open = windows.find((w) => w.url.startsWith(self.location.origin))
|
||||
if (open) return open.navigate(target).then((w) => (w || open).focus())
|
||||
return self.clients.openWindow(target)
|
||||
}))
|
||||
})
|
||||
@@ -0,0 +1,14 @@
|
||||
<% content_for :title, @title %>
|
||||
<h1 class="mb-4 text-xl font-bold"><%= @title %></h1>
|
||||
<% if @choices.any? %>
|
||||
<ul class="card max-w-md divide-y divide-slate-100">
|
||||
<% @choices.each do |aircraft, path| %>
|
||||
<li><%= link_to path, class: "flex items-baseline justify-between gap-3 px-4 py-3 hover:bg-slate-50" do %>
|
||||
<span class="font-semibold"><%= aircraft.tail_number %></span>
|
||||
<span class="text-sm text-slate-500"><%= [ aircraft.make, aircraft.model ].compact_blank.join(" ") %></span>
|
||||
<% end %></li>
|
||||
<% end %>
|
||||
</ul>
|
||||
<% else %>
|
||||
<%= empty_state t("shortcuts.choose.no_aircraft") %>
|
||||
<% end %>
|
||||
@@ -1,4 +1,10 @@
|
||||
<%= form_with model: [aircraft, squawk], multipart: true, class: "card card-body space-y-4 max-w-2xl" do |f| %>
|
||||
<%= form_with model: [aircraft, squawk], multipart: true, class: "card card-body space-y-4 max-w-2xl",
|
||||
data: (squawk.new_record? ? { controller: "offline-form", offline_form_kind_value: "squawk", offline_form_tail_value: aircraft.tail_number,
|
||||
action: "submit->offline-form#submit turbo:submit-start->offline-form#remember turbo:fetch-request-error->offline-form#networkFailed turbo:before-fetch-response->offline-form#gatewayFailed" } : {}) do |f| %>
|
||||
<% if squawk.new_record? %>
|
||||
<%= f.hidden_field :client_key, data: { offline_form_target: "key" } %>
|
||||
<div class="hidden rounded-md bg-sky-50 px-3 py-2 text-sm text-sky-900 ring-1 ring-sky-200" data-offline-form-target="notice" role="status"></div>
|
||||
<% end %>
|
||||
<%= f.errors_summary %>
|
||||
<%= f.field :priority, as: :select, collection: Squawk::PRIORITIES.invert, hint: t(".ground_aircraft_makes_the_aircraft") %>
|
||||
<%= f.field :issue_reported, as: :textarea, label: t(".issue"), required: true, autofocus: true %>
|
||||
|
||||
Reference in new issue
Block a user