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

[Fix] no-static-element-interactions: allow role assignments using a ternary with literals on both sides #865

Merged
merged 1 commit into from Jul 5, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 11 additions & 0 deletions __tests__/src/rules/no-static-element-interactions-test.js
Expand Up @@ -429,6 +429,11 @@ ruleTester.run(`${ruleName}:recommended`, rule, {
// Expressions should pass in recommended mode
{ code: '<div role={ROLE_BUTTON} onClick={() => {}} />;' },
{ code: '<div {...this.props} role={this.props.role} onKeyPress={e => this.handleKeyPress(e)}>{this.props.children}</div>' },
// Specific case for ternary operator with literals on both side
{
code: '<div role={isButton ? "button" : "link"} onClick={() => {}} />;',
options: [{ allowExpressionValues: true }],
},
)
.map(ruleOptionsMapperFactory(recommendedOptions))
.map(parserOptionsMapper),
Expand Down Expand Up @@ -465,5 +470,11 @@ ruleTester.run(`${ruleName}:strict`, rule, {
// Expressions should fail in strict mode
{ code: '<div role={ROLE_BUTTON} onClick={() => {}} />;', errors: [expectedError] },
{ code: '<div {...this.props} role={this.props.role} onKeyPress={e => this.handleKeyPress(e)}>{this.props.children}</div>', errors: [expectedError] },
// Specific case for ternary operator with literals on both side
{
code: '<div role={isButton ? "button" : "link"} onClick={() => {}} />;',
options: [{ allowExpressionValues: false }],
errors: [expectedError],
},
).map(parserOptionsMapper),
});
14 changes: 13 additions & 1 deletion src/rules/no-static-element-interactions.js
Expand Up @@ -58,6 +58,7 @@ export default ({
JSXOpeningElement: (node: JSXOpeningElement) => {
const { attributes } = node;
const type = elementType(node);

const {
allowExpressionValues,
handlers = defaultInteractiveProps,
Expand Down Expand Up @@ -99,7 +100,18 @@ export default ({
allowExpressionValues === true
&& isNonLiteralProperty(attributes, 'role')
) {
// This rule has no opinion about non-literal roles.
// Special case if role is assigned using ternary with literals on both side
const roleProp = getProp(attributes, 'role');
if (roleProp && roleProp.type === 'JSXAttribute' && roleProp.value.type === 'JSXExpressionContainer') {
if (roleProp.value.expression.type === 'ConditionalExpression') {
if (
roleProp.value.expression.consequent.type === 'Literal'
&& roleProp.value.expression.alternate.type === 'Literal'
) {
return;
}
}
}
return;
}

Expand Down