From 6ceb5ef7c32ef1c42d22b89048b32425fa22a725 Mon Sep 17 00:00:00 2001 From: Jay Ohms Date: Wed, 25 Feb 2026 15:32:00 -0500 Subject: [PATCH] Notify the form/buttons components of a disconnect before a page reload. This gives the native components an opportunity to reset their state before the fresh page loads. --- .../controllers/bridge/buttons_controller.js | 16 ++++++++++++++++ .../controllers/bridge/form_controller.js | 16 ++++++++++++++-- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/app/javascript/controllers/bridge/buttons_controller.js b/app/javascript/controllers/bridge/buttons_controller.js index 47d09a158..7cbf73501 100644 --- a/app/javascript/controllers/bridge/buttons_controller.js +++ b/app/javascript/controllers/bridge/buttons_controller.js @@ -5,6 +5,14 @@ export default class extends BridgeComponent { static component = "buttons" static targets = [ "button" ] + connect() { + window.addEventListener("beforeunload", this.handleBeforeUnload.bind(this)) + } + + disconnect() { + window.removeEventListener("beforeunload", this.handleBeforeUnload.bind(this)) + } + buttonTargetConnected() { this.notifyBridgeOfConnect() } @@ -27,6 +35,14 @@ export default class extends BridgeComponent { }) } + notifyBridgeOfDisconnect() { + this.send("disconnect") + } + + handleBeforeUnload() { + this.notifyBridgeOfDisconnect() + } + #clickButton(message) { const selectedIndex = message.data.selectedIndex this.#enabledButtonTargets[selectedIndex].click() diff --git a/app/javascript/controllers/bridge/form_controller.js b/app/javascript/controllers/bridge/form_controller.js index a3c780e62..e2d3f929c 100644 --- a/app/javascript/controllers/bridge/form_controller.js +++ b/app/javascript/controllers/bridge/form_controller.js @@ -6,13 +6,21 @@ export default class extends BridgeComponent { static targets = [ "submit", "cancel" ] static values = { submitTitle: String } + connect() { + window.addEventListener("beforeunload", this.handleBeforeUnload.bind(this)) + } + + disconnect() { + window.removeEventListener("beforeunload", this.handleBeforeUnload.bind(this)) + } + submitTargetConnected() { this.notifyBridgeOfConnect() this.#observeSubmitTarget() } submitTargetDisconnected() { - this.notifyBridgeOfDisonnect() + this.notifyBridgeOfDisconnect() this.submitObserver?.disconnect() } @@ -37,7 +45,7 @@ export default class extends BridgeComponent { } } - notifyBridgeOfDisonnect() { + notifyBridgeOfDisconnect() { this.send("disconnect") } @@ -49,6 +57,10 @@ export default class extends BridgeComponent { this.send("submitEnd") } + handleBeforeUnload() { + this.notifyBridgeOfDisconnect() + } + #observeSubmitTarget() { this.submitObserver = new MutationObserver(() => { this.send(this.submitTarget.disabled ? "submitDisabled" : "submitEnabled")