Skip to content

Commit cdb19c2

Browse files
fix(jsx-no-danger-with-children): account for ignored JSXText nodes (#1400)
* fix(jsx-no-danger-with-children): account for ignored JSXText nodes * chore: make regex more strict
1 parent 6ef1dbb commit cdb19c2

File tree

1 file changed

+28
-4
lines changed

1 file changed

+28
-4
lines changed

src/rules/jsx_no_danger_with_children.rs

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,11 @@ use super::{Context, LintRule};
44
use crate::handler::{Handler, Traverse};
55
use crate::tags::{self, Tags};
66
use crate::Program;
7-
use deno_ast::view::{JSXAttrName, JSXAttrOrSpread, JSXElement};
7+
use deno_ast::view::{
8+
JSXAttrName, JSXAttrOrSpread, JSXElement, JSXElementChild,
9+
};
810
use deno_ast::SourceRanged;
11+
use once_cell::sync::Lazy;
912

1013
#[derive(Debug)]
1114
pub struct JSXNoDangerWithChildren;
@@ -34,16 +37,34 @@ const MESSAGE: &str =
3437
"Using JSX children together with 'dangerouslySetInnerHTML' is invalid";
3538
const HINT: &str = "Remove the JSX children";
3639

40+
static IGNORE_TEXT: Lazy<regex::Regex> =
41+
Lazy::new(|| regex::Regex::new(r#"^\n\s+$"#).unwrap());
42+
3743
struct JSXNoDangerWithChildrenHandler;
3844

3945
impl Handler for JSXNoDangerWithChildrenHandler {
4046
fn jsx_element(&mut self, node: &JSXElement, ctx: &mut Context) {
4147
for attr in node.opening.attrs {
4248
if let JSXAttrOrSpread::JSXAttr(attr) = attr {
4349
if let JSXAttrName::Ident(id) = attr.name {
44-
if id.sym() == "dangerouslySetInnerHTML" && !node.children.is_empty()
45-
{
46-
ctx.add_diagnostic_with_hint(node.range(), CODE, MESSAGE, HINT);
50+
if id.sym() == "dangerouslySetInnerHTML" {
51+
let filtered = node
52+
.children
53+
.iter()
54+
.filter(|child| {
55+
if let JSXElementChild::JSXText(text) = child {
56+
if IGNORE_TEXT.is_match(text.value()) {
57+
return false;
58+
}
59+
}
60+
61+
true
62+
})
63+
.collect::<Vec<_>>();
64+
65+
if !filtered.is_empty() {
66+
ctx.add_diagnostic_with_hint(node.range(), CODE, MESSAGE, HINT);
67+
}
4768
}
4869
}
4970
}
@@ -61,6 +82,9 @@ mod tests {
6182
JSXNoDangerWithChildren,
6283
filename: "file:///foo.jsx",
6384
r#"<div dangerouslySetInnerHTML={{ __html: "foo" }} />"#,
85+
r#"<div dangerouslySetInnerHTML={{ __html: "foo" }}></div>"#,
86+
r#"<div dangerouslySetInnerHTML={{ __html: "foo" }}>
87+
</div>"#,
6488
};
6589
}
6690

0 commit comments

Comments
 (0)