All files / util dom-helpers.js

72% Statements 18/25
56.25% Branches 9/16
57.14% Functions 4/7
72% Lines 18/25
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82      7x   5x                     6x 6x 6x     1x 5x                         2x 2x 2x 2x                             7x 7x   7x 1x     6x 5x     1x                                  
import _ from 'lodash';
 
export function getAbsoluteBoundingClientRect(domNode) {
	const elementRect = domNode.getBoundingClientRect();
 
	return {
		bottom: elementRect.bottom + window.pageYOffset,
		top: elementRect.top + window.pageYOffset,
		left: elementRect.left + window.pageXOffset,
		right: elementRect.right + window.pageXOffset,
		height: elementRect.height,
		width: elementRect.width,
	};
}
 
export function scrollParentTo(domNode, additionalOffset = 0) {
	Eif (domNode) {
		const parentNode = domNode.parentNode;
		if (parentNode.scrollTop > domNode.offsetTop - additionalOffset) {
			// if the top of the node is above the scroll line,
			// align to top
			parentNode.scrollTop = domNode.offsetTop - additionalOffset;
		} else Iif (
			parentNode.scrollTop + parentNode.clientHeight <
			domNode.offsetTop + domNode.offsetHeight
		) {
			// else if the bottom of the node is below the fold,
			// align to bottom
			parentNode.scrollTop =
				domNode.offsetHeight - (parentNode.clientHeight - domNode.offsetTop);
		} // else don't need to align anything
	}
}
 
export function dispatchDOMEvent(node, eventName, assignedEventProps) {
	const event = document.createEvent('Event');
	event.initEvent(eventName, true, true);
	node.dispatchEvent(_.assign(event, assignedEventProps));
	return event;
}
 
/**
 * sharesAncestor
 *
 * Recursively looks at `node` and its parents for `nodeName` and makes
 * sure it contains `siblingNode`.
 *
 * @param {element} node - dom node to check if any of its ancestors are a `<label>`
 * @param {element} siblingNode - dom node to see if it shares an ancestor
 * @param {string} nodeName - dom node name, should be uppercased, e.g. `LABEL` or `SPAN`
 * @returns {boolean}
 */
export function sharesAncestor(node, siblingNode, nodeName) {
	const currentNodeName = _.get(node, 'nodeName');
	const parentNode = _.get(node, 'parentNode');
 
	if (currentNodeName === nodeName) {
		return node.contains(siblingNode);
	}
 
	if (parentNode) {
		return sharesAncestor(parentNode, siblingNode, nodeName);
	}
 
	return false;
}
 
export function shiftChildren(parent, n = 1) {
	if (n < 0) {
		_.times(Math.abs(n), () => {
			parent.appendChild(parent.children[0]);
		});
	} else if (n > 0) {
		_.times(n, () => {
			parent.insertBefore(
				parent.children[parent.children.length - 1],
				parent.children[0]
			);
		});
	}
}