Skip to content

Commit 215955e

Browse files
MatanBobieps1lon
andauthored
feat: add an isDisabled function to identify whether elements are disabled or not (#919)
Co-authored-by: Sebastian Silbermann <[email protected]>
1 parent ab4e208 commit 215955e

File tree

4 files changed

+53
-0
lines changed

4 files changed

+53
-0
lines changed

.changeset/rare-cycles-nail.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"dom-accessibility-api": minor
3+
---
4+
5+
add an `isDisabled` function to check if elements are disabled or not

sources/__tests__/is-disabled.js

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import { isDisabled } from "../is-disabled";
2+
import { cleanup, renderIntoDocument } from "./helpers/test-utils";
3+
4+
describe("isDisabled", () => {
5+
afterEach(cleanup);
6+
test.each([
7+
["<button data-test />", false],
8+
['<button data-test aria-disabled="true" />', true],
9+
['<button data-test disabled="true" />', true],
10+
["<button data-test disabled />", true],
11+
['<button data-test aria-disabled="false" />', false],
12+
["<div data-test disabled />", false],
13+
])("markup #%#", (markup, expectedIsDisabled) => {
14+
const container = renderIntoDocument(markup);
15+
expect(container).not.toBe(null);
16+
17+
const testNode = container.querySelector("[data-test]");
18+
expect(isDisabled(testNode)).toBe(expectedIsDisabled);
19+
});
20+
});

sources/index.ts

+1
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@ export { computeAccessibleDescription } from "./accessible-description";
22
export { computeAccessibleName } from "./accessible-name";
33
export { default as getRole } from "./getRole";
44
export * from "./is-inaccessible";
5+
export { isDisabled } from "./is-disabled";

sources/is-disabled.ts

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import { getLocalName } from "./getRole";
2+
3+
const elementsSupportingDisabledAttribute = new Set([
4+
"button",
5+
"fieldset",
6+
"input",
7+
"optgroup",
8+
"option",
9+
"select",
10+
"textarea",
11+
]);
12+
13+
/**
14+
* Check if an element is disabled
15+
* https://www.w3.org/TR/html-aam-1.0/#html-attribute-state-and-property-mappings
16+
* https://www.w3.org/TR/wai-aria-1.1/#aria-disabled
17+
*
18+
* @param element
19+
* @returns {boolean} true if disabled, otherwise false
20+
*/
21+
export function isDisabled(element: Element): boolean {
22+
const localName = getLocalName(element);
23+
return elementsSupportingDisabledAttribute.has(localName) &&
24+
element.hasAttribute("disabled")
25+
? true
26+
: element.getAttribute("aria-disabled") === "true";
27+
}

0 commit comments

Comments
 (0)