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:
rickyandClaude Opus 5.5 committed 2026-11-13 22:39:42 -05:00
1 parent 89ed0a76f9
commit 8d5f57da81
54 files changed
+1217 -203

No files matched your search

@@ -0,0 +1,15 @@
import { Controller } from "@hotwired/stimulus"
// After a release, offers to reload so this page picks up the new version.
export default class extends Controller {
static targets = [ "banner" ]
connect() {
this.show = () => this.bannerTarget.classList.remove("hidden")
document.addEventListener("app:updated", this.show)
}
disconnect() { document.removeEventListener("app:updated", this.show) }
reload() { location.reload() }
}
@@ -30,7 +30,7 @@ export default class extends Controller {
add(event) {
for (const file of event.target.files) {
const item = { file, path: file.webkitRelativePath || file.name, state: "pending", progress: 0 }
if (file.size > this.maxBytesValue) Object.assign(item, { state: "error", error: `over the ${Math.round(this.maxBytesValue / 1048576)} MB limit` })
if (file.size > this.maxBytesValue) Object.assign(item, { state: "error", error: t("bulk_upload.over_limit", { mb: Math.round(this.maxBytesValue / 1048576) }) })
this.items.push(item)
}
event.target.value = ""
@@ -0,0 +1,34 @@
import { Controller } from "@hotwired/stimulus"
// Profile → This device: install the app. Chrome and Android offer a button;
// iPhone and iPad install from Safari's Share menu; elsewhere the browser's menu.
export default class extends Controller {
static targets = [ "button", "installed", "ios", "other" ]
connect() {
this.offer = () => this.render()
document.addEventListener("install:available", this.offer)
this.render()
}
disconnect() { document.removeEventListener("install:available", this.offer) }
render() {
const installed = matchMedia("(display-mode: standalone)").matches || navigator.standalone === true
const ios = /iPad|iPhone|iPod/.test(navigator.userAgent) || (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1)
const prompt = !installed && !!window.samInstallPrompt
this.installedTarget.hidden = !installed
this.buttonTarget.hidden = !prompt
this.iosTarget.hidden = installed || prompt || !ios
this.otherTarget.hidden = installed || prompt || ios
}
async install() {
const offer = window.samInstallPrompt
if (!offer) return
offer.prompt()
await offer.userChoice
window.samInstallPrompt = null
this.render()
}
}
@@ -1,26 +1,28 @@
import { Controller } from "@hotwired/stimulus"
import { t } from "i18n"
import { queue, formFields, newKey } from "controllers/offline_queue"
import { queue, formFields, newKey, currentUser } from "controllers/offline_queue"
// The Log Flight form: with no connection, the flight is kept on this device
// and sent later (see offline_sync_controller). The next leg starts where the
// last saved one ended.
// Log Flight and Report Squawk: with no connection, the form is kept on this
// device and sent later (see offline_sync_controller). For flights, the next
// leg starts where the last saved one ended.
export default class extends Controller {
static targets = [ "key", "notice" ]
static values = { tail: String }
static values = { kind: { type: String, default: "flight" }, tail: String }
async connect() {
if (!this.keyTarget.value) this.keyTarget.value = newKey()
try {
const mine = (await queue.all()).filter((i) => i.url === this.element.action)
const mine = (await queue.mine()).filter((i) => i.url === this.element.action)
if (mine.length) {
this.prefillFrom(mine[mine.length - 1])
this.say(`${mine.length} flight${mine.length > 1 ? "s" : ""} logged offline on this device, waiting to send. This one starts where the last ended.`)
if (this.flight) this.prefillFrom(mine[mine.length - 1])
this.say(t(`offline.${this.kindValue}.queued_here`, { count: mine.length }))
}
} catch (_) { /* no IndexedDB: nothing queued */ }
this.rememberForm()
}
get flight() { return this.kindValue === "flight" }
// No connection: keep it here instead of submitting.
async submit(event) {
if (navigator.onLine) return
@@ -36,8 +38,8 @@ export default class extends Controller {
if (this.pending) await this.save(this.pending)
}
// A proxy answered because the app is unreachable (502/503/504): keep the
// flight instead of showing the proxy's error page.
// A proxy answered because the app is unreachable (502/503/504): keep it
// instead of showing the proxy's error page.
async gatewayFailed(event) {
if (![ 502, 503, 504 ].includes(event.detail.fetchResponse.statusCode) || !this.pending) return
event.preventDefault()
@@ -45,19 +47,20 @@ export default class extends Controller {
}
async save(fields) {
const item = { id: this.keyTarget.value, url: this.element.action, tail: this.tailValue, savedAt: new Date().toISOString(), fields }
const item = { id: this.keyTarget.value, kind: this.kindValue, url: this.element.action, tail: this.tailValue,
user: currentUser(), savedAt: new Date().toISOString(), fields }
try {
await queue.add(item)
} catch (_) {
this.say(t("offline.no_storage"))
this.say(t(`offline.${this.kindValue}.no_storage`))
return
}
this.prefillFrom(item)
this.clearLegFields()
if (this.flight) this.prefillFrom(item)
this.clearFields()
this.keyTarget.value = newKey()
this.pending = null
window.scrollTo({ top: 0 })
this.say(t("offline.saved_on_device"))
this.say(t(`offline.${this.kindValue}.saved_on_device`))
document.dispatchEvent(new CustomEvent("offline-queue:changed"))
}
@@ -69,19 +72,22 @@ export default class extends Controller {
set("departure_location", value("destination_location"))
}
clearLegFields() {
for (const name of [ "tach_in", "tach_time", "hobbs_in", "hobbs_time", "destination_location", "route", "notes",
"oil_added", "oil_level_after", "fuel_added", "fuel_level_after", "track_log", "engine_data" ]) {
const el = this.element.querySelector(`[name="flight_log[${name}]"]`)
clearFields() {
const names = this.flight
? [ "tach_in", "tach_time", "hobbs_in", "hobbs_time", "destination_location", "route", "notes",
"oil_added", "oil_level_after", "fuel_added", "fuel_level_after", "track_log", "engine_data" ].map((n) => `flight_log[${n}]`)
: [ "squawk[issue_reported]", "squawk[attachments][]" ]
for (const name of names) {
const el = this.element.querySelector(`[name="${name}"]`)
if (el) el.value = ""
}
}
// Lets the offline page offer this form for this aircraft.
// Lets the offline page and the home-screen shortcuts offer this form.
rememberForm() {
try {
const forms = JSON.parse(localStorage.getItem("sam-offline-forms") || "{}")
forms[location.pathname] = this.tailValue
forms[location.pathname] = { tail: this.tailValue, kind: this.kindValue }
localStorage.setItem("sam-offline-forms", JSON.stringify(forms))
} catch (_) { /* storage off */ }
}
@@ -0,0 +1,67 @@
import { Controller } from "@hotwired/stimulus"
import { currentUser } from "controllers/offline_queue"
// Saves, ahead of time, what's needed to work without signal: the Fleet page
// and, for each of your aircraft, its Overview, W&B, Log Flight and Report
// Squawk pages (fetching them through the service worker keeps a copy, see
// service-worker.js) and its photo (kept in sam-images, shown when offline). Done in the background at most once an hour, or when
// your aircraft change. Signing out clears it.
const EVERY = 60 * 60 * 1000
export default class extends Controller {
static values = { aircraft: Array }
connect() {
if (!navigator.onLine || !("serviceWorker" in navigator)) return
navigator.serviceWorker.ready.then(() => this.prepare()).catch(() => {})
}
async prepare() {
const signature = `${currentUser()}:${JSON.stringify(this.aircraftValue)}`
let last = {}
try { last = JSON.parse(localStorage.getItem("sam-offline-prep") || "{}") } catch (_) { /* storage off */ }
if (last.signature === signature && Date.now() - last.at < EVERY) return
if (!navigator.serviceWorker.controller) return // first visit: the worker takes over on the next page
const forms = {}
const paths = [ "/" ]
for (const a of this.aircraftValue) {
paths.push(...a.pages, a.flight, a.squawk)
forms[a.flight] = { tail: a.tail, kind: "flight" }
forms[a.squawk] = { tail: a.tail, kind: "squawk" }
}
for (const path of paths) {
if (!navigator.onLine) return
// One at a time, after the page has settled, so it never competes with what you're doing.
await new Promise((resolve) => (window.requestIdleCallback || setTimeout)(resolve, { timeout: 2000 }))
try { await fetch(path, { credentials: "same-origin", headers: { Accept: "text/html" } }) } catch (_) { return }
}
await this.savePictures(this.aircraftValue.map((a) => a.picture).filter(Boolean))
try {
localStorage.setItem("sam-offline-forms", JSON.stringify({ ...JSON.parse(localStorage.getItem("sam-offline-forms") || "{}"), ...forms }))
localStorage.setItem("sam-offline-prep", JSON.stringify({ signature, at: Date.now() }))
} catch (_) { /* storage off */ }
}
// The aircraft photos: refreshed, and those of aircraft you no longer have dropped.
async savePictures(urls) {
try {
const cache = await caches.open("sam-images")
const wanted = urls.map((url) => [ url, imageKey(url) ]).filter(([ , key ]) => key)
for (const request of await cache.keys()) if (!wanted.some(([ , key ]) => key === request.url)) await cache.delete(request)
for (const [ url, key ] of wanted) {
const response = await fetch(url, { credentials: "same-origin" }).catch(() => null)
if (response?.ok) await cache.put(key, response)
}
} catch (_) { /* no Cache API */ }
}
}
// 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 service-worker.js).
function imageKey(url) {
try {
const signed = new URL(url, location.origin).pathname.match(/\/blobs\/redirect\/([^/]+?)--/)[1]
return `${location.origin}/offline-image/${JSON.parse(atob(decodeURIComponent(signed)))._rails.data}`
} catch (_) { return null }
}
+18 -5
View File
@@ -1,7 +1,9 @@
// Flights logged without a connection, kept in this browser (IndexedDB, so
// attached track and engine files are kept too) until they can be sent.
// Flights and squawks saved without a connection, kept in this browser
// (IndexedDB, so attached files are kept too) until they can be sent. Each
// is tagged with the user who saved it and only ever sent while they're
// signed in. The service worker reads the same store to send in the background.
const DB = "sam-offline"
const STORE = "flights"
const STORE = "flights" // holds every kind; the name predates squawks
function open() {
return new Promise((resolve, reject) => {
@@ -22,12 +24,23 @@ async function run(mode, fn) {
})
}
// item: { id, url, tail, savedAt, fields: [[name, value]], error }
// The signed-in user (from the layout), or "" on a page without one.
export const currentUser = () => document.querySelector("meta[name=current-user]")?.content || ""
// item: { id, kind: "flight" | "squawk", url, tail, user, savedAt, fields: [[name, value]], error }
export const queue = {
add: (item) => run("readwrite", (s) => s.put(item)),
add: async (item) => {
await run("readwrite", (s) => s.put(item))
// Ask the browser not to clear this site's storage under pressure, so
// unsent items aren't lost; and to send them even if the app is closed.
try { await navigator.storage?.persist?.() } catch (_) { /* not supported */ }
try { await (await navigator.serviceWorker?.ready)?.sync?.register("sam-queue") } catch (_) { /* not supported or turned off */ }
},
put: (item) => run("readwrite", (s) => s.put(item)),
remove: (id) => run("readwrite", (s) => s.delete(id)),
all: async () => ((await run("readonly", (s) => s.getAll())) || []).sort((a, b) => a.savedAt.localeCompare(b.savedAt)),
// Items this user saved (items from before tagging count as theirs).
mine: async () => (await queue.all()).filter((i) => !i.user || i.user === currentUser()),
}
export function formFields(form) {
@@ -2,8 +2,9 @@ import { Controller } from "@hotwired/stimulus"
import { t } from "i18n"
import { queue } from "controllers/offline_queue"
// On every page: sends flights logged offline once there's a connection, and
// says what happened. A rejected flight stays until it's discarded.
// On every page: sends the flights and squawks this user saved offline once
// there's a connection, says what happened, and shows the count on the app
// icon. A rejected item stays until it's discarded.
export default class extends Controller {
static targets = [ "banner" ]
@@ -21,21 +22,21 @@ export default class extends Controller {
async sync() {
let items
try { items = await queue.all() } catch (_) { return }
if (!items.length) return this.show("")
try { items = await queue.mine() } catch (_) { return }
if (!items.length) { this.badge(0); return this.show("") }
if (!navigator.onLine || this.running) return this.status(items)
this.running = true
let sent = 0
const sent = []
try {
for (const item of items.filter((i) => !i.error)) {
const result = await this.send(item)
if (result === "sent") { await queue.remove(item.id); sent++ }
if (result === "sent") { await queue.remove(item.id); sent.push(item) }
else if (result === "signin") { this.show(t("offline.sign_in")); return }
else if (result === "offline") break
else { item.error = result; await queue.put(item) }
}
} finally { this.running = false }
this.status(await queue.all(), sent)
this.status(await queue.mine(), sent)
}
async send(item) {
@@ -56,13 +57,22 @@ export default class extends Controller {
return message || t("offline.not_accepted", { status: response.status })
}
status(items, sent = 0) {
status(items, sent = []) {
const failed = items.filter((i) => i.error)
const waiting = items.length - failed.length
const waiting = items.filter((i) => !i.error)
const parts = []
if (sent) parts.push(t("offline.sent", { count: sent }))
if (waiting) parts.push(t("offline.waiting", { count: waiting }))
for (const kind of [ "flight", "squawk" ]) {
const count = (list) => list.filter((i) => (i.kind || "flight") === kind).length
if (count(sent)) parts.push(t(`offline.${kind}.sent`, { count: count(sent) }))
if (count(waiting)) parts.push(t(`offline.${kind}.waiting`, { count: count(waiting) }))
}
this.show(parts.join(" "), failed)
this.badge(items.length)
}
// The number of unsent items on the installed app's icon.
badge(count) {
try { count ? navigator.setAppBadge?.(count) : navigator.clearAppBadge?.() } catch (_) { /* not supported */ }
}
show(text, failed = []) {
@@ -72,7 +82,7 @@ export default class extends Controller {
for (const item of failed) {
const date = (item.fields.find(([ n ]) => n === "flight_log[date]") || [])[1] || ""
const row = document.createElement("p")
row.textContent = `${item.tail} flight ${date} logged offline wasn't accepted: ${item.error} `
row.textContent = `${t(`offline.${item.kind || "flight"}.rejected`, { tail: item.tail, date, error: item.error })} `
const discard = Object.assign(document.createElement("button"), { type: "button", textContent: t("offline.discard"), className: "btn-secondary btn-sm ml-1" })
discard.addEventListener("click", async () => { await queue.remove(item.id); this.sync() })
row.append(discard)
@@ -0,0 +1,21 @@
import { Controller } from "@hotwired/stimulus"
import { t, locale } from "i18n"
// Pages the service worker kept for use without a connection (an aircraft's
// overview and weight and balance, and the Log Flight / Report Squawk forms)
// say when they were saved when they're shown from that copy.
const STALE_AFTER = 5 * 60 * 1000
export default class extends Controller {
static targets = [ "banner" ]
connect() {
const rendered = Date.parse(document.querySelector("meta[name=rendered-at]")?.content || "")
const stale = rendered && Date.now() - rendered > STALE_AFTER
if (stale) {
const when = new Date(rendered).toLocaleString(locale(), { dateStyle: "medium", timeStyle: "short" })
this.bannerTarget.textContent = t("offline.saved_copy", { time: when })
}
this.bannerTarget.classList.toggle("hidden", !stale)
}
}
@@ -0,0 +1,63 @@
import { Controller } from "@hotwired/stimulus"
import { t } from "i18n"
// Profile → This device: notifications on or off for this browser or app.
export default class extends Controller {
static targets = [ "status", "on", "off", "test" ]
static values = { key: String, url: String, testUrl: String }
async connect() {
if (!("serviceWorker" in navigator) || !("PushManager" in window) || !("Notification" in window)) {
const ios = /iPad|iPhone|iPod/.test(navigator.userAgent) || (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1)
return this.show(t(ios ? "push.ios_install_first" : "push.unsupported"), null)
}
this.registration = await navigator.serviceWorker.ready
const subscription = await this.registration.pushManager.getSubscription()
if (Notification.permission === "denied") return this.show(t("push.blocked"), null)
this.show(t(subscription ? "push.on" : "push.off"), !!subscription)
}
async turnOn() {
if (await Notification.requestPermission() !== "granted") return this.show(t("push.blocked"), null)
try {
const subscription = await this.registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: this.keyBytes() })
const response = await this.request("POST", this.urlValue, { subscription: subscription.toJSON() })
if (!response.ok) throw new Error(response.status)
this.show(t("push.on"), true)
} catch (_) {
this.show(t("push.failed"), false)
}
}
async turnOff() {
const subscription = await this.registration.pushManager.getSubscription()
if (subscription) {
await this.request("DELETE", this.urlValue, { endpoint: subscription.endpoint })
await subscription.unsubscribe()
}
this.show(t("push.off"), false)
}
async sendTest() {
await this.request("POST", this.testUrlValue, {})
this.statusTarget.textContent = t("push.test_sent")
}
// on: true / false, or null when it can't be changed here.
show(text, on) {
this.statusTarget.textContent = text
this.onTarget.hidden = on !== false
this.offTarget.hidden = on !== true
this.testTarget.hidden = on !== true
}
request(method, url, body) {
return fetch(url, { method, credentials: "same-origin", body: JSON.stringify(body),
headers: { "Content-Type": "application/json", "X-CSRF-Token": document.querySelector("meta[name=csrf-token]")?.content || "" } })
}
keyBytes() {
const base64 = (this.keyValue + "=".repeat((4 - this.keyValue.length % 4) % 4)).replace(/-/g, "+").replace(/_/g, "/")
return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0))
}
}
@@ -0,0 +1,22 @@
import { Controller } from "@hotwired/stimulus"
import { t } from "i18n"
import { queue } from "controllers/offline_queue"
// Signing out clears what this device kept for working offline (forms and
// page copies with aircraft details). Unsent flights and squawks stay, tagged
// with their user, and are sent the next time that person signs in here.
export default class extends Controller {
async clean(event) {
if (this.cleaned) return
event.preventDefault()
try {
const unsent = (await queue.mine()).length
if (unsent && !confirm(t("sign_out.unsent", { count: unsent }))) return
} catch (_) { /* no IndexedDB */ }
try { await Promise.all([ "sam-forms", "sam-pages", "sam-images", "sam-flight-forms" ].map((name) => caches.delete(name))) } catch (_) { /* no Cache API */ }
try { [ "sam-offline-forms", "sam-offline-prep" ].forEach((key) => localStorage.removeItem(key)) } catch (_) { /* storage off */ }
try { navigator.clearAppBadge?.() } catch (_) { /* not supported */ }
this.cleaned = true
this.element.requestSubmit()
}
}
@@ -24,7 +24,7 @@ export default class extends Controller {
const fuel = input.dataset.fuel === "true"
const max = parseFloat(input.dataset.max) || 0
const label = input.closest("label").querySelector(".label").firstChild.textContent.trim()
if (max && qty > max) messages.push([ "bad", `${label}: ${qty} is over its maximum of ${max} ${fuel ? "gal" : "lb"}.` ])
if (max && qty > max) messages.push([ "bad", t(fuel ? "wb.over_station_gal" : "wb.over_station_lb", { label, qty, max }) ])
const lbs = fuel ? qty * this.fuelDensityValue : qty
weight += lbs
moment += lbs * arm