native-text-alternative.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import getRole from '../aria/get-role';
  2. import getElementSpec from '../standards/get-element-spec';
  3. import nativeTextMethods from './native-text-methods';
  4. /**
  5. * Get the accessible text using native HTML methods only
  6. * @param {VirtualNode} element
  7. * @param {Object} context
  8. * @property {Bool} debug Enable logging for formControlValue
  9. * @return {String} Accessible text
  10. */
  11. function nativeTextAlternative(virtualNode, context = {}) {
  12. const { actualNode } = virtualNode;
  13. if (
  14. virtualNode.props.nodeType !== 1 ||
  15. ['presentation', 'none'].includes(getRole(virtualNode))
  16. ) {
  17. return '';
  18. }
  19. const textMethods = findTextMethods(virtualNode);
  20. // Find the first step that returns a non-empty string
  21. const accName = textMethods.reduce((accName, step) => {
  22. return accName || step(virtualNode, context);
  23. }, '');
  24. if (context.debug) {
  25. axe.log(accName || '{empty-value}', actualNode, context);
  26. }
  27. return accName;
  28. }
  29. /**
  30. * Get accessible text functions for a specific native HTML element
  31. * @private
  32. * @param {VirtualNode} element
  33. * @return {Function[]} Array of native accessible name computation methods
  34. */
  35. function findTextMethods(virtualNode) {
  36. const elmSpec = getElementSpec(virtualNode);
  37. const methods = elmSpec.namingMethods || [];
  38. return methods.map(methodName => nativeTextMethods[methodName]);
  39. }
  40. export default nativeTextAlternative;