-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
39 lines (31 loc) · 1.04 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
const POSITION_MAP = {
l: 'left',
r: 'right',
t: 'top',
b: 'bottom'
}
const reverseString = str => str.split('').reverse().join('')
const normalizePos = pos => (pos.startsWith('t') || pos.startsWith('b')) ? reverseString(pos) : pos
const extractPos = pos => pos.split('').map(p => POSITION_MAP[p])
const transformStyle = ({ x, y }) => `translate(${x}px, ${y}px)`
const relativeDiff = ({ a, aPos = 'lt', b, bPos = 'lt' }) => {
aPos = extractPos(normalizePos(aPos))
bPos = extractPos(normalizePos(bPos))
const aRect = a.getBoundingClientRect()
const bRect = b.getBoundingClientRect()
const { e: translateX, f: translateY } = new DOMMatrix(a.style.transform)
return {
x: bRect[bPos[0]] - aRect[aPos[0]] + translateX,
y: bRect[bPos[1]] - aRect[aPos[1]] + translateY
}
}
const matchPosition = ({ a, aPos = 'lt', b, bPos = 'lt' }) => {
const diff = relativeDiff({ a, aPos, b, bPos })
const style = transformStyle(diff)
a.style.setProperty('transform', style)
}
export {
matchPosition,
relativeDiff,
transformStyle
}