visible-virtual.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import sanitize from './sanitize';
  2. import isVisible from '../dom/is-visible';
  3. import AbstractVirtualNode from '../../core/base/virtual-node/abstract-virtual-node';
  4. import { getNodeFromTree } from '../../core/utils';
  5. /**
  6. * Returns the visible text of the virtual node
  7. * NOTE: when calculating the text or accessible text of a node that includes shadow
  8. * roots attached to it or its children, the flattened tree must be considered
  9. * rather than the "light DOM"
  10. * @method visibleVirtual
  11. * @memberof axe.commons.text
  12. * @instance
  13. * @param {VirtualNode} element
  14. * @param {Boolean} screenReader When provided, will evaluate visibility from the perspective of a screen reader
  15. * @param {Boolean} noRecursing When False, the result will contain text from the element and it's children.
  16. * When True, the result will only contain text from the element
  17. * @return {String}
  18. */
  19. function visibleVirtual(element, screenReader, noRecursing) {
  20. const vNode =
  21. element instanceof AbstractVirtualNode ? element : getNodeFromTree(element);
  22. // if the element does not have an actual node treat it as if
  23. // it is visible
  24. const visible =
  25. !element.actualNode ||
  26. (element.actualNode && isVisible(element.actualNode, screenReader));
  27. const result = vNode.children
  28. .map(child => {
  29. const { nodeType, nodeValue } = child.props;
  30. if (nodeType === 3) {
  31. // filter on text nodes
  32. if (nodeValue && visible) {
  33. return nodeValue;
  34. }
  35. } else if (!noRecursing) {
  36. return visibleVirtual(child, screenReader);
  37. }
  38. })
  39. .join('');
  40. return sanitize(result);
  41. }
  42. export default visibleVirtual;