Skip to content

Commit e5bef41

Browse files
committed
Refactor orientation helper to express intent more clearly
1 parent 39575a0 commit e5bef41

File tree

1 file changed

+18
-8
lines changed

1 file changed

+18
-8
lines changed

app/javascript/helpers/orientation_helpers.js

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,18 +8,28 @@ export function orient({ target, anchor = null, reset = false }) {
88

99
const targetGeometry = geometry(target)
1010
const anchorGeometry = geometry(anchor)
11+
const shouldOrientLeft = targetGeometry.spaceOnRight < EDGE_THRESHOLD && targetGeometry.spaceOnRight < targetGeometry.spaceOnLeft
12+
const shouldOrientRight = targetGeometry.spaceOnLeft < EDGE_THRESHOLD && targetGeometry.spaceOnLeft < targetGeometry.spaceOnRight
1113

12-
if (targetGeometry.spaceOnRight < EDGE_THRESHOLD && targetGeometry.spaceOnRight < targetGeometry.spaceOnLeft) {
13-
const offset = Math.min(0, anchorGeometry.spaceOnLeft + anchorGeometry.width - targetGeometry.width) * -1
14-
target.classList.add("orient-left")
15-
target.style.setProperty("--orient-offset", `${offset}px`)
16-
} else if (targetGeometry.spaceOnLeft < EDGE_THRESHOLD && targetGeometry.spaceOnLeft < targetGeometry.spaceOnRight) {
17-
const offset = Math.max(0, anchorGeometry.spaceOnLeft + targetGeometry.width - window.innerWidth) * -1
18-
target.classList.add("orient-right")
19-
target.style.setProperty("--orient-offset", `${offset}px`)
14+
if (shouldOrientLeft) {
15+
orientLeft({ el: target, targetGeometry, anchorGeometry })
16+
} else if (shouldOrientRight) {
17+
orientRight({ el: target, targetGeometry, anchorGeometry })
2018
}
2119
}
2220

21+
function orientLeft({ el, targetGeometry, anchorGeometry }) {
22+
const offset = Math.min(0, anchorGeometry.spaceOnLeft + anchorGeometry.width - targetGeometry.width) * -1
23+
el.classList.add("orient-left")
24+
el.style.setProperty("--orient-offset", `${offset}px`)
25+
}
26+
27+
function orientRight({ el, targetGeometry, anchorGeometry }) {
28+
const offset = Math.max(0, anchorGeometry.spaceOnLeft + targetGeometry.width - window.innerWidth) * -1
29+
el.classList.add("orient-right")
30+
el.style.setProperty("--orient-offset", `${offset}px`)
31+
}
32+
2333
function geometry(el) {
2434
const rect = el.getBoundingClientRect()
2535
return {

0 commit comments

Comments
 (0)