focus-lock
Version:
DOM trap for a focus
60 lines (59 loc) • 2.07 kB
JavaScript
import { parentAutofocusables } from './DOMutils';
import { contains } from './DOMutils';
import { asArray } from './array';
var getParents = function (node, parents) {
if (parents === void 0) { parents = []; }
parents.push(node);
if (node.parentNode) {
getParents(node.parentNode.host || node.parentNode, parents);
}
return parents;
};
/**
* finds a parent for both nodeA and nodeB
* @param nodeA
* @param nodeB
* @returns {boolean|*}
*/
export var getCommonParent = function (nodeA, nodeB) {
var parentsA = getParents(nodeA);
var parentsB = getParents(nodeB);
// tslint:disable-next-line:prefer-for-of
for (var i = 0; i < parentsA.length; i += 1) {
var currentParent = parentsA[i];
if (parentsB.indexOf(currentParent) >= 0) {
return currentParent;
}
}
return false;
};
export var getTopCommonParent = function (baseActiveElement, leftEntry, rightEntries) {
var activeElements = asArray(baseActiveElement);
var leftEntries = asArray(leftEntry);
var activeElement = activeElements[0];
var topCommon = false;
leftEntries.filter(Boolean).forEach(function (entry) {
topCommon = getCommonParent(topCommon || entry, entry) || topCommon;
rightEntries.filter(Boolean).forEach(function (subEntry) {
var common = getCommonParent(activeElement, subEntry);
if (common) {
if (!topCommon || contains(common, topCommon)) {
topCommon = common;
}
else {
topCommon = getCommonParent(common, topCommon);
}
}
});
});
// TODO: add assert here?
return topCommon;
};
/**
* return list of nodes which are expected to be autofocused inside a given top nodes
* @param entries
* @param visibilityCache
*/
export var allParentAutofocusables = function (entries, visibilityCache) {
return entries.reduce(function (acc, node) { return acc.concat(parentAutofocusables(node, visibilityCache)); }, []);
};