Skip to content

Commit

Permalink
fix role "switch" requiring "aria-checked" when used with native inpu…
Browse files Browse the repository at this point in the history
…t element (#1071)

* fix #932 not required switch prop

* extended comment

Closes #932
  • Loading branch information
JoCa96 authored Apr 24, 2024
1 parent d56bc42 commit 7395e00
Showing 2 changed files with 34 additions and 1 deletion.
10 changes: 10 additions & 0 deletions src/rules/__tests__/role-has-required-aria-props.test.ts
Original file line number Diff line number Diff line change
@@ -3,11 +3,21 @@ import makeRuleTester from "./makeRuleTester";

makeRuleTester("role-has-required-aria-props", rule, {
valid: [
"<input role='switch' type='checkbox' aria-labelledby='test' />",
"<span role='checkbox' aria-checked='false' aria-labelledby='test' tabindex='0' />",
"<span :role='role' aria-checked='false' aria-labelledby='test' tabindex='0' />",
"<span :role='role' />"
],
invalid: [
{
code: "<input role='switch' aria-labelledby='test' />",
errors: [
{
messageId: "default",
data: { role: "switch", attributes: "aria-checked" }
}
]
},
{
code: "<span role='checkbox' aria-labelledby='test' tabindex='0' />",
errors: [
25 changes: 24 additions & 1 deletion src/rules/role-has-required-aria-props.ts
Original file line number Diff line number Diff line change
@@ -18,6 +18,24 @@ function isAriaRoleDefinitionKey(role: any): role is ARIARoleDefinitionKey {
return roles.has(role);
}

function filterRequiredPropsExceptions(
node: AST.VElement,
role: ARIARoleDefinitionKey,
elementType: string,
requiredProps: string[]
) {
// Based on the pattern recommendation in https://www.w3.org/WAI/ARIA/apg/patterns/switch/#wai-ariaroles,states,andproperties
// "aria-checked" should not be required when elementType is `input` and has the type attribute `checkbox`.
if (
role.toLowerCase() === "switch" &&
elementType === "input" &&
getElementAttributeValue(node, "type") === "checkbox"
) {
return requiredProps.filter((p) => p !== "aria-checked");
}
return requiredProps;
}

const rule: Rule.RuleModule = {
meta: {
type: "problem",
@@ -48,7 +66,12 @@ const rule: Rule.RuleModule = {
.forEach((role) => {
if (isAriaRoleDefinitionKey(role)) {
const roleDefinition = roles.get(role) as any;
const requiredProps = Object.keys(roleDefinition.requiredProps);
const requiredProps = filterRequiredPropsExceptions(
node,
role,
elementType,
Object.keys(roleDefinition.requiredProps)
);

if (requiredProps && !hasAttributes(node, requiredProps)) {
context.report({

0 comments on commit 7395e00

Please sign in to comment.