2024-02-02 09:05:04 -06:00
|
|
|
import { Controller } from "@hotwired/stimulus"
|
|
|
|
|
|
|
|
// Connects to data-controller="dropdown"
|
|
|
|
export default class extends Controller {
|
|
|
|
static targets = ["menu"]
|
2024-03-28 18:24:07 +01:00
|
|
|
static values = { closeOnClick: { type: Boolean, default: true } }
|
2024-02-02 09:05:04 -06:00
|
|
|
|
2024-03-14 15:30:36 +01:00
|
|
|
toggleMenu = (e) => {
|
|
|
|
e.stopPropagation(); // Prevent event from closing the menu immediately
|
|
|
|
this.menuTarget.classList.contains("hidden") ? this.showMenu() : this.hideMenu();
|
|
|
|
}
|
|
|
|
|
|
|
|
showMenu = () => {
|
|
|
|
document.addEventListener("click", this.onDocumentClick);
|
|
|
|
this.menuTarget.classList.remove("hidden");
|
2024-02-02 09:05:04 -06:00
|
|
|
}
|
|
|
|
|
2024-02-08 14:37:36 -05:00
|
|
|
hideMenu = () => {
|
2024-03-14 15:30:36 +01:00
|
|
|
document.removeEventListener("click", this.onDocumentClick);
|
2024-02-02 09:05:04 -06:00
|
|
|
this.menuTarget.classList.add("hidden");
|
|
|
|
}
|
|
|
|
|
2024-03-14 15:30:36 +01:00
|
|
|
disconnect = () => {
|
|
|
|
this.hideMenu();
|
2024-02-02 09:05:04 -06:00
|
|
|
}
|
|
|
|
|
2024-03-14 15:30:36 +01:00
|
|
|
onDocumentClick = (e) => {
|
2024-03-28 18:24:07 +01:00
|
|
|
if (this.menuTarget.contains(e.target) && !this.closeOnClickValue ) {
|
2024-03-14 15:30:36 +01:00
|
|
|
// user has clicked inside of the dropdown
|
|
|
|
e.stopPropagation();
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
this.hideMenu();
|
2024-02-02 09:05:04 -06:00
|
|
|
}
|
2024-02-08 14:37:36 -05:00
|
|
|
}
|