role.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.queryByRole = exports.queryAllByRole = exports.getByRole = exports.getAllByRole = exports.findByRole = exports.findAllByRole = void 0;
  6. var _domAccessibilityApi = require("dom-accessibility-api");
  7. var _ariaQuery = require("aria-query");
  8. var _roleHelpers = require("../role-helpers");
  9. var _queryHelpers = require("../query-helpers");
  10. var _helpers = require("../helpers");
  11. var _allUtils = require("./all-utils");
  12. /* eslint-disable complexity */
  13. const queryAllByRole = (container, role, {
  14. hidden = (0, _allUtils.getConfig)().defaultHidden,
  15. name,
  16. description,
  17. queryFallbacks = false,
  18. selected,
  19. busy,
  20. checked,
  21. pressed,
  22. current,
  23. level,
  24. expanded,
  25. value: {
  26. now: valueNow,
  27. min: valueMin,
  28. max: valueMax,
  29. text: valueText
  30. } = {}
  31. } = {}) => {
  32. (0, _helpers.checkContainerType)(container);
  33. if (selected !== undefined) {
  34. // guard against unknown roles
  35. if (_ariaQuery.roles.get(role)?.props['aria-selected'] === undefined) {
  36. throw new Error(`"aria-selected" is not supported on role "${role}".`);
  37. }
  38. }
  39. if (busy !== undefined) {
  40. // guard against unknown roles
  41. if (_ariaQuery.roles.get(role)?.props['aria-busy'] === undefined) {
  42. throw new Error(`"aria-busy" is not supported on role "${role}".`);
  43. }
  44. }
  45. if (checked !== undefined) {
  46. // guard against unknown roles
  47. if (_ariaQuery.roles.get(role)?.props['aria-checked'] === undefined) {
  48. throw new Error(`"aria-checked" is not supported on role "${role}".`);
  49. }
  50. }
  51. if (pressed !== undefined) {
  52. // guard against unknown roles
  53. if (_ariaQuery.roles.get(role)?.props['aria-pressed'] === undefined) {
  54. throw new Error(`"aria-pressed" is not supported on role "${role}".`);
  55. }
  56. }
  57. if (current !== undefined) {
  58. /* istanbul ignore next */
  59. // guard against unknown roles
  60. // All currently released ARIA versions support `aria-current` on all roles.
  61. // Leaving this for symmetry and forward compatibility
  62. if (_ariaQuery.roles.get(role)?.props['aria-current'] === undefined) {
  63. throw new Error(`"aria-current" is not supported on role "${role}".`);
  64. }
  65. }
  66. if (level !== undefined) {
  67. // guard against using `level` option with any role other than `heading`
  68. if (role !== 'heading') {
  69. throw new Error(`Role "${role}" cannot have "level" property.`);
  70. }
  71. }
  72. if (valueNow !== undefined) {
  73. // guard against unknown roles
  74. if (_ariaQuery.roles.get(role)?.props['aria-valuenow'] === undefined) {
  75. throw new Error(`"aria-valuenow" is not supported on role "${role}".`);
  76. }
  77. }
  78. if (valueMax !== undefined) {
  79. // guard against unknown roles
  80. if (_ariaQuery.roles.get(role)?.props['aria-valuemax'] === undefined) {
  81. throw new Error(`"aria-valuemax" is not supported on role "${role}".`);
  82. }
  83. }
  84. if (valueMin !== undefined) {
  85. // guard against unknown roles
  86. if (_ariaQuery.roles.get(role)?.props['aria-valuemin'] === undefined) {
  87. throw new Error(`"aria-valuemin" is not supported on role "${role}".`);
  88. }
  89. }
  90. if (valueText !== undefined) {
  91. // guard against unknown roles
  92. if (_ariaQuery.roles.get(role)?.props['aria-valuetext'] === undefined) {
  93. throw new Error(`"aria-valuetext" is not supported on role "${role}".`);
  94. }
  95. }
  96. if (expanded !== undefined) {
  97. // guard against unknown roles
  98. if (_ariaQuery.roles.get(role)?.props['aria-expanded'] === undefined) {
  99. throw new Error(`"aria-expanded" is not supported on role "${role}".`);
  100. }
  101. }
  102. const subtreeIsInaccessibleCache = new WeakMap();
  103. function cachedIsSubtreeInaccessible(element) {
  104. if (!subtreeIsInaccessibleCache.has(element)) {
  105. subtreeIsInaccessibleCache.set(element, (0, _roleHelpers.isSubtreeInaccessible)(element));
  106. }
  107. return subtreeIsInaccessibleCache.get(element);
  108. }
  109. return Array.from(container.querySelectorAll(
  110. // Only query elements that can be matched by the following filters
  111. makeRoleSelector(role))).filter(node => {
  112. const isRoleSpecifiedExplicitly = node.hasAttribute('role');
  113. if (isRoleSpecifiedExplicitly) {
  114. const roleValue = node.getAttribute('role');
  115. if (queryFallbacks) {
  116. return roleValue.split(' ').filter(Boolean).some(roleAttributeToken => roleAttributeToken === role);
  117. }
  118. // other wise only send the first token to match
  119. const [firstRoleAttributeToken] = roleValue.split(' ');
  120. return firstRoleAttributeToken === role;
  121. }
  122. const implicitRoles = (0, _roleHelpers.getImplicitAriaRoles)(node);
  123. return implicitRoles.some(implicitRole => {
  124. return implicitRole === role;
  125. });
  126. }).filter(element => {
  127. if (selected !== undefined) {
  128. return selected === (0, _roleHelpers.computeAriaSelected)(element);
  129. }
  130. if (busy !== undefined) {
  131. return busy === (0, _roleHelpers.computeAriaBusy)(element);
  132. }
  133. if (checked !== undefined) {
  134. return checked === (0, _roleHelpers.computeAriaChecked)(element);
  135. }
  136. if (pressed !== undefined) {
  137. return pressed === (0, _roleHelpers.computeAriaPressed)(element);
  138. }
  139. if (current !== undefined) {
  140. return current === (0, _roleHelpers.computeAriaCurrent)(element);
  141. }
  142. if (expanded !== undefined) {
  143. return expanded === (0, _roleHelpers.computeAriaExpanded)(element);
  144. }
  145. if (level !== undefined) {
  146. return level === (0, _roleHelpers.computeHeadingLevel)(element);
  147. }
  148. if (valueNow !== undefined || valueMax !== undefined || valueMin !== undefined || valueText !== undefined) {
  149. let valueMatches = true;
  150. if (valueNow !== undefined) {
  151. valueMatches &&= valueNow === (0, _roleHelpers.computeAriaValueNow)(element);
  152. }
  153. if (valueMax !== undefined) {
  154. valueMatches &&= valueMax === (0, _roleHelpers.computeAriaValueMax)(element);
  155. }
  156. if (valueMin !== undefined) {
  157. valueMatches &&= valueMin === (0, _roleHelpers.computeAriaValueMin)(element);
  158. }
  159. if (valueText !== undefined) {
  160. valueMatches &&= (0, _allUtils.matches)((0, _roleHelpers.computeAriaValueText)(element) ?? null, element, valueText, text => text);
  161. }
  162. return valueMatches;
  163. }
  164. // don't care if aria attributes are unspecified
  165. return true;
  166. }).filter(element => {
  167. if (name === undefined) {
  168. // Don't care
  169. return true;
  170. }
  171. return (0, _allUtils.matches)((0, _domAccessibilityApi.computeAccessibleName)(element, {
  172. computedStyleSupportsPseudoElements: (0, _allUtils.getConfig)().computedStyleSupportsPseudoElements
  173. }), element, name, text => text);
  174. }).filter(element => {
  175. if (description === undefined) {
  176. // Don't care
  177. return true;
  178. }
  179. return (0, _allUtils.matches)((0, _domAccessibilityApi.computeAccessibleDescription)(element, {
  180. computedStyleSupportsPseudoElements: (0, _allUtils.getConfig)().computedStyleSupportsPseudoElements
  181. }), element, description, text => text);
  182. }).filter(element => {
  183. return hidden === false ? (0, _roleHelpers.isInaccessible)(element, {
  184. isSubtreeInaccessible: cachedIsSubtreeInaccessible
  185. }) === false : true;
  186. });
  187. };
  188. function makeRoleSelector(role) {
  189. const explicitRoleSelector = `*[role~="${role}"]`;
  190. const roleRelations = _ariaQuery.roleElements.get(role) ?? new Set();
  191. const implicitRoleSelectors = new Set(Array.from(roleRelations).map(({
  192. name
  193. }) => name));
  194. // Current transpilation config sometimes assumes `...` is always applied to arrays.
  195. // `...` is equivalent to `Array.prototype.concat` for arrays.
  196. // If you replace this code with `[explicitRoleSelector, ...implicitRoleSelectors]`, make sure every transpilation target retains the `...` in favor of `Array.prototype.concat`.
  197. return [explicitRoleSelector].concat(Array.from(implicitRoleSelectors)).join(',');
  198. }
  199. const getNameHint = name => {
  200. let nameHint = '';
  201. if (name === undefined) {
  202. nameHint = '';
  203. } else if (typeof name === 'string') {
  204. nameHint = ` and name "${name}"`;
  205. } else {
  206. nameHint = ` and name \`${name}\``;
  207. }
  208. return nameHint;
  209. };
  210. const getMultipleError = (c, role, {
  211. name
  212. } = {}) => {
  213. return `Found multiple elements with the role "${role}"${getNameHint(name)}`;
  214. };
  215. const getMissingError = (container, role, {
  216. hidden = (0, _allUtils.getConfig)().defaultHidden,
  217. name,
  218. description
  219. } = {}) => {
  220. if ((0, _allUtils.getConfig)()._disableExpensiveErrorDiagnostics) {
  221. return `Unable to find role="${role}"${getNameHint(name)}`;
  222. }
  223. let roles = '';
  224. Array.from(container.children).forEach(childElement => {
  225. roles += (0, _roleHelpers.prettyRoles)(childElement, {
  226. hidden,
  227. includeDescription: description !== undefined
  228. });
  229. });
  230. let roleMessage;
  231. if (roles.length === 0) {
  232. if (hidden === false) {
  233. roleMessage = 'There are no accessible roles. But there might be some inaccessible roles. ' + 'If you wish to access them, then set the `hidden` option to `true`. ' + 'Learn more about this here: https://testing-library.com/docs/dom-testing-library/api-queries#byrole';
  234. } else {
  235. roleMessage = 'There are no available roles.';
  236. }
  237. } else {
  238. roleMessage = `
  239. Here are the ${hidden === false ? 'accessible' : 'available'} roles:
  240. ${roles.replace(/\n/g, '\n ').replace(/\n\s\s\n/g, '\n\n')}
  241. `.trim();
  242. }
  243. let nameHint = '';
  244. if (name === undefined) {
  245. nameHint = '';
  246. } else if (typeof name === 'string') {
  247. nameHint = ` and name "${name}"`;
  248. } else {
  249. nameHint = ` and name \`${name}\``;
  250. }
  251. let descriptionHint = '';
  252. if (description === undefined) {
  253. descriptionHint = '';
  254. } else if (typeof description === 'string') {
  255. descriptionHint = ` and description "${description}"`;
  256. } else {
  257. descriptionHint = ` and description \`${description}\``;
  258. }
  259. return `
  260. Unable to find an ${hidden === false ? 'accessible ' : ''}element with the role "${role}"${nameHint}${descriptionHint}
  261. ${roleMessage}`.trim();
  262. };
  263. const queryAllByRoleWithSuggestions = exports.queryAllByRole = (0, _queryHelpers.wrapAllByQueryWithSuggestion)(queryAllByRole, queryAllByRole.name, 'queryAll');
  264. const [queryByRole, getAllByRole, getByRole, findAllByRole, findByRole] = (0, _allUtils.buildQueries)(queryAllByRole, getMultipleError, getMissingError);
  265. exports.findByRole = findByRole;
  266. exports.findAllByRole = findAllByRole;
  267. exports.getByRole = getByRole;
  268. exports.getAllByRole = getAllByRole;
  269. exports.queryByRole = queryByRole;