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
  • Loading branch information
V2dha authored and ljharb committed Jun 29, 2022
1 parent 2362832 commit 220766d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
10 changes: 9 additions & 1 deletion __tests__/src/rules/no-static-element-interactions-test.js
Expand Up @@ -429,9 +429,17 @@ 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={() => {}} />;' },
)
.map(ruleOptionsMapperFactory(recommendedOptions))
.map(parserOptionsMapper),
.map(parserOptionsMapper)
.concat(
{
code: '<div role={isButton ? "button" : "link"} onClick={() => {}} />;',
options: { allowExpressionValues: true },
},
),
invalid: [].concat(
neverValid,
)
Expand Down
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 rolePropVal = getPropValue(getProp(attributes, 'role'));
if (rolePropVal && rolePropVal.type === 'JSXExpressionContainer') {
if (rolePropVal.expression.type === 'ConditionalExpression') {
if (
rolePropVal.expression.consequent.type === 'Literal'
&& rolePropVal.expression.alternate.type === 'Literal'
) {
return;
}
}
}
return;
}

Expand Down

0 comments on commit 220766d

Please sign in to comment.