Connection status in the top bar, as SilverBullet does

- The top bar (and the phone's status bar) turns red when the server
  can't be reached: the device is offline, or a request failed (signal
  but no internet, or the proxy answering for the app). While red it
  checks /up every 15 seconds and turns back on its own.
- A ring fills while pages are saved for offline use or flights and
  squawks logged offline are sent, with the percentage in its middle,
  and hides when done. While some wait to send, it's amber with how many.

Checked on an Android 14 emulator: airplane mode on and off, saving for
offline, and a flight logged offline then sent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rickyandClaude Opus 5.5 committed 2026-11-15 13:15:50 -05:00
1 parent 66fa5f4423
commit d9de1be562
7 files changed
+220 -13

No files matched your search

@@ -0,0 +1,112 @@
import { Controller } from "@hotwired/stimulus"
import { t } from "i18n"
// The top bar shows the connection at a glance (as SilverBullet does):
// - it turns red when the server can't be reached: the device is offline, or
// a request failed (signal but no internet, or the proxy answering for the
// app). While red it checks /up every so often and turns back on its own;
// - a ring fills while pages are being saved for offline use or flights and
// squawks logged offline are being sent, with the percentage in its middle;
// - while some are waiting to send, the ring is amber with how many.
// Others report with events on document:
// sam:progress { source, done, total } (done >= total when finished)
// sam:waiting { count }
// sam:unreachable / sam:reachable
// The header is replaced on every page, so the state and the listeners live
// in this module and the header on the page just shows them.
const RETRY_EVERY = 15 * 1000
const UNREACHABLE = [ 502, 503, 504 ]
const OFFLINE_COLOR = "#b91c1c" // red-700, for the phone's status bar
const state = { online: navigator.onLine, progress: {}, waiting: 0 }
let header = null // the controller on the page
let checking = null
let timer = null
let normalColor = null
// Any answer from the app (even a sign-in redirect) means it's reachable.
async function check() {
checking ||= fetch("/up", { cache: "no-store", redirect: "manual", credentials: "same-origin" })
.then((response) => !UNREACHABLE.includes(response.status), () => false)
.finally(() => { checking = null })
setOnline(await checking)
}
function setOnline(online) {
clearTimeout(timer)
if (!online) timer = setTimeout(check, RETRY_EVERY)
if (state.online === online) return
state.online = online
header?.announce(online ? t("connection.back_online") : t("connection.offline"))
update()
}
// Several reports often arrive together (done sending, then none waiting):
// show them once, on the next frame, so the ring doesn't flicker between.
let frame = null
function update() {
frame ||= requestAnimationFrame(() => { frame = null; header?.render() })
}
window.addEventListener("online", check)
window.addEventListener("offline", () => setOnline(false))
document.addEventListener("visibilitychange", () => { if (document.visibilityState === "visible" && !state.online) check() })
document.addEventListener("sam:unreachable", () => setOnline(false))
document.addEventListener("turbo:fetch-request-error", () => setOnline(false))
document.addEventListener("sam:reachable", () => setOnline(true))
document.addEventListener("sam:progress", ({ detail }) => { state.progress[detail.source] = detail; update() })
document.addEventListener("sam:waiting", ({ detail }) => { state.waiting = detail.count; update() })
export default class extends Controller {
static targets = [ "ring", "label", "announce" ]
connect() {
header = this
this.themeColor = document.querySelector("meta[name=theme-color]")
normalColor ||= this.themeColor?.content
if (!navigator.onLine) setOnline(false)
else if (!state.online || this.fromSavedCopy()) check() // a fresh page, or maybe the offline copy
this.render()
}
disconnect() {
if (header === this) header = null
}
fromSavedCopy() {
const rendered = Date.parse(document.querySelector("meta[name=rendered-at]")?.content || "")
return rendered && Date.now() - rendered > 60 * 1000
}
announce(text) {
if (this.hasAnnounceTarget) this.announceTarget.textContent = text
}
render() {
this.element.classList.toggle("is-offline", !state.online)
this.element.title = state.online ? "" : t("connection.offline")
if (this.themeColor && normalColor) this.themeColor.content = state.online ? normalColor : OFFLINE_COLOR
const busy = Object.values(state.progress).filter((p) => p.total && p.done < p.total)
if (busy.length) {
const done = busy.reduce((sum, p) => sum + p.done, 0)
const total = busy.reduce((sum, p) => sum + p.total, 0)
const percent = Math.floor((done / total) * 100)
const what = busy.some((p) => p.source === "send") ? "sending" : "saving"
this.showRing({ percent, number: percent, waiting: false, text: t(`connection.${what}`, { percent }) })
} else if (state.waiting) {
this.showRing({ percent: 100, number: state.waiting, waiting: true, text: t("connection.waiting", { count: state.waiting }) })
} else {
this.ringTarget.hidden = true
}
}
showRing({ percent, number, waiting, text }) {
const ring = this.ringTarget
ring.hidden = false
ring.classList.toggle("is-waiting", waiting)
ring.style.setProperty("--progress", `${percent}%`)
ring.title = text
ring.setAttribute("aria-label", text)
this.labelTarget.textContent = number
}
}
@@ -8,6 +8,9 @@ import { currentUser } from "controllers/offline_queue"
// your aircraft change. Signing out clears it.
const EVERY = 60 * 60 * 1000
// How far along it is, for the ring in the top bar (connection_controller.js).
const progress = (done, total) => document.dispatchEvent(new CustomEvent("sam:progress", { detail: { source: "prep", done, total } }))
export default class extends Controller {
static values = { aircraft: Array }
@@ -30,13 +33,22 @@ export default class extends Controller {
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.flatMap((a) => a.pictures || []))
const pictures = this.aircraftValue.flatMap((a) => a.pictures || [])
const total = paths.length + 1
try {
for (const [ index, path ] of paths.entries()) {
progress(index, total)
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 (_) {
document.dispatchEvent(new CustomEvent("sam:unreachable"))
return
}
}
progress(paths.length, total)
await this.savePictures(pictures)
} finally { progress(total, total) }
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() }))
@@ -2,6 +2,8 @@ import { Controller } from "@hotwired/stimulus"
import { t } from "i18n"
import { queue } from "controllers/offline_queue"
const report = (name, detail) => document.dispatchEvent(new CustomEvent(name, { detail }))
// 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.
@@ -23,19 +25,24 @@ export default class extends Controller {
async sync() {
let items
try { items = await queue.mine() } catch (_) { return }
if (!items.length) { this.badge(0); return this.show("") }
if (!items.length) { this.badge(0); report("sam:waiting", { count: 0 }); return this.show("") }
if (!navigator.onLine || this.running) return this.status(items)
this.running = true
const sent = []
const sending = items.filter((i) => !i.error)
try {
for (const item of items.filter((i) => !i.error)) {
for (const [ index, item ] of sending.entries()) {
report("sam:progress", { source: "send", done: index, total: sending.length })
const result = await this.send(item)
if (result === "sent") { await queue.remove(item.id); sent.push(item) }
if (result === "sent") { await queue.remove(item.id); sent.push(item); report("sam:reachable") }
else if (result === "signin") { this.show(t("offline.sign_in")); return }
else if (result === "offline") break
else if (result === "offline") { report("sam:unreachable"); break }
else { item.error = result; await queue.put(item) }
}
} finally { this.running = false }
} finally {
this.running = false
report("sam:progress", { source: "send", done: 0, total: 0 })
}
this.status(await queue.mine(), sent)
}
@@ -68,6 +75,7 @@ export default class extends Controller {
}
this.show(parts.join(" "), failed)
this.badge(items.length)
report("sam:waiting", { count: waiting.length })
}
// The number of unsent items on the installed app's icon.