diff --git a/app/assets/tailwind/application.css b/app/assets/tailwind/application.css index 377d2b2..a59fc06 100644 --- a/app/assets/tailwind/application.css +++ b/app/assets/tailwind/application.css @@ -5,6 +5,7 @@ --color-page: oklch(96.8% 0.007 247.896); /* slate-100 */ --color-surface: oklch(100% 0 0); /* white: cards, inputs, menus */ --color-header: oklch(20.8% 0.042 265.755); /* slate-900: top bar, dark in both themes */ + --color-header-offline: oklch(50.5% 0.213 27.518); /* red-700: top bar when the server can't be reached */ --color-accent: oklch(50% 0.134 242.749); /* sky-700: primary buttons */ --color-accent-hover: oklch(44.3% 0.11 240.79); /* sky-800 */ } @@ -62,6 +63,7 @@ --color-page: oklch(15.5% 0.035 264); --color-surface: oklch(20.8% 0.042 265.755); --color-header: oklch(12.9% 0.042 264.695); + --color-header-offline: oklch(44.4% 0.177 26.899); /* red-800 */ --color-accent: oklch(50% 0.134 242.749); /* same blue: white text stays ≥ 4.5:1 */ --color-accent-hover: oklch(54% 0.15 242); @@ -190,3 +192,32 @@ @apply grid grid-cols-[6.5rem_minmax(0,1fr)] items-baseline gap-x-3; & > dt { @apply text-slate-500; } } + +/* The top bar's connection status (connection_controller.js, after + SilverBullet): red when the server can't be reached, and a ring that fills + with the percentage in its hole while saving for offline or sending. Amber + and full while flights or squawks wait to send, with how many. */ +header.is-offline { --color-header: var(--color-header-offline); } +.sync-ring { + position: relative; + display: inline-block; + flex: none; + width: 24px; + height: 24px; + border-radius: 9999px; + background: conic-gradient(var(--ring-color, white) var(--progress, 0%), rgb(255 255 255 / 0.25) 0); +} +.sync-ring[hidden] { display: none; } +.sync-ring.is-waiting { --ring-color: oklch(87.9% 0.169 91.605); } /* amber-300 */ +.sync-ring > span { + position: absolute; + inset: 2.5px; + display: flex; + align-items: center; + justify-content: center; + border-radius: 9999px; + background-color: var(--color-header); + font-size: 9px; + font-variant-numeric: tabular-nums; + line-height: 1; +} diff --git a/app/javascript/controllers/connection_controller.js b/app/javascript/controllers/connection_controller.js new file mode 100644 index 0000000..d63e11e --- /dev/null +++ b/app/javascript/controllers/connection_controller.js @@ -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 + } +} diff --git a/app/javascript/controllers/offline_prep_controller.js b/app/javascript/controllers/offline_prep_controller.js index fc4e419..5c889ba 100644 --- a/app/javascript/controllers/offline_prep_controller.js +++ b/app/javascript/controllers/offline_prep_controller.js @@ -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() })) diff --git a/app/javascript/controllers/offline_sync_controller.js b/app/javascript/controllers/offline_sync_controller.js index f629cba..fff8b53 100644 --- a/app/javascript/controllers/offline_sync_controller.js +++ b/app/javascript/controllers/offline_sync_controller.js @@ -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. diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb index fbcdd9e..9adbef2 100644 --- a/app/views/layouts/application.html.erb +++ b/app/views/layouts/application.html.erb @@ -27,11 +27,15 @@ "<% if current_user %> data-offline-prep-aircraft-value="<%= offline_pages.to_json %>"<% end %>> <%= t(".skip_to_content_html") %> <%# Solid and stuck to the top: iOS 26 home-screen apps then extend its color under the status bar instead of blurring it. %> -
+ <%# Red when the server can't be reached; the ring shows saving for offline and sending (connection_controller.js). %> +
<%= link_to root_path, class: "flex items-center gap-2 font-semibold tracking-tight whitespace-nowrap" do %> ✈ "><%= t(".sam") %> <% end %> +
+ + <% if current_user %> <%# Phones: Fleet, theme and one menu for the rest. %> <% end %> +
diff --git a/config/locales/en.yml b/config/locales/en.yml index 48a083d..cdc79cb 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -3924,6 +3924,14 @@ en: not_entries: 'Not logbook entries (forms, tags…), so nothing was transcribed from: %{pages}.' unreadable: 'Too hard to read: %{pages}.' js: + connection: + offline: "Offline: can't reach the server. Pages saved for offline use still work." + back_online: Back online. + saving: "Saving for offline use: %{percent}%" + sending: "Sending what was logged offline: %{percent}%" + waiting: + one: "%{count} logged offline, waiting to send" + other: "%{count} logged offline, waiting to send" pdf: loading: Loading the PDF… page: Page %{page} of %{pages} diff --git a/test/integration/connection_status_test.rb b/test/integration/connection_status_test.rb new file mode 100644 index 0000000..5b98134 --- /dev/null +++ b/test/integration/connection_status_test.rb @@ -0,0 +1,31 @@ +require "test_helper" + +# The top bar turns red when the server can't be reached and has a ring for +# saving for offline / sending (connection_controller.js); here, its markup, +# styles and strings. +class ConnectionStatusTest < ActionDispatch::IntegrationTest + test "the top bar carries the connection status, hidden ring and announcer" do + sign_in create_user + get root_path + assert_select "header[data-controller=connection]" do + assert_select ".sync-ring[hidden][role=img][data-connection-target=ring] [data-connection-target=label]" + assert_select "[role=status][data-connection-target=announce]" + end + strings = JSON.parse(css_select("script#i18n").first.text) + assert_equal %w[back_online offline saving sending waiting], strings["connection"].keys.sort + assert_match "%{percent}", strings["connection"]["saving"] + end + + test "signed out pages have it too, for the sign-in page offline" do + create_user + get new_session_path + assert_response :success + assert_select "header[data-controller=connection] .sync-ring[hidden]" + end + + test "the red top bar and the ring are styled" do + css = Rails.root.join("app/assets/tailwind/application.css").read + assert_match(/header\.is-offline \{ --color-header: var\(--color-header-offline\); \}/, css) + assert_match "conic-gradient", css + end +end