import { Controller } from '@hotwired/stimulus' /* * Pins the hover menu of templates/components/dropdown.html.twig to the viewport while it is open. * * The menu sits in the last cell of data tables, whose wrapper scrolls horizontally when a table is * wider than its column (components/datatable.css). A scrolling box clips everything absolutely * positioned inside it, so on the last rows the menu would vanish into a scrollbar. Fixed * positioning takes it out of that box; it stays a descendant of the hover group, so the CSS * group-hover that shows and hides it keeps working unchanged. * * Right-aligned to the button like before, and flipped above it when there is no room below. */ export default class extends Controller { static targets = [ 'button', 'menu' ] connect () { this.boundPosition = this.position.bind(this) } open () { this.position() window.addEventListener('scroll', this.boundPosition, true) window.addEventListener('resize', this.boundPosition) } close () { window.removeEventListener('scroll', this.boundPosition, true) window.removeEventListener('resize', this.boundPosition) } position () { const button = this.buttonTarget.getBoundingClientRect() const menu = this.menuTarget menu.style.position = 'fixed' menu.style.left = `${Math.max(0, button.right - menu.offsetWidth)}px` // the menu's own top padding bridges the gap to the button, so the hover is not lost // on the way down; when flipped, it covers the button from below instead const fitsBelow = button.top + menu.offsetHeight <= window.innerHeight menu.style.top = `${fitsBelow ? button.top : Math.max(0, button.bottom - menu.offsetHeight)}px` menu.style.right = 'auto' } disconnect () { this.close() } }