Tweak orientation helper to prevent popups from going off screen

This commit is contained in:
Adrien Maston
2026-01-23 14:06:17 +01:00
parent 65b2db0ec8
commit 764eb8987a
5 changed files with 29 additions and 23 deletions
@@ -26,7 +26,7 @@ export default class extends Controller {
this.dialogTarget.showModal()
} else {
this.dialogTarget.show()
orient(this.dialogTarget)
orient({ target: this.dialogTarget, anchor: this.element })
}
this.loadLazyFrames()
@@ -46,7 +46,7 @@ export default class extends Controller {
this.dialogTarget.close()
this.dialogTarget.setAttribute("aria-hidden", "true")
this.dialogTarget.blur()
orient(this.dialogTarget, false)
orient({ target: this.dialogTarget, reset: true })
this.dispatch("close")
}
@@ -15,11 +15,11 @@ export default class extends Controller {
}
mouseEnter(event) {
orient(this.#tooltipElement)
orient({ target: this.#tooltipElement, anchor: this.element })
}
mouseOut(event) {
orient(this.#tooltipElement, false)
orient({ target: this.#tooltipElement, reset: true })
}
get #tooltipElement() {
+21 -15
View File
@@ -1,24 +1,30 @@
const EDGE_THRESHOLD = 16
export function orient(el, orient = true) {
el.classList.remove("orient-left", "orient-right")
export function orient({ target, anchor = null, reset = false }) {
target.classList.remove("orient-left", "orient-right")
target.style.removeProperty("--orient-offset")
if (!orient) return
if (reset) return
const rightSpace = spaceOnRight(el)
const leftSpace = spaceOnLeft(el)
const targetGeometry = geometry(target)
const anchorGeometry = geometry(anchor)
if (rightSpace < EDGE_THRESHOLD && rightSpace < leftSpace) {
el.classList.add("orient-left")
} else if (leftSpace < EDGE_THRESHOLD && leftSpace < rightSpace) {
el.classList.add("orient-right")
if (targetGeometry.spaceOnRight < EDGE_THRESHOLD && targetGeometry.spaceOnRight < targetGeometry.spaceOnLeft) {
const offset = Math.min(0, anchorGeometry.spaceOnLeft + anchorGeometry.width - targetGeometry.width) * -1
target.classList.add("orient-left")
target.style.setProperty("--orient-offset", `${offset}px`)
} else if (targetGeometry.spaceOnLeft < EDGE_THRESHOLD && targetGeometry.spaceOnLeft < targetGeometry.spaceOnRight) {
const offset = Math.max(0, anchorGeometry.spaceOnLeft + targetGeometry.width - window.innerWidth) * -1
target.classList.add("orient-right")
target.style.setProperty("--orient-offset", `${offset}px`)
}
}
function spaceOnLeft(el) {
return el.getBoundingClientRect().left
}
function spaceOnRight(el) {
return window.innerWidth - el.getBoundingClientRect().right
function geometry(el) {
const rect = el.getBoundingClientRect()
return {
spaceOnLeft: rect.left,
spaceOnRight: window.innerWidth - rect.right,
width: rect.width
}
}