utils.tsx 939 B

1234567891011121314151617181920212223242526272829
  1. // Taken from https://stackoverflow.com/a/56859650/1015027
  2. function findTextWithMarkup(contentNode: null | Element, textMatch: string | RegExp) {
  3. const hasText = (node: Element): boolean => {
  4. if (node.textContent === null) {
  5. return false;
  6. }
  7. if (typeof textMatch === 'string') {
  8. return node.textContent.includes(textMatch);
  9. }
  10. return textMatch.test(node.textContent);
  11. };
  12. const nodeHasText = hasText(contentNode as Element);
  13. const childrenDontHaveText = Array.from(contentNode?.children || []).every(
  14. child => !hasText(child)
  15. );
  16. return nodeHasText && childrenDontHaveText;
  17. }
  18. /**
  19. * May be used with a *ByText RTL matcher to match text within multiple nodes
  20. *
  21. * e.g.: <div>Hello <span>world</span></div>
  22. */
  23. export function textWithMarkupMatcher(textMatch: string | RegExp) {
  24. return function (_: string, element: Element | null) {
  25. return findTextWithMarkup(element, textMatch);
  26. };
  27. }