| 1 |
import getStyleComputedProperty from './getStyleComputedProperty'; |
| 2 |
import includeScroll from './includeScroll'; |
| 3 |
import getScrollParent from './getScrollParent'; |
| 4 |
import getBoundingClientRect from './getBoundingClientRect'; |
| 5 |
import runIsIE from './isIE'; |
| 6 |
import getClientRect from './getClientRect'; |
| 7 |
|
| 8 |
export default function getOffsetRectRelativeToArbitraryNode(children, parent, fixedPosition = false) { |
| 9 |
const isIE10 = runIsIE(10); |
| 10 |
const isHTML = parent.nodeName === 'HTML'; |
| 11 |
const childrenRect = getBoundingClientRect(children); |
| 12 |
const parentRect = getBoundingClientRect(parent); |
| 13 |
const scrollParent = getScrollParent(children); |
| 14 |
|
| 15 |
const styles = getStyleComputedProperty(parent); |
| 16 |
const borderTopWidth = parseFloat(styles.borderTopWidth); |
| 17 |
const borderLeftWidth = parseFloat(styles.borderLeftWidth); |
| 18 |
|
| 19 |
// In cases where the parent is fixed, we must ignore negative scroll in offset calc |
| 20 |
if(fixedPosition && isHTML) { |
| 21 |
parentRect.top = Math.max(parentRect.top, 0); |
| 22 |
parentRect.left = Math.max(parentRect.left, 0); |
| 23 |
} |
| 24 |
let offsets = getClientRect({ |
| 25 |
top: childrenRect.top - parentRect.top - borderTopWidth, |
| 26 |
left: childrenRect.left - parentRect.left - borderLeftWidth, |
| 27 |
width: childrenRect.width, |
| 28 |
height: childrenRect.height, |
| 29 |
}); |
| 30 |
offsets.marginTop = 0; |
| 31 |
offsets.marginLeft = 0; |
| 32 |
|
| 33 |
// Subtract margins of documentElement in case it's being used as parent |
| 34 |
// we do this only on HTML because it's the only element that behaves |
| 35 |
// differently when margins are applied to it. The margins are included in |
| 36 |
// the box of the documentElement, in the other cases not. |
| 37 |
if (!isIE10 && isHTML) { |
| 38 |
const marginTop = parseFloat(styles.marginTop); |
| 39 |
const marginLeft = parseFloat(styles.marginLeft); |
| 40 |
|
| 41 |
offsets.top -= borderTopWidth - marginTop; |
| 42 |
offsets.bottom -= borderTopWidth - marginTop; |
| 43 |
offsets.left -= borderLeftWidth - marginLeft; |
| 44 |
offsets.right -= borderLeftWidth - marginLeft; |
| 45 |
|
| 46 |
// Attach marginTop and marginLeft because in some circumstances we may need them |
| 47 |
offsets.marginTop = marginTop; |
| 48 |
offsets.marginLeft = marginLeft; |
| 49 |
} |
| 50 |
|
| 51 |
if ( |
| 52 |
isIE10 && !fixedPosition |
| 53 |
? parent.contains(scrollParent) |
| 54 |
: parent === scrollParent && scrollParent.nodeName !== 'BODY' |
| 55 |
) { |
| 56 |
offsets = includeScroll(offsets, parent); |
| 57 |
} |
| 58 |
|
| 59 |
return offsets; |
| 60 |
} |