Skip to content

Commit

Permalink
fix: add code fix for jsx-boolean-value
Browse files Browse the repository at this point in the history
  • Loading branch information
dsherret committed Feb 21, 2025
1 parent 7e361b3 commit 864129e
Showing 1 changed file with 48 additions and 4 deletions.
52 changes: 48 additions & 4 deletions src/rules/jsx_boolean_value.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.

use super::{Context, LintRule};
use crate::diagnostic::{LintFix, LintFixChange};
use crate::handler::{Handler, Traverse};
use crate::tags::Tags;
use crate::{tags, Program};
use deno_ast::view::{Expr, JSXAttr, JSXAttrValue, JSXExpr, Lit};
use deno_ast::SourceRanged;
use deno_ast::swc::parser::token::Token;
use deno_ast::view::{AssignOp, Expr, JSXAttr, JSXAttrValue, JSXExpr, Lit};
use deno_ast::{SourceRange, SourceRanged, SourceRangedForSpanned};

#[derive(Debug)]
pub struct JSXBooleanValue;
Expand Down Expand Up @@ -33,6 +35,7 @@ impl LintRule for JSXBooleanValue {
const MESSAGE: &str =
"Passing 'true' to boolean attributes is the same as not passing it`";
const HINT: &str = "Remove the attribute value";
const FIX_DESC: &str = HINT;

struct JSXBooleanValueHandler;

Expand All @@ -41,8 +44,33 @@ impl Handler for JSXBooleanValueHandler {
if let Some(value) = node.value {
if let JSXAttrValue::JSXExprContainer(expr) = value {
if let JSXExpr::Expr(Expr::Lit(Lit::Bool(lit_bool))) = expr.expr {
if lit_bool.value() {
ctx.add_diagnostic_with_hint(value.range(), CODE, MESSAGE, HINT);
if lit_bool.value()
&& lit_bool.leading_comments_fast(ctx.program()).is_empty()
&& lit_bool.trailing_comments_fast(ctx.program()).is_empty()
{
let mut fixes = Vec::with_capacity(1);
if let Some(token) = expr.previous_token_fast(ctx.program()) {
if token.token == Token::AssignOp(AssignOp::Assign) {
let start_pos = token
.previous_token_fast(ctx.program())
.map(|t| t.end())
.unwrap_or(token.start());
fixes.push(LintFix {
description: FIX_DESC.into(),
changes: vec![LintFixChange {
new_text: "".into(),
range: SourceRange::new(start_pos, expr.end()),
}],
});
}
}
ctx.add_diagnostic_with_fixes(
value.range(),
CODE,
MESSAGE,
Some(HINT.into()),
fixes,
);
}
}
}
Expand All @@ -63,6 +91,8 @@ mod tests {
filename: "file:///foo.jsx",
// non derived classes.
"<Foo foo={false} />",
"<Foo foo={/* some comment */ true} />",
"<Foo foo={true /* some comment */} />",
"<Foo foo />",
};
}
Expand All @@ -77,6 +107,20 @@ mod tests {
col: 9,
message: MESSAGE,
hint: HINT,
fix: (FIX_DESC, "<Foo foo />"),
}
],
};

assert_lint_err! {
JSXBooleanValue,
filename: "file:///foo.jsx",
"<Foo foo = { true } />": [
{
col: 11,
message: MESSAGE,
hint: HINT,
fix: (FIX_DESC, "<Foo foo />"),
}
],
};
Expand Down

0 comments on commit 864129e

Please sign in to comment.