/** * @file Place un menu flottant dans la zone réellement visible : décalage horizontal, ouverture vers le haut * et hauteur limitée. */ const EDGE_GAP = 8; /** Zone visible : la fenêtre, sous la barre supérieure collante, réduite par les ancêtres qui coupent leur contenu. */ function visibleArea(element) { const area = { top: EDGE_GAP, right: window.innerWidth - EDGE_GAP, bottom: window.innerHeight - EDGE_GAP, left: EDGE_GAP }; const topbar = element.ownerDocument.querySelector(".topbar"); if (topbar) area.top = Math.max(area.top, topbar.getBoundingClientRect().bottom + EDGE_GAP); for (let parent = element.parentElement; parent && parent !== element.ownerDocument.documentElement; parent = parent.parentElement) { const style = window.getComputedStyle(parent); const bounds = parent.getBoundingClientRect(); if (style.overflowX !== "visible") { area.left = Math.max(area.left, bounds.left + EDGE_GAP); area.right = Math.min(area.right, bounds.right - EDGE_GAP); } if (style.overflowY !== "visible") { area.top = Math.max(area.top, bounds.top + EDGE_GAP); area.bottom = Math.min(area.bottom, bounds.bottom - EDGE_GAP); } } return area; } export function placeDropdownMenu(menu, trigger) { // Repartir de la position prévue par le style : chaque calcul mesure le menu tel qu'il s'ouvrirait naturellement. Object.assign(menu.style, { translate: "", top: "", bottom: "", maxHeight: "", overflowY: "" }); const area = visibleArea(menu); const box = menu.getBoundingClientRect(); let shift = 0; if (box.right > area.right) shift = area.right - box.right; if (box.left + shift < area.left) shift = area.left - box.left; if (shift) menu.style.translate = `${Math.round(shift)}px 0`; if (box.bottom <= area.bottom) return; const anchor = trigger.getBoundingClientRect(); const gap = box.top - anchor.bottom; const below = area.bottom - anchor.bottom - gap; const above = anchor.top - area.top - gap; const openAbove = box.height <= above || above > below; if (openAbove) Object.assign(menu.style, { top: "auto", bottom: `calc(100% + ${Math.round(gap)}px)` }); const room = Math.floor(openAbove ? above : below); if (box.height > room) Object.assign(menu.style, { maxHeight: `${Math.max(room, 80)}px`, overflowY: "auto" }); }