mirror of
https://github.com/rickbarrette/simple-aircraft-manager-rails.git
synced 2026-11-17 15:50:36 -05:00
Log flights offline: the form is kept by the service worker, flights queue on the device (IndexedDB) and send when back online; one-time keys prevent duplicates
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
08ba017c7e
commit
191eb030e8
14 files changed
+314
-14
No files matched your search
@@ -0,0 +1,84 @@
|
||||
import { Controller } from "@hotwired/stimulus"
|
||||
import { queue, formFields, newKey } 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.
|
||||
export default class extends Controller {
|
||||
static targets = [ "key", "notice" ]
|
||||
static values = { 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)
|
||||
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.`)
|
||||
}
|
||||
} catch (_) { /* no IndexedDB: nothing queued */ }
|
||||
this.rememberForm()
|
||||
}
|
||||
|
||||
// No connection: keep it here instead of submitting.
|
||||
async submit(event) {
|
||||
if (navigator.onLine) return
|
||||
event.preventDefault()
|
||||
event.stopImmediatePropagation()
|
||||
await this.save(formFields(this.element))
|
||||
}
|
||||
|
||||
// Kept in case the request fails on the way (no signal but the browser thinks it's online).
|
||||
remember() { this.pending = formFields(this.element) }
|
||||
|
||||
async networkFailed() {
|
||||
if (this.pending) await this.save(this.pending)
|
||||
}
|
||||
|
||||
async save(fields) {
|
||||
const item = { id: this.keyTarget.value, url: this.element.action, tail: this.tailValue, savedAt: new Date().toISOString(), fields }
|
||||
try {
|
||||
await queue.add(item)
|
||||
} catch (_) {
|
||||
this.say("No connection, and this browser can't store the flight. Write it down and log it when you're back online.")
|
||||
return
|
||||
}
|
||||
this.prefillFrom(item)
|
||||
this.clearLegFields()
|
||||
this.keyTarget.value = newKey()
|
||||
this.pending = null
|
||||
window.scrollTo({ top: 0 })
|
||||
this.say("No connection: flight saved on this device. It's sent automatically when you're back online. Log the next leg below, or close the app.")
|
||||
document.dispatchEvent(new CustomEvent("offline-queue:changed"))
|
||||
}
|
||||
|
||||
prefillFrom(item) {
|
||||
const value = (name) => (item.fields.find(([ n ]) => n === `flight_log[${name}]`) || [])[1]
|
||||
const set = (name, v) => { const el = this.element.querySelector(`[name="flight_log[${name}]"]`); if (el && v) el.value = v }
|
||||
set("tach_out", value("tach_in"))
|
||||
set("hobbs_out", value("hobbs_in"))
|
||||
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}]"]`)
|
||||
if (el) el.value = ""
|
||||
}
|
||||
}
|
||||
|
||||
// Lets the offline page offer this form for this aircraft.
|
||||
rememberForm() {
|
||||
try {
|
||||
const forms = JSON.parse(localStorage.getItem("sam-offline-forms") || "{}")
|
||||
forms[location.pathname] = this.tailValue
|
||||
localStorage.setItem("sam-offline-forms", JSON.stringify(forms))
|
||||
} catch (_) { /* storage off */ }
|
||||
}
|
||||
|
||||
say(text) {
|
||||
this.noticeTarget.textContent = text
|
||||
this.noticeTarget.classList.remove("hidden")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
// Flights logged without a connection, kept in this browser (IndexedDB, so
|
||||
// attached track and engine files are kept too) until they can be sent.
|
||||
const DB = "sam-offline"
|
||||
const STORE = "flights"
|
||||
|
||||
function open() {
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = indexedDB.open(DB, 1)
|
||||
req.onupgradeneeded = () => req.result.createObjectStore(STORE, { keyPath: "id" })
|
||||
req.onsuccess = () => resolve(req.result)
|
||||
req.onerror = () => reject(req.error)
|
||||
})
|
||||
}
|
||||
|
||||
async function run(mode, fn) {
|
||||
const db = await open()
|
||||
return new Promise((resolve, reject) => {
|
||||
const tx = db.transaction(STORE, mode)
|
||||
const result = fn(tx.objectStore(STORE))
|
||||
tx.oncomplete = () => resolve(result && "result" in result ? result.result : undefined)
|
||||
tx.onerror = () => reject(tx.error)
|
||||
})
|
||||
}
|
||||
|
||||
// item: { id, url, tail, savedAt, fields: [[name, value]], error }
|
||||
export const queue = {
|
||||
add: (item) => run("readwrite", (s) => s.put(item)),
|
||||
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)),
|
||||
}
|
||||
|
||||
export function formFields(form) {
|
||||
return [ ...new FormData(form).entries() ].filter(([ name, value ]) => !(value instanceof File && value.size === 0) && name !== "authenticity_token")
|
||||
}
|
||||
|
||||
export function newKey() {
|
||||
return (crypto.randomUUID && crypto.randomUUID()) || `${Date.now()}-${Math.random().toString(36).slice(2)}`
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { Controller } from "@hotwired/stimulus"
|
||||
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.
|
||||
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)
|
||||
this.sync()
|
||||
}
|
||||
|
||||
disconnect() {
|
||||
window.removeEventListener("online", this.sync)
|
||||
document.removeEventListener("offline-queue:changed", this.sync)
|
||||
}
|
||||
|
||||
async sync() {
|
||||
let items
|
||||
try { items = await queue.all() } catch (_) { return }
|
||||
if (!items.length) return this.show("")
|
||||
if (!navigator.onLine || this.running) return this.status(items)
|
||||
this.running = true
|
||||
let sent = 0
|
||||
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++ }
|
||||
else if (result === "signin") { this.show("Sign in to send the flights logged offline."); return }
|
||||
else if (result === "offline") break
|
||||
else { item.error = result; await queue.put(item) }
|
||||
}
|
||||
} finally { this.running = false }
|
||||
this.status(await queue.all(), 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 {
|
||||
response = await fetch(item.url, { method: "POST", body, credentials: "same-origin", headers: { Accept: "text/html" } })
|
||||
} catch (_) { 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 || `Not accepted (${response.status}).`
|
||||
}
|
||||
|
||||
status(items, sent = 0) {
|
||||
const failed = items.filter((i) => i.error)
|
||||
const waiting = items.length - failed.length
|
||||
const parts = []
|
||||
if (sent) parts.push(`Sent ${sent} flight${sent > 1 ? "s" : ""} logged offline.`)
|
||||
if (waiting) parts.push(`${waiting} flight${waiting > 1 ? "s" : ""} logged offline waiting for a connection.`)
|
||||
this.show(parts.join(" "), failed)
|
||||
}
|
||||
|
||||
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 = `${item.tail} flight ${date} logged offline wasn't accepted: ${item.error} `
|
||||
const discard = Object.assign(document.createElement("button"), { type: "button", textContent: "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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user