58 lines
2.3 KiB
JavaScript
58 lines
2.3 KiB
JavaScript
|
/**
|
||
|
* The helper functions here will make the target element as modal to screen readers, by placing aria-hidden on elements
|
||
|
* that are siblings to the target element and the target element's ancestors (because aria-hidden gets inherited).
|
||
|
* That way, all other elements on the page are hidden to the screen reader.
|
||
|
*/
|
||
|
import { getDocument } from './dom/getDocument';
|
||
|
/** Tag names to ignore when modalizing */
|
||
|
var tagsToIgnore = ['TEMPLATE', 'STYLE', 'SCRIPT'];
|
||
|
/**
|
||
|
* Call this on a target element to make it modal to screen readers.
|
||
|
* Returns a function that undoes the changes it made.
|
||
|
*/
|
||
|
export function modalize(target) {
|
||
|
var targetDocument = getDocument(target);
|
||
|
if (!targetDocument) {
|
||
|
// can't do this in SSR
|
||
|
return function () { return undefined; };
|
||
|
}
|
||
|
var affectedNodes = [];
|
||
|
// start at target, then recurse and do the same for parent, until we reach <body>
|
||
|
while (target !== targetDocument.body && target.parentElement) {
|
||
|
// grab all siblings of current element
|
||
|
for (var _i = 0, _a = target.parentElement.children; _i < _a.length; _i++) {
|
||
|
var sibling = _a[_i];
|
||
|
// but ignore elements that are already aria-hidden
|
||
|
var ariaHidden = sibling.getAttribute('aria-hidden');
|
||
|
if (sibling !== target && (ariaHidden === null || ariaHidden === void 0 ? void 0 : ariaHidden.toLowerCase()) !== 'true' && tagsToIgnore.indexOf(sibling.tagName) === -1) {
|
||
|
affectedNodes.push([sibling, ariaHidden]);
|
||
|
}
|
||
|
}
|
||
|
target = target.parentElement;
|
||
|
}
|
||
|
// take all those elements and set aria-hidden=true on them
|
||
|
affectedNodes.forEach(function (_a) {
|
||
|
var node = _a[0];
|
||
|
node.setAttribute('aria-hidden', 'true');
|
||
|
});
|
||
|
return function () {
|
||
|
unmodalize(affectedNodes);
|
||
|
affectedNodes = []; // dispose
|
||
|
};
|
||
|
}
|
||
|
/**
|
||
|
* Undoes the changes that modalize() did.
|
||
|
*/
|
||
|
function unmodalize(affectedNodes) {
|
||
|
affectedNodes.forEach(function (_a) {
|
||
|
var node = _a[0], originalValue = _a[1];
|
||
|
// Restore the original value (false or unset)
|
||
|
if (originalValue) {
|
||
|
node.setAttribute('aria-hidden', originalValue);
|
||
|
}
|
||
|
else {
|
||
|
node.removeAttribute('aria-hidden');
|
||
|
}
|
||
|
});
|
||
|
}
|
||
|
//# sourceMappingURL=modalize.js.map
|