query-helpers.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.buildQueries = buildQueries;
  6. exports.getElementError = getElementError;
  7. exports.getMultipleElementsFoundError = getMultipleElementsFoundError;
  8. exports.makeFindQuery = makeFindQuery;
  9. exports.makeGetAllQuery = makeGetAllQuery;
  10. exports.makeSingleQuery = makeSingleQuery;
  11. exports.queryAllByAttribute = queryAllByAttribute;
  12. exports.queryByAttribute = queryByAttribute;
  13. exports.wrapSingleQueryWithSuggestion = exports.wrapAllByQueryWithSuggestion = void 0;
  14. var _suggestions = require("./suggestions");
  15. var _matches = require("./matches");
  16. var _waitFor = require("./wait-for");
  17. var _config = require("./config");
  18. function getElementError(message, container) {
  19. return (0, _config.getConfig)().getElementError(message, container);
  20. }
  21. function getMultipleElementsFoundError(message, container) {
  22. return getElementError(`${message}\n\n(If this is intentional, then use the \`*AllBy*\` variant of the query (like \`queryAllByText\`, \`getAllByText\`, or \`findAllByText\`)).`, container);
  23. }
  24. function queryAllByAttribute(attribute, container, text, {
  25. exact = true,
  26. collapseWhitespace,
  27. trim,
  28. normalizer
  29. } = {}) {
  30. const matcher = exact ? _matches.matches : _matches.fuzzyMatches;
  31. const matchNormalizer = (0, _matches.makeNormalizer)({
  32. collapseWhitespace,
  33. trim,
  34. normalizer
  35. });
  36. return Array.from(container.querySelectorAll(`[${attribute}]`)).filter(node => matcher(node.getAttribute(attribute), node, text, matchNormalizer));
  37. }
  38. function queryByAttribute(attribute, container, text, options) {
  39. const els = queryAllByAttribute(attribute, container, text, options);
  40. if (els.length > 1) {
  41. throw getMultipleElementsFoundError(`Found multiple elements by [${attribute}=${text}]`, container);
  42. }
  43. return els[0] || null;
  44. }
  45. // this accepts a query function and returns a function which throws an error
  46. // if more than one elements is returned, otherwise it returns the first
  47. // element or null
  48. function makeSingleQuery(allQuery, getMultipleError) {
  49. return (container, ...args) => {
  50. const els = allQuery(container, ...args);
  51. if (els.length > 1) {
  52. const elementStrings = els.map(element => getElementError(null, element).message).join('\n\n');
  53. throw getMultipleElementsFoundError(`${getMultipleError(container, ...args)}
  54. Here are the matching elements:
  55. ${elementStrings}`, container);
  56. }
  57. return els[0] || null;
  58. };
  59. }
  60. function getSuggestionError(suggestion, container) {
  61. return (0, _config.getConfig)().getElementError(`A better query is available, try this:
  62. ${suggestion.toString()}
  63. `, container);
  64. }
  65. // this accepts a query function and returns a function which throws an error
  66. // if an empty list of elements is returned
  67. function makeGetAllQuery(allQuery, getMissingError) {
  68. return (container, ...args) => {
  69. const els = allQuery(container, ...args);
  70. if (!els.length) {
  71. throw (0, _config.getConfig)().getElementError(getMissingError(container, ...args), container);
  72. }
  73. return els;
  74. };
  75. }
  76. // this accepts a getter query function and returns a function which calls
  77. // waitFor and passing a function which invokes the getter.
  78. function makeFindQuery(getter) {
  79. return (container, text, options, waitForOptions) => {
  80. return (0, _waitFor.waitFor)(() => {
  81. return getter(container, text, options);
  82. }, {
  83. container,
  84. ...waitForOptions
  85. });
  86. };
  87. }
  88. const wrapSingleQueryWithSuggestion = (query, queryAllByName, variant) => (container, ...args) => {
  89. const element = query(container, ...args);
  90. const [{
  91. suggest = (0, _config.getConfig)().throwSuggestions
  92. } = {}] = args.slice(-1);
  93. if (element && suggest) {
  94. const suggestion = (0, _suggestions.getSuggestedQuery)(element, variant);
  95. if (suggestion && !queryAllByName.endsWith(suggestion.queryName)) {
  96. throw getSuggestionError(suggestion.toString(), container);
  97. }
  98. }
  99. return element;
  100. };
  101. exports.wrapSingleQueryWithSuggestion = wrapSingleQueryWithSuggestion;
  102. const wrapAllByQueryWithSuggestion = (query, queryAllByName, variant) => (container, ...args) => {
  103. const els = query(container, ...args);
  104. const [{
  105. suggest = (0, _config.getConfig)().throwSuggestions
  106. } = {}] = args.slice(-1);
  107. if (els.length && suggest) {
  108. // get a unique list of all suggestion messages. We are only going to make a suggestion if
  109. // all the suggestions are the same
  110. const uniqueSuggestionMessages = [...new Set(els.map(element => {
  111. var _getSuggestedQuery;
  112. return (_getSuggestedQuery = (0, _suggestions.getSuggestedQuery)(element, variant)) == null ? void 0 : _getSuggestedQuery.toString();
  113. }))];
  114. if (
  115. // only want to suggest if all the els have the same suggestion.
  116. uniqueSuggestionMessages.length === 1 && !queryAllByName.endsWith(
  117. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- TODO: Can this be null at runtime?
  118. (0, _suggestions.getSuggestedQuery)(els[0], variant).queryName)) {
  119. throw getSuggestionError(uniqueSuggestionMessages[0], container);
  120. }
  121. }
  122. return els;
  123. };
  124. // TODO: This deviates from the published declarations
  125. // However, the implementation always required a dyadic (after `container`) not variadic `queryAllBy` considering the implementation of `makeFindQuery`
  126. // This is at least statically true and can be verified by accepting `QueryMethod<Arguments, HTMLElement[]>`
  127. exports.wrapAllByQueryWithSuggestion = wrapAllByQueryWithSuggestion;
  128. function buildQueries(queryAllBy, getMultipleError, getMissingError) {
  129. const queryBy = wrapSingleQueryWithSuggestion(makeSingleQuery(queryAllBy, getMultipleError), queryAllBy.name, 'query');
  130. const getAllBy = makeGetAllQuery(queryAllBy, getMissingError);
  131. const getBy = makeSingleQuery(getAllBy, getMultipleError);
  132. const getByWithSuggestions = wrapSingleQueryWithSuggestion(getBy, queryAllBy.name, 'get');
  133. const getAllWithSuggestions = wrapAllByQueryWithSuggestion(getAllBy, queryAllBy.name.replace('query', 'get'), 'getAll');
  134. const findAllBy = makeFindQuery(wrapAllByQueryWithSuggestion(getAllBy, queryAllBy.name, 'findAll'));
  135. const findBy = makeFindQuery(wrapSingleQueryWithSuggestion(getBy, queryAllBy.name, 'find'));
  136. return [queryBy, getAllWithSuggestions, getByWithSuggestions, findAllBy, findBy];
  137. }