accessible-name-and-description.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. "use strict";
  2. exports.__esModule = true;
  3. exports.computeTextAlternative = computeTextAlternative;
  4. var _array = _interopRequireDefault(require("./polyfills/array.from"));
  5. var _SetLike = _interopRequireDefault(require("./polyfills/SetLike"));
  6. var _util = require("./util");
  7. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  8. /**
  9. * implements https://w3c.github.io/accname/
  10. */
  11. /**
  12. *
  13. * @param {string} string -
  14. * @returns {FlatString} -
  15. */
  16. function asFlatString(s) {
  17. return s.trim().replace(/\s\s+/g, " ");
  18. }
  19. /**
  20. *
  21. * @param node -
  22. * @param options - These are not optional to prevent accidentally calling it without options in `computeAccessibleName`
  23. * @returns {boolean} -
  24. */
  25. function isHidden(node, getComputedStyleImplementation) {
  26. if (!(0, _util.isElement)(node)) {
  27. return false;
  28. }
  29. if (node.hasAttribute("hidden") || node.getAttribute("aria-hidden") === "true") {
  30. return true;
  31. }
  32. var style = getComputedStyleImplementation(node);
  33. return style.getPropertyValue("display") === "none" || style.getPropertyValue("visibility") === "hidden";
  34. }
  35. /**
  36. * @param {Node} node -
  37. * @returns {boolean} - As defined in step 2E of https://w3c.github.io/accname/#mapping_additional_nd_te
  38. */
  39. function isControl(node) {
  40. return (0, _util.hasAnyConcreteRoles)(node, ["button", "combobox", "listbox", "textbox"]) || hasAbstractRole(node, "range");
  41. }
  42. function hasAbstractRole(node, role) {
  43. if (!(0, _util.isElement)(node)) {
  44. return false;
  45. }
  46. switch (role) {
  47. case "range":
  48. return (0, _util.hasAnyConcreteRoles)(node, ["meter", "progressbar", "scrollbar", "slider", "spinbutton"]);
  49. default:
  50. throw new TypeError("No knowledge about abstract role '".concat(role, "'. This is likely a bug :("));
  51. }
  52. }
  53. /**
  54. * element.querySelectorAll but also considers owned tree
  55. * @param element
  56. * @param selectors
  57. */
  58. function querySelectorAllSubtree(element, selectors) {
  59. var elements = (0, _array.default)(element.querySelectorAll(selectors));
  60. (0, _util.queryIdRefs)(element, "aria-owns").forEach(function (root) {
  61. // babel transpiles this assuming an iterator
  62. elements.push.apply(elements, (0, _array.default)(root.querySelectorAll(selectors)));
  63. });
  64. return elements;
  65. }
  66. function querySelectedOptions(listbox) {
  67. if ((0, _util.isHTMLSelectElement)(listbox)) {
  68. // IE11 polyfill
  69. return listbox.selectedOptions || querySelectorAllSubtree(listbox, "[selected]");
  70. }
  71. return querySelectorAllSubtree(listbox, '[aria-selected="true"]');
  72. }
  73. function isMarkedPresentational(node) {
  74. return (0, _util.hasAnyConcreteRoles)(node, ["none", "presentation"]);
  75. }
  76. /**
  77. * Elements specifically listed in html-aam
  78. *
  79. * We don't need this for `label` or `legend` elements.
  80. * Their implicit roles already allow "naming from content".
  81. *
  82. * sources:
  83. *
  84. * - https://w3c.github.io/html-aam/#table-element
  85. */
  86. function isNativeHostLanguageTextAlternativeElement(node) {
  87. return (0, _util.isHTMLTableCaptionElement)(node);
  88. }
  89. /**
  90. * https://w3c.github.io/aria/#namefromcontent
  91. */
  92. function allowsNameFromContent(node) {
  93. return (0, _util.hasAnyConcreteRoles)(node, ["button", "cell", "checkbox", "columnheader", "gridcell", "heading", "label", "legend", "link", "menuitem", "menuitemcheckbox", "menuitemradio", "option", "radio", "row", "rowheader", "switch", "tab", "tooltip", "treeitem"]);
  94. }
  95. /**
  96. * TODO https://github.com/eps1lon/dom-accessibility-api/issues/100
  97. */
  98. function isDescendantOfNativeHostLanguageTextAlternativeElement( // eslint-disable-next-line @typescript-eslint/no-unused-vars -- not implemented yet
  99. node) {
  100. return false;
  101. }
  102. /**
  103. * TODO https://github.com/eps1lon/dom-accessibility-api/issues/101
  104. */
  105. // eslint-disable-next-line @typescript-eslint/no-unused-vars -- not implemented yet
  106. function computeTooltipAttributeValue(node) {
  107. return null;
  108. }
  109. function getValueOfTextbox(element) {
  110. if ((0, _util.isHTMLInputElement)(element) || (0, _util.isHTMLTextAreaElement)(element)) {
  111. return element.value;
  112. } // https://github.com/eps1lon/dom-accessibility-api/issues/4
  113. return element.textContent || "";
  114. }
  115. function getTextualContent(declaration) {
  116. var content = declaration.getPropertyValue("content");
  117. if (/^["'].*["']$/.test(content)) {
  118. return content.slice(1, -1);
  119. }
  120. return "";
  121. }
  122. /**
  123. * https://html.spec.whatwg.org/multipage/forms.html#category-label
  124. * TODO: form-associated custom elements
  125. * @param element
  126. */
  127. function isLabelableElement(element) {
  128. var localName = (0, _util.getLocalName)(element);
  129. return localName === "button" || localName === "input" && element.getAttribute("type") !== "hidden" || localName === "meter" || localName === "output" || localName === "progress" || localName === "select" || localName === "textarea";
  130. }
  131. /**
  132. * > [...], then the first such descendant in tree order is the label element's labeled control.
  133. * -- https://html.spec.whatwg.org/multipage/forms.html#labeled-control
  134. * @param element
  135. */
  136. function findLabelableElement(element) {
  137. if (isLabelableElement(element)) {
  138. return element;
  139. }
  140. var labelableElement = null;
  141. element.childNodes.forEach(function (childNode) {
  142. if (labelableElement === null && (0, _util.isElement)(childNode)) {
  143. var descendantLabelableElement = findLabelableElement(childNode);
  144. if (descendantLabelableElement !== null) {
  145. labelableElement = descendantLabelableElement;
  146. }
  147. }
  148. });
  149. return labelableElement;
  150. }
  151. /**
  152. * Polyfill of HTMLLabelElement.control
  153. * https://html.spec.whatwg.org/multipage/forms.html#labeled-control
  154. * @param label
  155. */
  156. function getControlOfLabel(label) {
  157. if (label.control !== undefined) {
  158. return label.control;
  159. }
  160. var htmlFor = label.getAttribute("for");
  161. if (htmlFor !== null) {
  162. return label.ownerDocument.getElementById(htmlFor);
  163. }
  164. return findLabelableElement(label);
  165. }
  166. /**
  167. * Polyfill of HTMLInputElement.labels
  168. * https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/labels
  169. * @param element
  170. */
  171. function getLabels(element) {
  172. var labelsProperty = element.labels;
  173. if (labelsProperty === null) {
  174. return labelsProperty;
  175. }
  176. if (labelsProperty !== undefined) {
  177. return (0, _array.default)(labelsProperty);
  178. } // polyfill
  179. if (!isLabelableElement(element)) {
  180. return null;
  181. }
  182. var document = element.ownerDocument;
  183. return (0, _array.default)(document.querySelectorAll("label")).filter(function (label) {
  184. return getControlOfLabel(label) === element;
  185. });
  186. }
  187. /**
  188. * Gets the contents of a slot used for computing the accname
  189. * @param slot
  190. */
  191. function getSlotContents(slot) {
  192. // Computing the accessible name for elements containing slots is not
  193. // currently defined in the spec. This implementation reflects the
  194. // behavior of NVDA 2020.2/Firefox 81 and iOS VoiceOver/Safari 13.6.
  195. var assignedNodes = slot.assignedNodes();
  196. if (assignedNodes.length === 0) {
  197. // if no nodes are assigned to the slot, it displays the default content
  198. return (0, _array.default)(slot.childNodes);
  199. }
  200. return assignedNodes;
  201. }
  202. /**
  203. * implements https://w3c.github.io/accname/#mapping_additional_nd_te
  204. * @param root
  205. * @param [options]
  206. * @param [options.getComputedStyle] - mock window.getComputedStyle. Needs `content`, `display` and `visibility`
  207. */
  208. function computeTextAlternative(root) {
  209. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  210. var consultedNodes = new _SetLike.default();
  211. var window = (0, _util.safeWindow)(root);
  212. var _options$compute = options.compute,
  213. compute = _options$compute === void 0 ? "name" : _options$compute,
  214. _options$computedStyl = options.computedStyleSupportsPseudoElements,
  215. computedStyleSupportsPseudoElements = _options$computedStyl === void 0 ? options.getComputedStyle !== undefined : _options$computedStyl,
  216. _options$getComputedS = options.getComputedStyle,
  217. getComputedStyle = _options$getComputedS === void 0 ? window.getComputedStyle.bind(window) : _options$getComputedS; // 2F.i
  218. function computeMiscTextAlternative(node, context) {
  219. var accumulatedText = "";
  220. if ((0, _util.isElement)(node) && computedStyleSupportsPseudoElements) {
  221. var pseudoBefore = getComputedStyle(node, "::before");
  222. var beforeContent = getTextualContent(pseudoBefore);
  223. accumulatedText = "".concat(beforeContent, " ").concat(accumulatedText);
  224. } // FIXME: Including aria-owns is not defined in the spec
  225. // But it is required in the web-platform-test
  226. var childNodes = (0, _util.isHTMLSlotElement)(node) ? getSlotContents(node) : (0, _array.default)(node.childNodes).concat((0, _util.queryIdRefs)(node, "aria-owns"));
  227. childNodes.forEach(function (child) {
  228. var result = computeTextAlternative(child, {
  229. isEmbeddedInLabel: context.isEmbeddedInLabel,
  230. isReferenced: false,
  231. recursion: true
  232. }); // TODO: Unclear why display affects delimiter
  233. // see https://github.com/w3c/accname/issues/3
  234. var display = (0, _util.isElement)(child) ? getComputedStyle(child).getPropertyValue("display") : "inline";
  235. var separator = display !== "inline" ? " " : ""; // trailing separator for wpt tests
  236. accumulatedText += "".concat(separator).concat(result).concat(separator);
  237. });
  238. if ((0, _util.isElement)(node) && computedStyleSupportsPseudoElements) {
  239. var pseudoAfter = getComputedStyle(node, "::after");
  240. var afterContent = getTextualContent(pseudoAfter);
  241. accumulatedText = "".concat(accumulatedText, " ").concat(afterContent);
  242. }
  243. return accumulatedText;
  244. }
  245. function computeElementTextAlternative(node) {
  246. if (!(0, _util.isElement)(node)) {
  247. return null;
  248. }
  249. /**
  250. *
  251. * @param element
  252. * @param attributeName
  253. * @returns A string non-empty string or `null`
  254. */
  255. function useAttribute(element, attributeName) {
  256. var attribute = element.getAttributeNode(attributeName);
  257. if (attribute !== null && !consultedNodes.has(attribute) && attribute.value.trim() !== "") {
  258. consultedNodes.add(attribute);
  259. return attribute.value;
  260. }
  261. return null;
  262. } // https://w3c.github.io/html-aam/#fieldset-and-legend-elements
  263. if ((0, _util.isHTMLFieldSetElement)(node)) {
  264. consultedNodes.add(node);
  265. var children = (0, _array.default)(node.childNodes);
  266. for (var i = 0; i < children.length; i += 1) {
  267. var child = children[i];
  268. if ((0, _util.isHTMLLegendElement)(child)) {
  269. return computeTextAlternative(child, {
  270. isEmbeddedInLabel: false,
  271. isReferenced: false,
  272. recursion: false
  273. });
  274. }
  275. }
  276. } else if ((0, _util.isHTMLTableElement)(node)) {
  277. // https://w3c.github.io/html-aam/#table-element
  278. consultedNodes.add(node);
  279. var _children = (0, _array.default)(node.childNodes);
  280. for (var _i = 0; _i < _children.length; _i += 1) {
  281. var _child = _children[_i];
  282. if ((0, _util.isHTMLTableCaptionElement)(_child)) {
  283. return computeTextAlternative(_child, {
  284. isEmbeddedInLabel: false,
  285. isReferenced: false,
  286. recursion: false
  287. });
  288. }
  289. }
  290. } else if ((0, _util.isSVGSVGElement)(node)) {
  291. // https://www.w3.org/TR/svg-aam-1.0/
  292. consultedNodes.add(node);
  293. var _children2 = (0, _array.default)(node.childNodes);
  294. for (var _i2 = 0; _i2 < _children2.length; _i2 += 1) {
  295. var _child2 = _children2[_i2];
  296. if ((0, _util.isSVGTitleElement)(_child2)) {
  297. return _child2.textContent;
  298. }
  299. }
  300. return null;
  301. } else if ((0, _util.getLocalName)(node) === "img" || (0, _util.getLocalName)(node) === "area") {
  302. // https://w3c.github.io/html-aam/#area-element
  303. // https://w3c.github.io/html-aam/#img-element
  304. var nameFromAlt = useAttribute(node, "alt");
  305. if (nameFromAlt !== null) {
  306. return nameFromAlt;
  307. }
  308. } else if ((0, _util.isHTMLOptGroupElement)(node)) {
  309. var nameFromLabel = useAttribute(node, "label");
  310. if (nameFromLabel !== null) {
  311. return nameFromLabel;
  312. }
  313. }
  314. if ((0, _util.isHTMLInputElement)(node) && (node.type === "button" || node.type === "submit" || node.type === "reset")) {
  315. // https://w3c.github.io/html-aam/#input-type-text-input-type-password-input-type-search-input-type-tel-input-type-email-input-type-url-and-textarea-element-accessible-description-computation
  316. var nameFromValue = useAttribute(node, "value");
  317. if (nameFromValue !== null) {
  318. return nameFromValue;
  319. } // TODO: l10n
  320. if (node.type === "submit") {
  321. return "Submit";
  322. } // TODO: l10n
  323. if (node.type === "reset") {
  324. return "Reset";
  325. }
  326. }
  327. var labels = getLabels(node);
  328. if (labels !== null && labels.length !== 0) {
  329. consultedNodes.add(node);
  330. return (0, _array.default)(labels).map(function (element) {
  331. return computeTextAlternative(element, {
  332. isEmbeddedInLabel: true,
  333. isReferenced: false,
  334. recursion: true
  335. });
  336. }).filter(function (label) {
  337. return label.length > 0;
  338. }).join(" ");
  339. } // https://w3c.github.io/html-aam/#input-type-image-accessible-name-computation
  340. // TODO: wpt test consider label elements but html-aam does not mention them
  341. // We follow existing implementations over spec
  342. if ((0, _util.isHTMLInputElement)(node) && node.type === "image") {
  343. var _nameFromAlt = useAttribute(node, "alt");
  344. if (_nameFromAlt !== null) {
  345. return _nameFromAlt;
  346. }
  347. var nameFromTitle = useAttribute(node, "title");
  348. if (nameFromTitle !== null) {
  349. return nameFromTitle;
  350. } // TODO: l10n
  351. return "Submit Query";
  352. }
  353. return useAttribute(node, "title");
  354. }
  355. function computeTextAlternative(current, context) {
  356. if (consultedNodes.has(current)) {
  357. return "";
  358. } // special casing, cheating to make tests pass
  359. // https://github.com/w3c/accname/issues/67
  360. if ((0, _util.hasAnyConcreteRoles)(current, ["menu"])) {
  361. consultedNodes.add(current);
  362. return "";
  363. } // 2A
  364. if (isHidden(current, getComputedStyle) && !context.isReferenced) {
  365. consultedNodes.add(current);
  366. return "";
  367. } // 2B
  368. var labelElements = (0, _util.queryIdRefs)(current, "aria-labelledby");
  369. if (compute === "name" && !context.isReferenced && labelElements.length > 0) {
  370. return labelElements.map(function (element) {
  371. return computeTextAlternative(element, {
  372. isEmbeddedInLabel: context.isEmbeddedInLabel,
  373. isReferenced: true,
  374. // thais isn't recursion as specified, otherwise we would skip
  375. // `aria-label` in
  376. // <input id="myself" aria-label="foo" aria-labelledby="myself"
  377. recursion: false
  378. });
  379. }).join(" ");
  380. } // 2C
  381. // Changed from the spec in anticipation of https://github.com/w3c/accname/issues/64
  382. // spec says we should only consider skipping if we have a non-empty label
  383. var skipToStep2E = context.recursion && isControl(current) && compute === "name";
  384. if (!skipToStep2E) {
  385. var ariaLabel = ((0, _util.isElement)(current) && current.getAttribute("aria-label") || "").trim();
  386. if (ariaLabel !== "" && compute === "name") {
  387. consultedNodes.add(current);
  388. return ariaLabel;
  389. } // 2D
  390. if (!isMarkedPresentational(current)) {
  391. var elementTextAlternative = computeElementTextAlternative(current);
  392. if (elementTextAlternative !== null) {
  393. consultedNodes.add(current);
  394. return elementTextAlternative;
  395. }
  396. }
  397. } // 2E
  398. if (skipToStep2E || context.isEmbeddedInLabel || context.isReferenced) {
  399. if ((0, _util.hasAnyConcreteRoles)(current, ["combobox", "listbox"])) {
  400. consultedNodes.add(current);
  401. var selectedOptions = querySelectedOptions(current);
  402. if (selectedOptions.length === 0) {
  403. // defined per test `name_heading_combobox`
  404. return (0, _util.isHTMLInputElement)(current) ? current.value : "";
  405. }
  406. return (0, _array.default)(selectedOptions).map(function (selectedOption) {
  407. return computeTextAlternative(selectedOption, {
  408. isEmbeddedInLabel: context.isEmbeddedInLabel,
  409. isReferenced: false,
  410. recursion: true
  411. });
  412. }).join(" ");
  413. }
  414. if (hasAbstractRole(current, "range")) {
  415. consultedNodes.add(current);
  416. if (current.hasAttribute("aria-valuetext")) {
  417. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- safe due to hasAttribute guard
  418. return current.getAttribute("aria-valuetext");
  419. }
  420. if (current.hasAttribute("aria-valuenow")) {
  421. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- safe due to hasAttribute guard
  422. return current.getAttribute("aria-valuenow");
  423. } // Otherwise, use the value as specified by a host language attribute.
  424. return current.getAttribute("value") || "";
  425. }
  426. if ((0, _util.hasAnyConcreteRoles)(current, ["textbox"])) {
  427. consultedNodes.add(current);
  428. return getValueOfTextbox(current);
  429. }
  430. } // 2F: https://w3c.github.io/accname/#step2F
  431. if (allowsNameFromContent(current) || (0, _util.isElement)(current) && context.isReferenced || isNativeHostLanguageTextAlternativeElement(current) || isDescendantOfNativeHostLanguageTextAlternativeElement(current)) {
  432. consultedNodes.add(current);
  433. return computeMiscTextAlternative(current, {
  434. isEmbeddedInLabel: context.isEmbeddedInLabel,
  435. isReferenced: false
  436. });
  437. }
  438. if (current.nodeType === current.TEXT_NODE) {
  439. consultedNodes.add(current);
  440. return current.textContent || "";
  441. }
  442. if (context.recursion) {
  443. consultedNodes.add(current);
  444. return computeMiscTextAlternative(current, {
  445. isEmbeddedInLabel: context.isEmbeddedInLabel,
  446. isReferenced: false
  447. });
  448. }
  449. var tooltipAttributeValue = computeTooltipAttributeValue(current);
  450. if (tooltipAttributeValue !== null) {
  451. consultedNodes.add(current);
  452. return tooltipAttributeValue;
  453. } // TODO should this be reachable?
  454. consultedNodes.add(current);
  455. return "";
  456. }
  457. return asFlatString(computeTextAlternative(root, {
  458. isEmbeddedInLabel: false,
  459. // by spec computeAccessibleDescription starts with the referenced elements as roots
  460. isReferenced: compute === "description",
  461. recursion: false
  462. }));
  463. }
  464. //# sourceMappingURL=accessible-name-and-description.js.map