The personal finance app for everyone (by everyone)
Ruby
Keep the rule prompt visible after the transaction drawer closes (#4210)
GFR7b7013ab8dcc
diff --git a/app/javascript/controllers/notification_tray_controller.js b/app/javascript/controllers/notification_tray_controller.jsindex 2f0cf5a06b..906ffb4efc 100644--- a/app/javascript/controllers/notification_tray_controller.js+++ b/app/javascript/controllers/notification_tray_controller.js@@ -14,10 +14,26 @@ export default class extends Controller {this.resizeObserver = new ResizeObserver(() => this.reposition());this.resizeObserver.observe(this.mainTarget);this.reposition();++ this._deferredStreams = [];+ this._onBeforeStreamRender = this.#deferWhileDialogOpen.bind(this);+ this._onDialogClose = this.#onDialogClose.bind(this);+ document.addEventListener(+ "turbo:before-stream-render",+ this._onBeforeStreamRender,+ );+ // `close` doesn't bubble; a capturing listener still sees every dialog's.+ document.addEventListener("close", this._onDialogClose, true);}disconnect() {this.resizeObserver?.disconnect();+ document.removeEventListener(+ "turbo:before-stream-render",+ this._onBeforeStreamRender,+ );+ document.removeEventListener("close", this._onDialogClose, true);+ this._dialogRemovalObserver?.disconnect();}reposition() {@@ -37,4 +53,87 @@ export default class extends Controller {preserveStyle(event) {if (event.detail.attributeName === "style") event.preventDefault();}++ // A native <dialog> shown via showModal() (the transaction drawer, any+ // modal) renders in the browser's top layer, which sits above this tray+ // regardless of z-index. A "create a rule?" CTA streaming in while one is+ // open is invisible and unclickable until the dialog closes, and by then+ // its one-time flash has already been consumed server-side, so it never+ // gets a second chance to render. Hold the stream's render until no dialog+ // is open any more.+ //+ // Separately, some background jobs (e.g. Account::SyncCompleteEvent)+ // broadcast a raw <turbo-stream action="refresh"> with no target: a+ // full-page morph that bypasses the sync-toast controller's own+ // dialog/CTA-aware deferral entirely, since Turbo handles "refresh"+ // itself rather than routing it through that Stimulus controller. Left+ // alone, one of these can silently wipe an unread CTA a moment after it+ // was revealed. Hold those the same way, and skip them while a CTA is+ // waiting for the user.+ #deferWhileDialogOpen(event) {+ const stream = event.target;+ const isCta = stream.target === "cta";+ const isRefresh = stream.action === "refresh";+ if (!isCta && !isRefresh) return;++ if (!this.#dialogOpen()) {+ if (isRefresh && this.#ctaPending()) event.detail.render = () => {};+ return;+ }++ const render = event.detail.render;+ event.detail.render = (streamElement) => {+ this._deferredStreams.push({ isRefresh, render, streamElement });+ // Turbo calls this after waiting for the next paint; the dialog may+ // have closed in between, with no close event left to release it.+ this.#flushIfNoDialogOpen();+ if (this._deferredStreams.length > 0) this.#watchForDialogRemoval();+ };+ }++ // Captured on the document rather than bound to the dialog that was open+ // when the stream arrived, so stacked dialogs and a drawer replaced by the+ // next one are both covered. A dialog can also leave the DOM without any+ // close event (a frame replaced by a stream, one drawer swapped for the+ // next), which the mutation observer catches while streams are waiting.+ #onDialogClose(event) {+ if (event.target instanceof HTMLDialogElement) this.#flushIfNoDialogOpen();+ }++ #watchForDialogRemoval() {+ this._dialogRemovalObserver ??= new MutationObserver(() =>+ this.#flushIfNoDialogOpen(),+ );+ // `open` too: a dialog closed by dropping the attribute fires no close event.+ this._dialogRemovalObserver.observe(document.body, {+ childList: true,+ subtree: true,+ attributes: true,+ attributeFilter: ["open"],+ });+ }++ #flushIfNoDialogOpen() {+ if (this._deferredStreams.length === 0 || this.#dialogOpen()) return;++ this._dialogRemovalObserver?.disconnect();+ const streams = this._deferredStreams;+ this._deferredStreams = [];++ // CTAs first: a refresh morphs the page to the server's HTML, where the+ // already-consumed CTA no longer exists.+ for (const { isRefresh, render, streamElement } of streams) {+ if (!isRefresh) render(streamElement);+ }+ const refresh = streams.find(({ isRefresh }) => isRefresh);+ if (refresh && !this.#ctaPending()) refresh.render(refresh.streamElement);+ }++ #dialogOpen() {+ return !!document.querySelector("dialog[open]");+ }++ #ctaPending() {+ return !!document.getElementById("cta")?.firstElementChild;+ }}diff --git a/app/javascript/controllers/sync_toast_controller.js b/app/javascript/controllers/sync_toast_controller.jsindex 20cfc4c9e1..f7af867774 100644--- a/app/javascript/controllers/sync_toast_controller.js+++ b/app/javascript/controllers/sync_toast_controller.js@@ -37,15 +37,18 @@ export default class extends Controller {}#arm() {- if (this.#userIsInteracting()) return; // mid-form: wait for a manual refresh+ if (this.#userIsInteracting() || this.#ctaPending()) return; // mid-form / unread CTA: wait for a manual refresh// Re-check at fire time, not just arm time: the post-dialog reveal often// lands on a form the dialog was sitting on, and the user resumes typing// inside this window (a morph would wipe their non-turbo-permanent// input). A dialog opened during the window is the same hazard — the- // refresh would close it. Either way, bail and leave the toast visible- // for a manual refresh, matching the mid-form behavior.+ // refresh would close it. A "create a rule?" CTA revealed by the same+ // dialog close is a third: it's un-acknowledged, server-flash-backed+ // content a morph would silently discard before the user could act on+ // it. Either way, bail and leave the toast visible for a manual refresh.this._timer = setTimeout(() => {- if (this.#userIsInteracting() || this.#dialogOpen()) return;+ if (this.#userIsInteracting() || this.#dialogOpen() || this.#ctaPending())+ return;this.refresh();}, this.autoRefreshDelayValue);}@@ -103,6 +106,10 @@ export default class extends Controller {return !!document.querySelector("dialog[open]");}+ #ctaPending() {+ return !!document.getElementById("cta")?.firstElementChild;+ }+#userIsInteracting() {const el = document.activeElement;if (!el || el === document.body || el === document.documentElement)diff --git a/test/system/category_rule_prompt_test.rb b/test/system/category_rule_prompt_test.rbindex af0be20a33..d8dfa25bbd 100644--- a/test/system/category_rule_prompt_test.rb+++ b/test/system/category_rule_prompt_test.rb@@ -64,7 +64,77 @@ class CategoryRulePromptTest < ApplicationSystemTestCaseassert_no_text "Updated to #{@categories.second.name}"end+ test "a prompt from the transaction drawer waits until the drawer closes" do+ visit transactions_url+ open_drawer @entry+ assign_category_in_drawer @categories.first++ # The drawer sits in the browser's top layer: a prompt rendered now would be hidden behind it.+ assert_no_selector "#cta *", visible: :all++ close_drawer+ assert_selector "#cta", text: "Updated to #{@categories.first.name}"+ end++ test "a held prompt survives the drawer being replaced by another one" do+ other_entry = @user.family.entries.transactions.where.not(id: @entry.id).order(date: :desc).first++ visit transactions_url+ open_drawer @entry+ assign_category_in_drawer @categories.first++ # Swapping the drawer's content removes the open dialog without a close event.+ open_drawer other_entry+ assert_no_selector "#cta *", visible: :all++ close_drawer+ assert_selector "#cta", text: "Updated to #{@categories.first.name}"+ end++ test "a held prompt shows when the open dialog is removed without closing" do+ visit transactions_url+ open_drawer @entry+ assign_category_in_drawer @categories.first+ assert_no_selector "#cta *", visible: :all++ # Like a stream replacing the modal frame with an empty one: no close event fires.+ page.execute_script(%(document.querySelector("turbo-frame#drawer").replaceChildren()))++ assert_selector "#cta", text: "Updated to #{@categories.first.name}"+ end++ test "a held prompt shows when the open attribute is removed from the dialog" do+ visit transactions_url+ open_drawer @entry+ assign_category_in_drawer @categories.first+ assert_no_selector "#cta *", visible: :all++ page.execute_script(%(document.querySelector("turbo-frame#drawer dialog[open]").removeAttribute("open")))++ assert_selector "#cta", text: "Updated to #{@categories.first.name}"+ end+private+ def open_drawer(entry)+ page.execute_script <<~JS+ document.querySelector("turbo-frame#drawer").src = "#{transaction_url(entry)}"+ JS+ assert_selector "turbo-frame#drawer dialog[open] ##{dom_id(entry, :header)}"+ end++ def assign_category_in_drawer(category)+ within "turbo-frame#drawer [data-controller='category-select']" do+ find("button", match: :first).click+ find("button[data-category-id='#{category.id}']").click+ end+ assert_selector "##{dom_id(@entry)}", text: category.name+ end++ def close_drawer+ find("turbo-frame#drawer dialog[open]").send_keys(:escape)+ assert_no_selector "turbo-frame#drawer dialog[open]"+ end+def assign_category(category)within "##{dom_id(@entry.entryable, 'category_menu_desktop')}" dofind("button", match: :first).click