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. 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.mine() } catch (_) { return } 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 [ 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 { response = await fetch(item.url, { method: "POST", body, credentials: "same-origin", headers: { Accept: "text/html" } }) } 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) } }