Files
rickyandClaude Opus 5.5 e4bc3a5b7b Weak signal counts as no signal
With a signal so weak requests hang, the phone still says it's online, so
nothing fell back: Log Flight waited minutes with no feedback, and pages
never reached the offline page.

- Log Flight and Report Squawk say "Sending…" and, after 10 seconds
  without an answer (60 with photos), keep the entry on the device as
  with no signal. When the top bar is already red they keep it right
  away. If it got through after all, the copy sent later is dropped
  (same client_key).
- What's kept on the device isn't sent while the top bar is red, gives
  up after 15 seconds, and goes again as soon as the server answers.
- Every page of the app falls back to its kept copy or the offline page:
  after 10 seconds, then 3 while requests keep failing, and at once right
  after a failure. Downloads made while you wait (.sam.zip, records
  package, PDFs) have no time limit.

Checked on an Android 14 emulator with a connection that accepts
requests and never answers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:34:13 -05:00

114 lines
5.1 KiB
JavaScript

import { Controller } from "@hotwired/stimulus"
import { t } from "i18n"
import { queue } from "controllers/offline_queue"
import { serverReachable } from "controllers/connection_controller"
// How long to wait for the server to take one before trying again later
// (a weak signal can leave a request hanging for minutes). Photos take longer.
const WAIT = 15 * 1000
const WAIT_WITH_FILES = 60 * 1000
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. Nothing is tried while
// the top bar is red; it goes again as soon as it turns back
// (connection_controller.js), signal or not.
export default class extends Controller {
static targets = [ "banner" ]
connect() {
this.sync = this.sync.bind(this)
window.addEventListener("online", this.sync)
document.addEventListener("offline-queue:changed", this.sync)
document.addEventListener("sam:back-online", this.sync)
this.sync()
}
disconnect() {
window.removeEventListener("online", this.sync)
document.removeEventListener("offline-queue:changed", this.sync)
document.removeEventListener("sam:back-online", this.sync)
}
async sync() {
let items
try { items = await queue.mine() } catch (_) { return }
if (!items.length) { this.badge(0); report("sam:waiting", { count: 0 }); return this.show("") }
if (!navigator.onLine || !serverReachable() || this.running) return this.status(items)
this.running = true
const sent = []
const sending = items.filter((i) => !i.error)
try {
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); report("sam:reachable") }
else if (result === "signin") { this.show(t("offline.sign_in")); return }
else if (result === "offline") { report("sam:unreachable"); break }
else { item.error = result; await queue.put(item) }
}
} finally {
this.running = false
report("sam:progress", { source: "send", done: 0, total: 0 })
}
this.status(await queue.mine(), sent)
}
async send(item) {
const body = new FormData()
for (const [ name, value ] of item.fields) body.append(name, value)
const token = document.querySelector("meta[name=csrf-token]")?.content
if (token) body.append("authenticity_token", token)
let response
try {
const files = item.fields.some(([ , value ]) => value instanceof Blob)
response = await fetch(item.url, { method: "POST", body, credentials: "same-origin", headers: { Accept: "text/html" },
signal: AbortSignal.timeout(files ? WAIT_WITH_FILES : WAIT) })
} catch (_) { return "offline" }
if ([ 502, 503, 504 ].includes(response.status)) return "offline"
if (response.url.includes("/session/new")) return "signin"
if (response.ok) return "sent"
const html = await response.text()
const doc = new DOMParser().parseFromString(html, "text/html")
const message = [ ...doc.querySelectorAll("[role=alert], .field-error") ].map((e) => e.textContent.trim()).filter(Boolean).join(" ")
return message || t("offline.not_accepted", { status: response.status })
}
status(items, sent = []) {
const failed = items.filter((i) => i.error)
const waiting = items.filter((i) => !i.error)
const parts = []
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)
report("sam:waiting", { count: waiting.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 = []) {
const banner = this.bannerTarget
banner.replaceChildren()
if (text) banner.append(Object.assign(document.createElement("p"), { textContent: text }))
for (const item of failed) {
const date = (item.fields.find(([ n ]) => n === "flight_log[date]") || [])[1] || ""
const row = document.createElement("p")
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)
banner.append(row)
}
banner.classList.toggle("hidden", !text && !failed.length)
}
}