| 1 |
import isOffsetContainer from './isOffsetContainer'; |
| 2 |
import getRoot from './getRoot'; |
| 3 |
import getOffsetParent from './getOffsetParent'; |
| 4 |
|
| 5 |
/** |
| 6 |
* Finds the offset parent common to the two provided nodes |
| 7 |
* @method |
| 8 |
* @memberof Popper.Utils |
| 9 |
* @argument {Element} element1 |
| 10 |
* @argument {Element} element2 |
| 11 |
* @returns {Element} common offset parent |
| 12 |
*/ |
| 13 |
export default function findCommonOffsetParent(element1, element2) { |
| 14 |
// This check is needed to avoid errors in case one of the elements isn't defined for any reason |
| 15 |
if (!element1 || !element1.nodeType || !element2 || !element2.nodeType) { |
| 16 |
return document.documentElement; |
| 17 |
} |
| 18 |
|
| 19 |
// Here we make sure to give as "start" the element that comes first in the DOM |
| 20 |
const order = |
| 21 |
element1.compareDocumentPosition(element2) & |
| 22 |
Node.DOCUMENT_POSITION_FOLLOWING; |
| 23 |
const start = order ? element1 : element2; |
| 24 |
const end = order ? element2 : element1; |
| 25 |
|
| 26 |
// Get common ancestor container |
| 27 |
const range = document.createRange(); |
| 28 |
range.setStart(start, 0); |
| 29 |
range.setEnd(end, 0); |
| 30 |
const { commonAncestorContainer } = range; |
| 31 |
|
| 32 |
// Both nodes are inside #document |
| 33 |
if ( |
| 34 |
(element1 !== commonAncestorContainer && |
| 35 |
element2 !== commonAncestorContainer) || |
| 36 |
start.contains(end) |
| 37 |
) { |
| 38 |
if (isOffsetContainer(commonAncestorContainer)) { |
| 39 |
return commonAncestorContainer; |
| 40 |
} |
| 41 |
|
| 42 |
return getOffsetParent(commonAncestorContainer); |
| 43 |
} |
| 44 |
|
| 45 |
// one of the nodes is inside shadowDOM, find which one |
| 46 |
const element1root = getRoot(element1); |
| 47 |
if (element1root.host) { |
| 48 |
return findCommonOffsetParent(element1root.host, element2); |
| 49 |
} else { |
| 50 |
return findCommonOffsetParent(element1, getRoot(element2).host); |
| 51 |
} |
| 52 |
} |