Skip to content

Commit

Permalink
feat: add jsx-no-danger-with-children rule
Browse files Browse the repository at this point in the history
  • Loading branch information
marvinhagemeister committed Nov 22, 2024
1 parent 5a7ce21 commit 5c20a4d
Show file tree
Hide file tree
Showing 4 changed files with 114 additions and 0 deletions.
16 changes: 16 additions & 0 deletions docs/rules/jsx_no_danger_with_children.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
Using JSX children together with `dangerouslySetInnerHTML` is invalid as they
will be ignored.

### Invalid:

```tsx
<div dangerouslySetInnerHTML={{ __html: "<h1>hello</h1>" }}>
<h1>this will never be rendered</h1>
</div>;
```

### Valid:

```tsx
<div dangerouslySetInnerHTML={{ __html: "<h1>hello</h1>" }} />;
```
2 changes: 2 additions & 0 deletions src/rules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ pub mod fresh_handler_export;
pub mod fresh_server_event_handlers;
pub mod getter_return;
pub mod guard_for_in;
pub mod jsx_no_danger_with_children;
pub mod no_array_constructor;
pub mod no_async_promise_executor;
pub mod no_await_in_loop;
Expand Down Expand Up @@ -255,6 +256,7 @@ fn get_all_rules_raw() -> Vec<Box<dyn LintRule>> {
Box::new(fresh_server_event_handlers::FreshServerEventHandlers),
Box::new(getter_return::GetterReturn),
Box::new(guard_for_in::GuardForIn),
Box::new(jsx_no_danger_with_children::JSXNoDangerWithChildren),
Box::new(no_array_constructor::NoArrayConstructor),
Box::new(no_async_promise_executor::NoAsyncPromiseExecutor),
Box::new(no_await_in_loop::NoAwaitInLoop),
Expand Down
88 changes: 88 additions & 0 deletions src/rules/jsx_no_danger_with_children.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.

use super::{Context, LintRule};
use crate::handler::{Handler, Traverse};
use crate::Program;
use deno_ast::view::{JSXAttrName, JSXAttrOrSpread, JSXElement};
use deno_ast::SourceRanged;

#[derive(Debug)]
pub struct JSXNoDangerWithChildren;

const CODE: &str = "jsx-no-danger-with-children";

impl LintRule for JSXNoDangerWithChildren {
fn tags(&self) -> &'static [&'static str] {
&["react", "jsx", "fresh"]
}

fn code(&self) -> &'static str {
CODE
}

fn lint_program_with_ast_view(
&self,
context: &mut Context,
program: Program,
) {
JSXNoDangerWithChildrenHandler.traverse(program, context);
}

#[cfg(feature = "docs")]
fn docs(&self) -> &'static str {
include_str!("../../docs/rules/jsx_no_danger_with_children.md")
}
}

const MESSAGE: &str =
"Using JSX children together with 'dangerouslySetInnerHTML' is invalid";
const HINT: &str = "Remove the JSX children";

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" {
if !node.children.is_empty() {
ctx.add_diagnostic_with_hint(node.range(), CODE, MESSAGE, HINT);
}
}
}
}
}
}
}

// most tests are taken from ESlint, commenting those
// requiring code path support
#[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" }} />"#,
};
}

#[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
}
]
};
}
}
8 changes: 8 additions & 0 deletions www/static/docs.json
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,14 @@
"docs": "Require `for-in` loops to include an `if` statement\n\nLooping over objects with a `for-in` loop will include properties that are\ninherited through the prototype chain. This behavior can lead to unexpected\nitems in your for loop.\n\n### Invalid:\n\n```typescript\nfor (const key in obj) {\n foo(obj, key);\n}\n```\n\n### Valid:\n\n```typescript\nfor (const key in obj) {\n if (Object.hasOwn(obj, key)) {\n foo(obj, key);\n }\n}\n```\n\n```typescript\nfor (const key in obj) {\n if (!Object.hasOwn(obj, key)) {\n continue;\n }\n foo(obj, key);\n}\n```\n",
"tags": []
},
{
"code": "jsx-no-danger-with-children",
"docs": "Using JSX children together with `dangerouslySetInnerHTML` is invalid as they\nwill be ignored.\n\n### Invalid:\n\n```tsx\n<div dangerouslySetInnerHTML={{ __html: \"<h1>hello</h1>\" }}>\n <h1>this will never be rendered</h1>\n</div>;\n```\n\n### Valid:\n\n```tsx\n<div dangerouslySetInnerHTML={{ __html: \"<h1>hello</h1>\" }} />;\n```\n",
"tags": [
"react",
"jsx"
]
},
{
"code": "no-array-constructor",
"docs": "Enforce conventional usage of array construction\n\nArray construction is conventionally done via literal notation such as `[]` or\n`[1, 2, 3]`. Using the `new Array()` is discouraged as is `new Array(1, 2, 3)`.\nThere are two reasons for this. The first is that a single supplied argument\ndefines the array length, while multiple arguments instead populate the array of\nno fixed size. This confusion is avoided when pre-populated arrays are only\ncreated using literal notation. The second argument to avoiding the `Array`\nconstructor is that the `Array` global may be redefined.\n\nThe one exception to this rule is when creating a new array of fixed size, e.g.\n`new Array(6)`. This is the conventional way to create arrays of fixed length.\n\n### Invalid:\n\n```typescript\n// This is 4 elements, not a size 100 array of 3 elements\nconst a = new Array(100, 1, 2, 3);\n\nconst b = new Array(); // use [] instead\n```\n\n### Valid:\n\n```typescript\nconst a = new Array(100);\nconst b = [];\nconst c = [1, 2, 3];\n```\n",
Expand Down

0 comments on commit 5c20a4d

Please sign in to comment.