Skip to content

Commit 912db2b

Browse files
authored
Use the delta with current position to execute a single positioning
1 parent d628227 commit 912db2b

File tree

1 file changed

+25
-14
lines changed

1 file changed

+25
-14
lines changed

src/text-expander-element.ts

+25-14
Original file line numberDiff line numberDiff line change
@@ -84,20 +84,7 @@ class TextExpander {
8484

8585
this.expander.dispatchEvent(new Event('text-expander-activate'))
8686

87-
const caretRect = new InputRange(this.input, match.position).getBoundingClientRect()
88-
const nominalPosition = {top: caretRect.top + caretRect.height, left: caretRect.left}
89-
menu.style.top = `${nominalPosition.top}px`
90-
menu.style.left = `${nominalPosition.left}px`
91-
92-
// Nominal position is relative to entire document, but the menu could be positioned relative to a container if
93-
// it is not `fixed` or on the top layer
94-
const actualPosition = menu.getBoundingClientRect()
95-
96-
const topDelta = actualPosition.top - nominalPosition.top
97-
if (topDelta !== 0) menu.style.top = `${nominalPosition.top - topDelta}px`
98-
99-
const leftDelta = actualPosition.left - nominalPosition.left
100-
if (leftDelta !== 0) menu.style.left = `${nominalPosition.left - leftDelta}px`
87+
this.positionMenu(menu, match.position)
10188

10289
this.combobox.start()
10390
menu.addEventListener('combobox-commit', this.oncommit)
@@ -107,6 +94,30 @@ class TextExpander {
10794
this.combobox.navigate(1)
10895
}
10996

97+
private positionMenu(menu: HTMLElement, position: number) {
98+
const caretRect = new InputRange(this.input, position).getBoundingClientRect()
99+
const targetPosition = {left: caretRect.left, top: caretRect.top + caretRect.height}
100+
101+
const currentPosition = menu.getBoundingClientRect()
102+
103+
const delta = {
104+
left: targetPosition.left - currentPosition.left,
105+
top: targetPosition.top - currentPosition.top
106+
}
107+
108+
// eslint-disable-next-line no-console
109+
console.log(delta)
110+
111+
if (delta.left !== 0 || delta.top !== 0) {
112+
// Use computedStyle to avoid nesting calc() deeper and deeper
113+
const currentStyle = getComputedStyle(menu)
114+
115+
// Using `calc` avoids having to parse the current pixel value
116+
menu.style.left = currentStyle.left ? `calc(${currentStyle.left} + ${delta.left}px)` : `${delta.left}px`
117+
menu.style.top = currentStyle.top ? `calc(${currentStyle.top} + ${delta.top}px)` : `${delta.top}px`
118+
}
119+
}
120+
110121
private deactivate() {
111122
const menu = this.menu
112123
if (!menu || !this.combobox) return false

0 commit comments

Comments
 (0)