Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
5.0 KB
Raw Blame
import { Controller } from "@hotwired/stimulus";

// Connects to data-controller="sync-toast"
//
// Shown when a background sync completes and the family's data has changed.
// - Idle              → morph-refreshes the page after a short delay.
// - Mid-form          → stays put; the user refreshes when ready.
// - A modal <dialog> is open → the toast is deferred (it would otherwise sit
//   dimmed-but-clickable behind the dialog's top-layer backdrop, and a refresh
//   would close the dialog and discard its in-progress input). It is revealed
//   once the dialog closes — the first moment a refresh is actually safe.
export default class extends Controller {
  static values = {
    autoRefreshDelay: { type: Number, default: 500 },
  };

  connect() {
    // A page fetch after the toast (e.g. the account page's refresh stream) already re-renders
    // the page. Frame, form and prefetch fetches target their own element, so they don't count.
    this._onFetch = (event) => {
      const headers = event.detail.fetchOptions?.headers || {};
      if (event.target === document.documentElement && !headers["Turbo-Frame"])
        clearTimeout(this._timer);
    };
    document.addEventListener("turbo:before-fetch-request", this._onFetch);

    if (this.#dialogOpen()) {
      this.#deferUntilDialogCloses();
      return;
    }
    this.#arm();
  }

  disconnect() {
    clearTimeout(this._timer);
    document.removeEventListener("turbo:before-fetch-request", this._onFetch);
    this.#removeDeferredDialogListener();
  }

  // Turbo 8 morph refresh (the app sets `turbo_refreshes_with method: :morph,
  // scroll: :preserve`) instead of window.location.reload(): no white flash,
  // scroll position and `data-turbo-permanent` elements (the AI chat panel)
  // are preserved.
  refresh() {
    clearTimeout(this._timer);
    Turbo.visit(window.location.href, { action: "replace" });
  }

  #arm() {
    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. 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() || this.#ctaPending())
        return;
      this.refresh();
    }, this.autoRefreshDelayValue);
  }

  #deferUntilDialogCloses() {
    this.element.style.display = "none";
    const dialog = document.querySelector("dialog[open]");
    if (!dialog) {
      this.#reveal();
      return;
    }
    // Keep refs so disconnect() can detach this listener. Otherwise a toast
    // replaced by a newer broadcast while the dialog is still open stays
    // subscribed, and its now-detached controller fires #reveal()/#arm() on
    // close — a spurious auto-refresh from a stale toast.
    //
    // Known edge: if this dialog leaves the DOM without firing `close` (e.g.
    // a morph removes it), the toast stays hidden until the next broadcast
    // replaces it. Acceptable: the next sync re-delivers the toast.
    this._deferredDialog = dialog;
    this._dialogCloseHandler = () => this.#onDialogClose();
    dialog.addEventListener("close", this._dialogCloseHandler, { once: true });
  }

  #onDialogClose() {
    // The `once` listener has already fired and detached itself.
    this._deferredDialog = null;
    this._dialogCloseHandler = null;
    // Another dialog may still be open (stacked modals) — keep deferring until
    // every dialog has closed.
    if (this.#dialogOpen()) {
      this.#deferUntilDialogCloses();
      return;
    }
    this.#reveal();
  }

  #removeDeferredDialogListener() {
    if (this._deferredDialog && this._dialogCloseHandler) {
      this._deferredDialog.removeEventListener(
        "close",
        this._dialogCloseHandler,
      );
    }
    this._deferredDialog = null;
    this._dialogCloseHandler = null;
  }

  #reveal() {
    this.element.style.display = "";
    this.#arm();
  }

  #dialogOpen() {
    return !!document.querySelector("dialog[open]");
  }

  #ctaPending() {
    return !!document.getElementById("cta")?.firstElementChild;
  }

  #userIsInteracting() {
    // A grabbed list item (sortable-list) is only saved when it is released;
    // a morph would drop the move. Focus may have left it, so look it up in
    // the whole document.
    if (document.querySelector("[aria-grabbed='true']")) return true;

    const el = document.activeElement;
    if (!el || el === document.body || el === document.documentElement)
      return false;
    return (
      el.isContentEditable ||
      el.closest("form, dialog, [role='dialog']") !== null
    );
  }
}