Skip to content

Commit

Permalink
refactor: replace our custom getAccessibleName with google's accname …
Browse files Browse the repository at this point in the history
…package
  • Loading branch information
mondaychen committed Apr 9, 2024
1 parent df985f6 commit cc3fffc
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 33 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"@emotion/react": "^11.11.1",
"@emotion/styled": "^11.11.0",
"@types/dom-speech-recognition": "^0.0.4",
"accname": "^1.1.0",
"construct-style-sheets-polyfill": "3.1.0",
"formik": "^2.4.5",
"immer": "^10.0.3",
Expand Down
7 changes: 7 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

36 changes: 3 additions & 33 deletions src/pages/content/drawLabels.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { getAccessibleName } from "accname";
import {
VISIBLE_TEXT_ATTRIBUTE_NAME,
ARIA_LABEL_ATTRIBUTE_NAME,
Expand Down Expand Up @@ -120,37 +121,6 @@ function isTouchedElement(elem: Element) {
);
}

function getAriaLabel(elem: Element): string {
// aria-labelledby has higher priority than aria-label
// https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby
if (elem.hasAttribute("aria-labelledby")) {
// use Set to dedupe
const ids = new Set<string>(
elem.getAttribute("aria-labelledby")?.split(" ") ?? [],
);

const label = Array.from(ids)
.map((id: string) => {
const labelElem = document.getElementById(id);
if (labelElem) {
if (isInputElement(labelElem)) {
// for input elements, use the value as the label
return labelElem.value;
}
// doesn't matter if the text is visible or not
return labelElem.textContent ?? "";
}
})
.join(" ")
.trim();

if (label.length > 0) {
return label;
}
}
return elem.getAttribute("aria-label") ?? "";
}

// find the visible text and best-match aria-label of the element
// note that this function has a side effect of writing the attributes in the DOM
function traverseDom(node: Node, selector: string): DomAttrs {
Expand All @@ -166,7 +136,7 @@ function traverseDom(node: Node, selector: string): DomAttrs {
}

let visibleText = "";
let ariaLabel = getAriaLabel(node);
let ariaLabel = getAccessibleName(node);

// skip children of SVGs because they have their own visibility rules
if (node.tagName.toLocaleLowerCase() !== "svg") {
Expand Down Expand Up @@ -293,7 +263,7 @@ function getLabelData(
}
// fallback to use aria-label
if (label.length === 0) {
label = getAriaLabel(elem);
label = getAccessibleName(elem);
}
// fallback to use text content
if (label.length === 0) {
Expand Down

0 comments on commit cc3fffc

Please sign in to comment.