Created
August 9, 2020 02:59
-
-
Save HunterLarco/1cfb3e9998524c6c4803ec7cbb2a843e to your computer and use it in GitHub Desktop.
This file contains 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
function isIterableNode(node) { | |
if (node.nodeName == 'NOSCRIPT') { | |
return false; | |
} | |
return true; | |
} | |
function* nodeIterator(root) { | |
const treeWalker = document.createTreeWalker( | |
root, | |
NodeFilter.SHOW_ALL, | |
{ | |
acceptNode(node) { | |
return isIterableNode(node) | |
? NodeFilter.FILTER_ACCEPT | |
: NodeFilder.FILTER_REJECT; | |
}, | |
} | |
); | |
let node = treeWalker.currentNode; | |
while (node) { | |
yield node; | |
node = treeWalker.nextNode(); | |
} | |
} | |
export default function* walk(selection) { | |
const startContainer = selection.startContainer; | |
const startOffset = selection.startOffset; | |
const endContainer = selection.endContainer; | |
const endOffset = selection.endOffset; | |
if (startContainer === endContainer && startOffset == endOffset) { | |
return null; | |
} | |
if (!startContainer.childNodes.length) { | |
yield startContainer | |
} | |
if (startContainer === endContainer) { | |
return; | |
} | |
let ancestor = startContainer; | |
while (ancestor) { | |
let sibling = ancestor; | |
while (sibling.nextSibling) { | |
sibling = sibling.nextSibling; | |
for (const node of nodeIterator(sibling)) { | |
if (!node.childNodes.length) { | |
yield node | |
} | |
if (node === endContainer) { | |
return | |
} | |
} | |
} | |
ancestor = ancestor.parentNode; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment