label-content-name-mismatch-evaluate.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import {
  2. accessibleText,
  3. isHumanInterpretable,
  4. visibleTextNodes,
  5. isIconLigature,
  6. sanitize,
  7. removeUnicode
  8. } from '../../commons/text';
  9. /**
  10. * Check if a given text exists in another
  11. *
  12. * @param {String} compare given text to check
  13. * @param {String} compareWith text against which to be compared
  14. * @returns {Boolean}
  15. */
  16. function isStringContained(compare, compareWith) {
  17. const curatedCompareWith = curateString(compareWith);
  18. const curatedCompare = curateString(compare);
  19. if (!curatedCompareWith || !curatedCompare) {
  20. return false;
  21. }
  22. return curatedCompareWith.includes(curatedCompare);
  23. }
  24. /**
  25. * Curate given text, by removing emoji's, punctuations, unicode and trim whitespace.
  26. *
  27. * @param {String} str given text to curate
  28. * @returns {String}
  29. */
  30. function curateString(str) {
  31. const noUnicodeStr = removeUnicode(str, {
  32. emoji: true,
  33. nonBmp: true,
  34. punctuations: true
  35. });
  36. return sanitize(noUnicodeStr);
  37. }
  38. function labelContentNameMismatchEvaluate(node, options, virtualNode) {
  39. const { pixelThreshold, occuranceThreshold } = options || {};
  40. const accText = accessibleText(node).toLowerCase();
  41. if (isHumanInterpretable(accText) < 1) {
  42. return undefined;
  43. }
  44. const textVNodes = visibleTextNodes(virtualNode);
  45. const nonLigatureText = textVNodes
  46. .filter(
  47. textVNode =>
  48. !isIconLigature(textVNode, pixelThreshold, occuranceThreshold)
  49. )
  50. .map(textVNode => textVNode.actualNode.nodeValue)
  51. .join('');
  52. const visibleText = sanitize(nonLigatureText).toLowerCase();
  53. if (!visibleText) {
  54. return true;
  55. }
  56. if (isHumanInterpretable(visibleText) < 1) {
  57. if (isStringContained(visibleText, accText)) {
  58. return true;
  59. }
  60. return undefined;
  61. }
  62. return isStringContained(visibleText, accText);
  63. }
  64. export default labelContentNameMismatchEvaluate;