web 3d图形渲染器
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

587 lines
18 KiB

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