|
|
import isOffsetContainer from './isOffsetContainer'; |
|
|
import getRoot from './getRoot'; |
|
|
import getOffsetParent from './getOffsetParent'; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export default function findCommonOffsetParent(element1, element2) { |
|
|
|
|
|
if (!element1 || !element1.nodeType || !element2 || !element2.nodeType) { |
|
|
return document.documentElement; |
|
|
} |
|
|
|
|
|
|
|
|
const order = |
|
|
element1.compareDocumentPosition(element2) & |
|
|
Node.DOCUMENT_POSITION_FOLLOWING; |
|
|
const start = order ? element1 : element2; |
|
|
const end = order ? element2 : element1; |
|
|
|
|
|
|
|
|
const range = document.createRange(); |
|
|
range.setStart(start, 0); |
|
|
range.setEnd(end, 0); |
|
|
const { commonAncestorContainer } = range; |
|
|
|
|
|
|
|
|
if ( |
|
|
(element1 !== commonAncestorContainer && |
|
|
element2 !== commonAncestorContainer) || |
|
|
start.contains(end) |
|
|
) { |
|
|
if (isOffsetContainer(commonAncestorContainer)) { |
|
|
return commonAncestorContainer; |
|
|
} |
|
|
|
|
|
return getOffsetParent(commonAncestorContainer); |
|
|
} |
|
|
|
|
|
|
|
|
const element1root = getRoot(element1); |
|
|
if (element1root.host) { |
|
|
return findCommonOffsetParent(element1root.host, element2); |
|
|
} else { |
|
|
return findCommonOffsetParent(element1, getRoot(element2).host); |
|
|
} |
|
|
} |
|
|
|