Skip to content

Commit

Permalink
Add contains "polyfill" to domUtils
Browse files Browse the repository at this point in the history
small change, replace isNodeInRoot() in RootCloseWrapper, with a
elem.contains polyfill. offers better performance than recursively
walking up parentNodes, not that it matters much in the instances we use
it.
  • Loading branch information
jquense committed Jun 9, 2015
1 parent f2da250 commit 19b0cd4
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 19 deletions.
20 changes: 1 addition & 19 deletions src/RootCloseWrapper.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,6 @@ import EventListener from './utils/EventListener';

// TODO: Merge this logic with dropdown logic once #526 is done.

/**
* Checks whether a node is within
* a root nodes tree
*
* @param {DOMElement} node
* @param {DOMElement} root
* @returns {boolean}
*/
function isNodeInRoot(node, root) {
while (node) {
if (node === root) {
return true;
}
node = node.parentNode;
}

return false;
}

export default class RootCloseWrapper extends React.Component {
constructor(props) {
Expand All @@ -44,7 +26,7 @@ export default class RootCloseWrapper extends React.Component {
// If the click originated from within this component, don't do anything.
// e.srcElement is required for IE8 as e.target is undefined
let target = e.target || e.srcElement;
if (isNodeInRoot(target, React.findDOMNode(this))) {
if (domUtils.contains(React.findDOMNode(this), target)) {
return;
}

Expand Down
25 changes: 25 additions & 0 deletions src/utils/domUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,32 @@ function offsetParentFunc(elem) {
return offsetParent || docElem;
}

/**
* Cross browser .contains() polyfill
* @param {HTMLElement} elem
* @param {HTMLElement} inner
* @return {bool}
*/
function contains(elem, inner){
function ie8Contains(root, node) {
while (node) {
if (node === root) {
return true;
}
node = node.parentNode;
}
return false;
}

return (elem && elem.contains)
? elem.contains(inner)
: (elem && elem.compareDocumentPosition)
? elem === inner || !!(elem.compareDocumentPosition(inner) & 16)
: ie8Contains(elem, inner);
}

export default {
contains,
ownerDocument,
getComputedStyles,
getOffset,
Expand Down

0 comments on commit 19b0cd4

Please sign in to comment.