Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 28 additions & 4 deletions src/rules/jsx_no_danger_with_children.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@ use super::{Context, LintRule};
use crate::handler::{Handler, Traverse};
use crate::tags::{self, Tags};
use crate::Program;
use deno_ast::view::{JSXAttrName, JSXAttrOrSpread, JSXElement};
use deno_ast::view::{
JSXAttrName, JSXAttrOrSpread, JSXElement, JSXElementChild,
};
use deno_ast::SourceRanged;
use once_cell::sync::Lazy;

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

static IGNORE_TEXT: Lazy<regex::Regex> =
Lazy::new(|| regex::Regex::new(r#"^\n\s+$"#).unwrap());

struct JSXNoDangerWithChildrenHandler;

impl Handler for JSXNoDangerWithChildrenHandler {
fn jsx_element(&mut self, node: &JSXElement, ctx: &mut Context) {
for attr in node.opening.attrs {
if let JSXAttrOrSpread::JSXAttr(attr) = attr {
if let JSXAttrName::Ident(id) = attr.name {
if id.sym() == "dangerouslySetInnerHTML" && !node.children.is_empty()
{
ctx.add_diagnostic_with_hint(node.range(), CODE, MESSAGE, HINT);
if id.sym() == "dangerouslySetInnerHTML" {
let filtered = node
.children
.iter()
.filter(|child| {
if let JSXElementChild::JSXText(text) = child {
if IGNORE_TEXT.is_match(text.value()) {
return false;
}
}

true
})
.collect::<Vec<_>>();

if !filtered.is_empty() {
ctx.add_diagnostic_with_hint(node.range(), CODE, MESSAGE, HINT);
}
}
}
}
Expand All @@ -61,6 +82,9 @@ mod tests {
JSXNoDangerWithChildren,
filename: "file:///foo.jsx",
r#"<div dangerouslySetInnerHTML={{ __html: "foo" }} />"#,
r#"<div dangerouslySetInnerHTML={{ __html: "foo" }}></div>"#,
r#"<div dangerouslySetInnerHTML={{ __html: "foo" }}>
</div>"#,
};
}

Expand Down
Loading