Last active
February 1, 2024 19:28
-
-
Save souporserious/d8f6701426c8e331792c0c99635d2bfa to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** Get the offset ancestors of a node. */ | |
function getOffsetAncestors(node: HTMLElement): Set<HTMLElement> { | |
let ancestors = new Set<HTMLElement>() | |
let current: Element | null = node.offsetParent | |
while (current) { | |
if (current instanceof HTMLElement) { | |
ancestors.add(current) | |
current = current.offsetParent | |
} else { | |
break | |
} | |
} | |
return ancestors | |
} | |
/** Find the common offset parent of a set of nodes. */ | |
function findCommonOffsetParent(nodes: HTMLElement[] = []): HTMLElement { | |
let commonAncestors = getOffsetAncestors(nodes[0]) | |
for (let index = 1; index < nodes.length; index++) { | |
const ancestors = getOffsetAncestors(nodes[index]) | |
for (let ancestor of commonAncestors) { | |
if (!ancestors.has(ancestor)) { | |
commonAncestors.delete(ancestor) | |
} | |
} | |
if (commonAncestors.size === 0) { | |
return document.body | |
} | |
} | |
return commonAncestors.size > 0 | |
? commonAncestors.values().next().value | |
: document.body | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment