Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add an isDisabled function to identify whether elements are disabled or not #919

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/rare-cycles-nail.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"dom-accessibility-api": minor
---

add an `isDisabled` function to check if elements are disabled or not
20 changes: 20 additions & 0 deletions sources/__tests__/is-disabled.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { isDisabled } from "../is-disabled";
import { cleanup, renderIntoDocument } from "./helpers/test-utils";

describe("isDisabled", () => {
afterEach(cleanup);
test.each([
["<button data-test />", false],
['<button data-test aria-disabled="true" />', true],
['<button data-test disabled="true" />', true],
["<button data-test disabled />", true],
['<button data-test aria-disabled="false" />', false],
["<div data-test disabled />", false],
])("markup #%#", (markup, expectedIsDisabled) => {
const container = renderIntoDocument(markup);
expect(container).not.toBe(null);

const testNode = container.querySelector("[data-test]");
expect(isDisabled(testNode)).toBe(expectedIsDisabled);
});
});
1 change: 1 addition & 0 deletions sources/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ export { computeAccessibleDescription } from "./accessible-description";
export { computeAccessibleName } from "./accessible-name";
export { default as getRole } from "./getRole";
export * from "./is-inaccessible";
export { isDisabled } from "./is-disabled";
27 changes: 27 additions & 0 deletions sources/is-disabled.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { getLocalName } from "./getRole";

const elementsSupportingDisabledAttribute = new Set([
"button",
"fieldset",
"input",
"optgroup",
"option",
"select",
"textarea",
]);

/**
* Check if an element is disabled
* https://www.w3.org/TR/html-aam-1.0/#html-attribute-state-and-property-mappings
* https://www.w3.org/TR/wai-aria-1.1/#aria-disabled
*
* @param element
* @returns {boolean} true if disabled, otherwise false
*/
export function isDisabled(element: Element): boolean {
const localName = getLocalName(element);
return elementsSupportingDisabledAttribute.has(localName) &&
element.hasAttribute("disabled")
? true
: element.getAttribute("aria-disabled") === "true";
}