Skip to content

Commit

Permalink
[Fix] no-static-element-interactions: allow role assignments using …
Browse files Browse the repository at this point in the history
…a ternary with literals on both sides

Fixes #766.

Co-authored-by: Vividha <rvividha@gmail.com>
Co-authored-by: Jordan Harband <ljharb@gmail.com>
  • Loading branch information
V2dha and ljharb committed Jun 29, 2022
1 parent 2362832 commit 7524e0c
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
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

0 comments on commit 7524e0c

Please sign in to comment.