From 91fb5cda225a278d4c80986b50c35b4796943ce6 Mon Sep 17 00:00:00 2001 From: Graham McIntire Date: Sun, 12 Apr 2026 10:40:33 -0500 Subject: [PATCH] Delay disconnect alerts by 3s to avoid flashing on brief hiccups --- assets/js/app.ts | 35 +++++++++++++++++++++ lib/microwaveprop_web/components/layouts.ex | 4 --- 2 files changed, 35 insertions(+), 4 deletions(-) diff --git a/assets/js/app.ts b/assets/js/app.ts index 8f67c9e3..3eda2b25 100644 --- a/assets/js/app.ts +++ b/assets/js/app.ts @@ -81,6 +81,41 @@ topbar.config({barColors: {0: "#29d"}, shadowColor: "rgba(0, 0, 0, .3)"}) window.addEventListener("phx:page-loading-start", _info => topbar.show(300)) window.addEventListener("phx:page-loading-stop", _info => topbar.hide()) +// Delay disconnect alerts by 3 seconds so brief hiccups don't flash errors +let disconnectTimer: ReturnType | null = null +const DISCONNECT_DELAY_MS = 3000 + +function showDisconnectAlert(id: string) { + const el = document.getElementById(id) + if (el) el.removeAttribute("hidden") +} + +function hideDisconnectAlert(id: string) { + const el = document.getElementById(id) + if (el) el.setAttribute("hidden", "") +} + +new MutationObserver(() => { + const root = document.querySelector("[data-phx-main]") + if (!root) return + + const hasError = root.classList.contains("phx-client-error") || + root.classList.contains("phx-server-error") + + if (hasError && !disconnectTimer) { + disconnectTimer = setTimeout(() => { + const r = document.querySelector("[data-phx-main]") + if (r?.classList.contains("phx-client-error")) showDisconnectAlert("client-error") + if (r?.classList.contains("phx-server-error")) showDisconnectAlert("server-error") + }, DISCONNECT_DELAY_MS) + } else if (!hasError && disconnectTimer) { + clearTimeout(disconnectTimer) + disconnectTimer = null + hideDisconnectAlert("client-error") + hideDisconnectAlert("server-error") + } +}).observe(document.body, {subtree: true, attributes: true, attributeFilter: ["class"]}) + // connect if there are any LiveViews on the page liveSocket.connect() diff --git a/lib/microwaveprop_web/components/layouts.ex b/lib/microwaveprop_web/components/layouts.ex index 752ba687..9583e5e5 100644 --- a/lib/microwaveprop_web/components/layouts.ex +++ b/lib/microwaveprop_web/components/layouts.ex @@ -141,8 +141,6 @@ defmodule MicrowavepropWeb.Layouts do id="client-error" kind={:error} title={gettext("We can't find the internet")} - phx-disconnected={show(".phx-client-error #client-error") |> JS.remove_attribute("hidden")} - phx-connected={hide("#client-error") |> JS.set_attribute({"hidden", ""})} hidden > {gettext("Attempting to reconnect")} @@ -153,8 +151,6 @@ defmodule MicrowavepropWeb.Layouts do id="server-error" kind={:error} title={gettext("Something went wrong!")} - phx-disconnected={show(".phx-server-error #server-error") |> JS.remove_attribute("hidden")} - phx-connected={hide("#server-error") |> JS.set_attribute({"hidden", ""})} hidden > {gettext("Attempting to reconnect")}