accessible-name-and-description.mjs 18 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
/**
 * implements https://w3c.github.io/accname/
 */
import ArrayFrom from "./polyfills/array.from.mjs";
import SetLike from "./polyfills/SetLike.mjs";
import { hasAnyConcreteRoles, isElement, isHTMLTableCaptionElement, isHTMLInputElement, isHTMLSelectElement, isHTMLTextAreaElement, safeWindow, isHTMLFieldSetElement, isHTMLLegendElement, isHTMLTableElement, isHTMLSlotElement, isSVGSVGElement, isSVGTitleElement, queryIdRefs, getLocalName } from "./util.mjs";
/**
 *  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.
 */

/**
 *
 * @param {string} string -
 * @returns {FlatString} -
 */
function asFlatString(s) {
  return s.trim().replace(/\s\s+/g, " ");
}
/**
 *
 * @param node -
 * @param options - These are not optional to prevent accidentally calling it without options in `computeAccessibleName`
 * @returns {boolean} -
 */


function isHidden(node, getComputedStyleImplementation) {
  if (!isElement(node)) {
    return false;
  }

  if (node.hasAttribute("hidden") || node.getAttribute("aria-hidden") === "true") {
    return true;
  }

  var style = getComputedStyleImplementation(node);
  return style.getPropertyValue("display") === "none" || style.getPropertyValue("visibility") === "hidden";
}
/**
 * @param {Node} node -
 * @returns {boolean} - As defined in step 2E of https://w3c.github.io/accname/#mapping_additional_nd_te
 */


function isControl(node) {
  return hasAnyConcreteRoles(node, ["button", "combobox", "listbox", "textbox"]) || hasAbstractRole(node, "range");
}

function hasAbstractRole(node, role) {
  if (!isElement(node)) {
    return false;
  }

  switch (role) {
    case "range":
      return hasAnyConcreteRoles(node, ["meter", "progressbar", "scrollbar", "slider", "spinbutton"]);

    default:
      throw new TypeError("No knowledge about abstract role '".concat(role, "'. This is likely a bug :("));
  }
}
/**
 * element.querySelectorAll but also considers owned tree
 * @param element
 * @param selectors
 */


function querySelectorAllSubtree(element, selectors) {
  var elements = ArrayFrom(element.querySelectorAll(selectors));
  queryIdRefs(element, "aria-owns").forEach(function (root) {
    // babel transpiles this assuming an iterator
    elements.push.apply(elements, ArrayFrom(root.querySelectorAll(selectors)));
  });
  return elements;
}

function querySelectedOptions(listbox) {
  if (isHTMLSelectElement(listbox)) {
    // IE11 polyfill
    return listbox.selectedOptions || querySelectorAllSubtree(listbox, "[selected]");
  }

  return querySelectorAllSubtree(listbox, '[aria-selected="true"]');
}

function isMarkedPresentational(node) {
  return hasAnyConcreteRoles(node, ["none", "presentation"]);
}
/**
 * Elements specifically listed in html-aam
 *
 * We don't need this for `label` or `legend` elements.
 * Their implicit roles already allow "naming from content".
 *
 * sources:
 *
 * - https://w3c.github.io/html-aam/#table-element
 */


function isNativeHostLanguageTextAlternativeElement(node) {
  return isHTMLTableCaptionElement(node);
}
/**
 * https://w3c.github.io/aria/#namefromcontent
 */


function allowsNameFromContent(node) {
  return hasAnyConcreteRoles(node, ["button", "cell", "checkbox", "columnheader", "gridcell", "heading", "label", "legend", "link", "menuitem", "menuitemcheckbox", "menuitemradio", "option", "radio", "row", "rowheader", "switch", "tab", "tooltip", "treeitem"]);
}
/**
 * TODO https://github.com/eps1lon/dom-accessibility-api/issues/100
 */


function isDescendantOfNativeHostLanguageTextAlternativeElement( // eslint-disable-next-line @typescript-eslint/no-unused-vars -- not implemented yet
node) {
  return false;
}
/**
 * TODO https://github.com/eps1lon/dom-accessibility-api/issues/101
 */
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- not implemented yet


function computeTooltipAttributeValue(node) {
  return null;
}

function getValueOfTextbox(element) {
  if (isHTMLInputElement(element) || isHTMLTextAreaElement(element)) {
    return element.value;
  } // https://github.com/eps1lon/dom-accessibility-api/issues/4


  return element.textContent || "";
}

function getTextualContent(declaration) {
  var content = declaration.getPropertyValue("content");

  if (/^["'].*["']$/.test(content)) {
    return content.slice(1, -1);
  }

  return "";
}
/**
 * https://html.spec.whatwg.org/multipage/forms.html#category-label
 * TODO: form-associated custom elements
 * @param element
 */


function isLabelableElement(element) {
  var localName = getLocalName(element);
  return localName === "button" || localName === "input" && element.getAttribute("type") !== "hidden" || localName === "meter" || localName === "output" || localName === "progress" || localName === "select" || localName === "textarea";
}
/**
 * > [...], then the first such descendant in tree order is the label element's labeled control.
 * -- https://html.spec.whatwg.org/multipage/forms.html#labeled-control
 * @param element
 */


function findLabelableElement(element) {
  if (isLabelableElement(element)) {
    return element;
  }

  var labelableElement = null;
  element.childNodes.forEach(function (childNode) {
    if (labelableElement === null && isElement(childNode)) {
      var descendantLabelableElement = findLabelableElement(childNode);

      if (descendantLabelableElement !== null) {
        labelableElement = descendantLabelableElement;
      }
    }
  });
  return labelableElement;
}
/**
 * Polyfill of HTMLLabelElement.control
 * https://html.spec.whatwg.org/multipage/forms.html#labeled-control
 * @param label
 */


function getControlOfLabel(label) {
  if (label.control !== undefined) {
    return label.control;
  }

  var htmlFor = label.getAttribute("for");

  if (htmlFor !== null) {
    return label.ownerDocument.getElementById(htmlFor);
  }

  return findLabelableElement(label);
}
/**
 * Polyfill of HTMLInputElement.labels
 * https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/labels
 * @param element
 */


function getLabels(element) {
  var labelsProperty = element.labels;

  if (labelsProperty === null) {
    return labelsProperty;
  }

  if (labelsProperty !== undefined) {
    return ArrayFrom(labelsProperty);
  }

  if (!isLabelableElement(element)) {
    return null;
  }

  var document = element.ownerDocument;
  return ArrayFrom(document.querySelectorAll("label")).filter(function (label) {
    return getControlOfLabel(label) === element;
  });
}
/**
 * Gets the contents of a slot used for computing the accname
 * @param slot
 */


function getSlotContents(slot) {
  // Computing the accessible name for elements containing slots is not
  // currently defined in the spec. This implementation reflects the
  // behavior of NVDA 2020.2/Firefox 81 and iOS VoiceOver/Safari 13.6.
  var assignedNodes = slot.assignedNodes();

  if (assignedNodes.length === 0) {
    // if no nodes are assigned to the slot, it displays the default content
    return ArrayFrom(slot.childNodes);
  }

  return assignedNodes;
}
/**
 * implements https://w3c.github.io/accname/#mapping_additional_nd_te
 * @param root
 * @param [options]
 * @param [options.getComputedStyle] - mock window.getComputedStyle. Needs `content`, `display` and `visibility`
 */


export function computeTextAlternative(root) {
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var consultedNodes = new SetLike();
  var window = safeWindow(root);
  var _options$compute = options.compute,
      compute = _options$compute === void 0 ? "name" : _options$compute,
      _options$computedStyl = options.computedStyleSupportsPseudoElements,
      computedStyleSupportsPseudoElements = _options$computedStyl === void 0 ? options.getComputedStyle !== undefined : _options$computedStyl,
      _options$getComputedS = options.getComputedStyle,
      getComputedStyle = _options$getComputedS === void 0 ? window.getComputedStyle.bind(window) : _options$getComputedS; // 2F.i

  function computeMiscTextAlternative(node, context) {
    var accumulatedText = "";

    if (isElement(node) && computedStyleSupportsPseudoElements) {
      var pseudoBefore = getComputedStyle(node, "::before");
      var beforeContent = getTextualContent(pseudoBefore);
      accumulatedText = "".concat(beforeContent, " ").concat(accumulatedText);
    } // FIXME: Including aria-owns is not defined in the spec
    // But it is required in the web-platform-test


    var childNodes = isHTMLSlotElement(node) ? getSlotContents(node) : ArrayFrom(node.childNodes).concat(queryIdRefs(node, "aria-owns"));
    childNodes.forEach(function (child) {
      var result = computeTextAlternative(child, {
        isEmbeddedInLabel: context.isEmbeddedInLabel,
        isReferenced: false,
        recursion: true
      }); // TODO: Unclear why display affects delimiter
      // see https://github.com/w3c/accname/issues/3

      var display = isElement(child) ? getComputedStyle(child).getPropertyValue("display") : "inline";
      var separator = display !== "inline" ? " " : ""; // trailing separator for wpt tests

      accumulatedText += "".concat(separator).concat(result).concat(separator);
    });

    if (isElement(node) && computedStyleSupportsPseudoElements) {
      var pseudoAfter = getComputedStyle(node, "::after");
      var afterContent = getTextualContent(pseudoAfter);
      accumulatedText = "".concat(accumulatedText, " ").concat(afterContent);
    }

    return accumulatedText;
  }

  function computeElementTextAlternative(node) {
    if (!isElement(node)) {
      return null;
    }
    /**
     *
     * @param element
     * @param attributeName
     * @returns A string non-empty string or `null`
     */


    function useAttribute(element, attributeName) {
      var attribute = element.getAttributeNode(attributeName);

      if (attribute !== null && !consultedNodes.has(attribute) && attribute.value.trim() !== "") {
        consultedNodes.add(attribute);
        return attribute.value;
      }

      return null;
    } // https://w3c.github.io/html-aam/#fieldset-and-legend-elements


    if (isHTMLFieldSetElement(node)) {
      consultedNodes.add(node);
      var children = ArrayFrom(node.childNodes);

      for (var i = 0; i < children.length; i += 1) {
        var child = children[i];

        if (isHTMLLegendElement(child)) {
          return computeTextAlternative(child, {
            isEmbeddedInLabel: false,
            isReferenced: false,
            recursion: false
          });
        }
      }
    } else if (isHTMLTableElement(node)) {
      // https://w3c.github.io/html-aam/#table-element
      consultedNodes.add(node);

      var _children = ArrayFrom(node.childNodes);

      for (var _i = 0; _i < _children.length; _i += 1) {
        var _child = _children[_i];

        if (isHTMLTableCaptionElement(_child)) {
          return computeTextAlternative(_child, {
            isEmbeddedInLabel: false,
            isReferenced: false,
            recursion: false
          });
        }
      }
    } else if (isSVGSVGElement(node)) {
      // https://www.w3.org/TR/svg-aam-1.0/
      consultedNodes.add(node);

      var _children2 = ArrayFrom(node.childNodes);

      for (var _i2 = 0; _i2 < _children2.length; _i2 += 1) {
        var _child2 = _children2[_i2];

        if (isSVGTitleElement(_child2)) {
          return _child2.textContent;
        }
      }

      return null;
    } else if (getLocalName(node) === "img" || getLocalName(node) === "area") {
      // https://w3c.github.io/html-aam/#area-element
      // https://w3c.github.io/html-aam/#img-element
      var nameFromAlt = useAttribute(node, "alt");

      if (nameFromAlt !== null) {
        return nameFromAlt;
      }
    }

    if (isHTMLInputElement(node) && (node.type === "button" || node.type === "submit" || node.type === "reset")) {
      // 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
      var nameFromValue = useAttribute(node, "value");

      if (nameFromValue !== null) {
        return nameFromValue;
      } // TODO: l10n


      if (node.type === "submit") {
        return "Submit";
      } // TODO: l10n


      if (node.type === "reset") {
        return "Reset";
      }
    }

    if (isHTMLInputElement(node) || isHTMLSelectElement(node) || isHTMLTextAreaElement(node)) {
      var input = node;
      var labels = getLabels(input);

      if (labels !== null && labels.length !== 0) {
        consultedNodes.add(input);
        return ArrayFrom(labels).map(function (element) {
          return computeTextAlternative(element, {
            isEmbeddedInLabel: true,
            isReferenced: false,
            recursion: true
          });
        }).filter(function (label) {
          return label.length > 0;
        }).join(" ");
      }
    } // https://w3c.github.io/html-aam/#input-type-image-accessible-name-computation
    // TODO: wpt test consider label elements but html-aam does not mention them
    // We follow existing implementations over spec


    if (isHTMLInputElement(node) && node.type === "image") {
      var _nameFromAlt = useAttribute(node, "alt");

      if (_nameFromAlt !== null) {
        return _nameFromAlt;
      }

      var nameFromTitle = useAttribute(node, "title");

      if (nameFromTitle !== null) {
        return nameFromTitle;
      } // TODO: l10n


      return "Submit Query";
    }

    return useAttribute(node, "title");
  }

  function computeTextAlternative(current, context) {
    if (consultedNodes.has(current)) {
      return "";
    } // special casing, cheating to make tests pass
    // https://github.com/w3c/accname/issues/67


    if (hasAnyConcreteRoles(current, ["menu"])) {
      consultedNodes.add(current);
      return "";
    } // 2A


    if (isHidden(current, getComputedStyle) && !context.isReferenced) {
      consultedNodes.add(current);
      return "";
    } // 2B


    var labelElements = queryIdRefs(current, "aria-labelledby");

    if (compute === "name" && !context.isReferenced && labelElements.length > 0) {
      return labelElements.map(function (element) {
        return computeTextAlternative(element, {
          isEmbeddedInLabel: context.isEmbeddedInLabel,
          isReferenced: true,
          // thais isn't recursion as specified, otherwise we would skip
          // `aria-label` in
          // <input id="myself" aria-label="foo" aria-labelledby="myself"
          recursion: false
        });
      }).join(" ");
    } // 2C
    // Changed from the spec in anticipation of https://github.com/w3c/accname/issues/64
    // spec says we should only consider skipping if we have a non-empty label


    var skipToStep2E = context.recursion && isControl(current) && compute === "name";

    if (!skipToStep2E) {
      var ariaLabel = (isElement(current) && current.getAttribute("aria-label") || "").trim();

      if (ariaLabel !== "" && compute === "name") {
        consultedNodes.add(current);
        return ariaLabel;
      } // 2D


      if (!isMarkedPresentational(current)) {
        var elementTextAlternative = computeElementTextAlternative(current);

        if (elementTextAlternative !== null) {
          consultedNodes.add(current);
          return elementTextAlternative;
        }
      }
    } // 2E


    if (skipToStep2E || context.isEmbeddedInLabel || context.isReferenced) {
      if (hasAnyConcreteRoles(current, ["combobox", "listbox"])) {
        consultedNodes.add(current);
        var selectedOptions = querySelectedOptions(current);

        if (selectedOptions.length === 0) {
          // defined per test `name_heading_combobox`
          return isHTMLInputElement(current) ? current.value : "";
        }

        return ArrayFrom(selectedOptions).map(function (selectedOption) {
          return computeTextAlternative(selectedOption, {
            isEmbeddedInLabel: context.isEmbeddedInLabel,
            isReferenced: false,
            recursion: true
          });
        }).join(" ");
      }

      if (hasAbstractRole(current, "range")) {
        consultedNodes.add(current);

        if (current.hasAttribute("aria-valuetext")) {
          // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- safe due to hasAttribute guard
          return current.getAttribute("aria-valuetext");
        }

        if (current.hasAttribute("aria-valuenow")) {
          // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- safe due to hasAttribute guard
          return current.getAttribute("aria-valuenow");
        } // Otherwise, use the value as specified by a host language attribute.


        return current.getAttribute("value") || "";
      }

      if (hasAnyConcreteRoles(current, ["textbox"])) {
        consultedNodes.add(current);
        return getValueOfTextbox(current);
      }
    } // 2F: https://w3c.github.io/accname/#step2F


    if (allowsNameFromContent(current) || isElement(current) && context.isReferenced || isNativeHostLanguageTextAlternativeElement(current) || isDescendantOfNativeHostLanguageTextAlternativeElement(current)) {
      consultedNodes.add(current);
      return computeMiscTextAlternative(current, {
        isEmbeddedInLabel: context.isEmbeddedInLabel,
        isReferenced: false
      });
    }

    if (current.nodeType === current.TEXT_NODE) {
      consultedNodes.add(current);
      return current.textContent || "";
    }

    if (context.recursion) {
      consultedNodes.add(current);
      return computeMiscTextAlternative(current, {
        isEmbeddedInLabel: context.isEmbeddedInLabel,
        isReferenced: false
      });
    }

    var tooltipAttributeValue = computeTooltipAttributeValue(current);

    if (tooltipAttributeValue !== null) {
      consultedNodes.add(current);
      return tooltipAttributeValue;
    } // TODO should this be reachable?


    consultedNodes.add(current);
    return "";
  }

  return asFlatString(computeTextAlternative(root, {
    isEmbeddedInLabel: false,
    // by spec computeAccessibleDescription starts with the referenced elements as roots
    isReferenced: compute === "description",
    recursion: false
  }));
}
//# sourceMappingURL=accessible-name-and-description.mjs.map