Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
5.7 KB
Raw Blame
import {
  autoUpdate,
  computePosition,
  flip,
  offset,
  shift,
} from "@floating-ui/dom";
import { Controller } from "@hotwired/stimulus";

/**
 * Positioned panel for mixed content (forms, pickers, account menus).
 * Mirrors DS--menu's positioning + open/close lifecycle but skips the
 * `role="menu"` / arrow-key navigation that's specific to action lists.
 * Wiring `aria-expanded` on the trigger so AT users hear "expanded" /
 * "collapsed" as the panel opens / closes.
 */
export default class extends Controller {
  static targets = ["button", "content", "frame"];

  static values = {
    show: Boolean,
    placement: { type: String, default: "bottom-end" },
    offset: { type: Number, default: 6 },
    mobileFullwidth: { type: Boolean, default: true },
    frameId: String,
    frameSrc: String,
  };

  connect() {
    this.boundUpdate = this.update.bind(this);
    this.addEventListeners();
    this.startAutoUpdate();
  }

  // Derived from the content element's own class rather than tracked as
  // separate state. A Turbo morph (e.g. a same-page refresh while this
  // popover is mounted) re-renders the content element closed without
  // going through toggle()/close(), which would otherwise leave a plain
  // instance property out of sync with the DOM — swallowing the next
  // click because toggle() would think it still needs to close.
  get show() {
    return !this.contentTarget.classList.contains("hidden");
  }

  disconnect() {
    this.removeEventListeners();
    this.stopAutoUpdate();
    this.close();
  }

  addEventListeners() {
    this.buttonTarget.addEventListener("click", this.toggle);
    this.element.addEventListener("keydown", this.handleKeydown);
    document.addEventListener("click", this.handleOutsideClick);
    document.addEventListener("turbo:load", this.handleTurboLoad);
  }

  removeEventListeners() {
    this.buttonTarget.removeEventListener("click", this.toggle);
    this.element.removeEventListener("keydown", this.handleKeydown);
    document.removeEventListener("click", this.handleOutsideClick);
    document.removeEventListener("turbo:load", this.handleTurboLoad);
  }

  handleTurboLoad = () => {
    if (!this.show) this.close();
  };

  // A click in a modal dialog opened on top of the panel (e.g. the
  // data-turbo-confirm dialog of a form inside it) is not outside the panel.
  handleOutsideClick = (event) => {
    const dialog = event.target.closest?.("dialog[open]");
    if (dialog && !dialog.contains(this.element)) return;

    if (this.show && !this.element.contains(event.target)) this.close();
  };

  handleKeydown = (event) => {
    if (event.key === "Escape") {
      this.close();
      this.buttonTarget.focus();
    }
  };

  toggle = () => {
    const nextShow = !this.show;
    this.contentTarget.classList.toggle("hidden", !nextShow);
    this.buttonTarget.setAttribute("aria-expanded", nextShow.toString());
    if (nextShow) {
      this.mountFrame();
      this.update();
      this.focusFirstElement();
    }
  };

  // Lazy panels (frameSrc value) get their <turbo-frame> on first open only;
  // connecting it with a src makes Turbo fetch it. Until then the panel is an
  // empty slot, so a page with hundreds of popovers ships no frame markup
  // for the ones never opened. Turbo marks the frame aria-busy while loading.
  mountFrame() {
    if (!this.hasFrameTarget || !this.frameSrcValue) return;
    if (this.frameTarget.childElementCount > 0) return;

    const frame = document.createElement("turbo-frame");
    frame.id = this.frameIdValue;
    frame.setAttribute("src", this.frameSrcValue);
    const placeholder = document.createElement("div");
    placeholder.className = "p-6 flex items-center justify-center";
    const skeleton = document.createElement("div");
    skeleton.className = "h-4 w-24 rounded-md bg-container-inset animate-pulse";
    placeholder.append(skeleton);
    frame.append(placeholder);
    this.frameTarget.replaceChildren(frame);
  }

  // Used as an action (a Cancel button in the panel), close() returns focus
  // to the trigger like Escape does, instead of dropping it to <body>.
  close(event) {
    this.contentTarget.classList.add("hidden");
    this.buttonTarget.setAttribute("aria-expanded", "false");
    if (event) this.buttonTarget.focus();
  }

  focusFirstElement() {
    const focusableElements =
      'button, [href], input:not([type="hidden"]), select, textarea, [tabindex]:not([tabindex="-1"])';
    const firstFocusableElement =
      this.contentTarget.querySelectorAll(focusableElements)[0];
    if (firstFocusableElement) {
      firstFocusableElement.focus({ preventScroll: true });
    }
  }

  startAutoUpdate() {
    if (!this._cleanup) {
      this._cleanup = autoUpdate(
        this.buttonTarget,
        this.contentTarget,
        this.boundUpdate,
      );
    }
  }

  stopAutoUpdate() {
    if (this._cleanup) {
      this._cleanup();
      this._cleanup = null;
    }
  }

  update() {
    if (!this.buttonTarget || !this.contentTarget) return;

    const isSmallScreen = !window.matchMedia("(min-width: 768px)").matches;
    const useMobileFullwidth = isSmallScreen && this.mobileFullwidthValue;

    computePosition(this.buttonTarget, this.contentTarget, {
      placement: useMobileFullwidth ? "bottom" : this.placementValue,
      middleware: [offset(this.offsetValue), flip({ padding: 5 }), shift({ padding: 5 })],
      strategy: "fixed",
    }).then(({ x, y }) => {
      if (useMobileFullwidth) {
        Object.assign(this.contentTarget.style, {
          position: "fixed",
          left: "0px",
          width: "100vw",
          top: `${y}px`,
        });
      } else {
        Object.assign(this.contentTarget.style, {
          position: "fixed",
          left: `${x}px`,
          top: `${y}px`,
          width: "",
        });
      }
    });
  }
}