-
Notifications
You must be signed in to change notification settings - Fork 181
Expand file tree
/
Copy pathjsx_no_danger_with_children.rs
More file actions
105 lines (90 loc) · 2.62 KB
/
jsx_no_danger_with_children.rs
File metadata and controls
105 lines (90 loc) · 2.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
use super::{Context, LintRule};
use crate::handler::{Handler, Traverse};
use crate::tags::{self, Tags};
use crate::Program;
use deno_ast::view::{
JSXAttrName, JSXAttrOrSpread, JSXElement, JSXElementChild,
};
use deno_ast::SourceRanged;
use once_cell::sync::Lazy;
#[derive(Debug)]
pub struct JSXNoDangerWithChildren;
const CODE: &str = "jsx-no-danger-with-children";
impl LintRule for JSXNoDangerWithChildren {
fn tags(&self) -> Tags {
&[tags::RECOMMENDED, tags::REACT, tags::JSX, tags::FRESH]
}
fn code(&self) -> &'static str {
CODE
}
fn lint_program_with_ast_view(
&self,
context: &mut Context,
program: Program,
) {
JSXNoDangerWithChildrenHandler.traverse(program, context);
}
}
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" {
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);
}
}
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn jsx_no_danger_with_children_valid() {
assert_lint_ok! {
JSXNoDangerWithChildren,
filename: "file:///foo.jsx",
r#"<div dangerouslySetInnerHTML={{ __html: "foo" }} />"#,
r#"<div dangerouslySetInnerHTML={{ __html: "foo" }}></div>"#,
r#"<div dangerouslySetInnerHTML={{ __html: "foo" }}>
</div>"#,
};
}
#[test]
fn jsx_no_danger_with_children_invalid() {
assert_lint_err! {
JSXNoDangerWithChildren,
filename: "file:///foo.jsx",
r#"<div dangerouslySetInnerHTML={{ __html: "foo" }}>foo</div>"#: [
{
col: 0,
message: MESSAGE,
hint: HINT
}
]
};
}
}