@murky-web/oxlint-plugin-solid 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +163 -18
  2. package/THIRD_PARTY_NOTICES.md +7 -4
  3. package/package.json +5 -2
  4. package/src/compat.mjs +3 -0
  5. package/src/index.mjs +26 -3
  6. package/src/rules/components_return_once.mjs +136 -89
  7. package/src/rules/event_handlers.mjs +55 -35
  8. package/src/rules/filename_matches_export.mjs +292 -0
  9. package/src/rules/function_size.mjs +189 -0
  10. package/src/rules/imports.mjs +24 -21
  11. package/src/rules/init_declarations.mjs +139 -0
  12. package/src/rules/jsx_no_duplicate_props.mjs +46 -18
  13. package/src/rules/jsx_no_script_url.mjs +7 -6
  14. package/src/rules/jsx_no_undef.mjs +35 -38
  15. package/src/rules/jsx_uses_vars.mjs +4 -4
  16. package/src/rules/no_array_handlers.mjs +38 -9
  17. package/src/rules/no_cleanup_in_effect_apply.mjs +154 -0
  18. package/src/rules/no_destructure.mjs +105 -35
  19. package/src/rules/no_innerhtml.mjs +64 -31
  20. package/src/rules/no_module_scope_reactive_primitive.mjs +73 -0
  21. package/src/rules/no_owned_primitives_in_ref.mjs +30 -9
  22. package/src/rules/no_proxy_apis.mjs +44 -15
  23. package/src/rules/no_react_deps.mjs +397 -41
  24. package/src/rules/no_react_specific_props.mjs +40 -11
  25. package/src/rules/no_server_import_in_client.mjs +9 -9
  26. package/src/rules/no_setter_in_effect.mjs +153 -30
  27. package/src/rules/no_single_arg_create_effect.mjs +55 -0
  28. package/src/rules/no_unassigned_vars.mjs +99 -0
  29. package/src/rules/no_unknown_namespaces.mjs +108 -29
  30. package/src/rules/no_untracked_effect_read.mjs +69 -32
  31. package/src/rules/no_write_in_pure_computation.mjs +273 -0
  32. package/src/rules/prefer_arrow_components.mjs +47 -21
  33. package/src/rules/prefer_class_object.mjs +52 -20
  34. package/src/rules/prefer_destructuring.mjs +164 -0
  35. package/src/rules/prefer_for.mjs +42 -12
  36. package/src/rules/prefer_ref_shorthand.mjs +142 -0
  37. package/src/rules/prefer_show.mjs +55 -24
  38. package/src/rules/reactive_async.mjs +64 -17
  39. package/src/rules/reactivity.mjs +1218 -350
  40. package/src/rules/self_closing_comp.mjs +23 -18
  41. package/src/rules/strict_void_return.mjs +50 -20
  42. package/src/rules/style_prop.mjs +53 -25
  43. package/src/rules/typed_merge_defaults.mjs +88 -0
  44. package/src/rules/validate_jsx_nesting.mjs +16 -16
  45. package/src/utils.mjs +65 -34
@@ -1,4 +1,5 @@
1
- import { jsxPropName } from "../utils.mjs";
1
+ import { getSourceCode } from "../compat.mjs";
2
+ import { jsxPropName, messageCode } from "../utils.mjs";
2
3
  const DEFAULT_CLASSNAMES = ["cn", "clsx", "classnames"];
3
4
  export default {
4
5
  meta: {
@@ -6,7 +7,7 @@ export default {
6
7
  docs: {
7
8
  description:
8
9
  "Enforce the `class` object/array form over the removed `classList` prop or a classnames helper. Solid 2.0 accepts `{ [class: string]: boolean }` on `class` directly.",
9
- url: "https://docs.solidjs.com/",
10
+ url: "https://docs.solidjs.com/"
10
11
  },
11
12
  fixable: "code",
12
13
  schema: [
@@ -19,25 +20,37 @@ export default {
19
20
  "An array of names to treat as `classnames` functions",
20
21
  default: DEFAULT_CLASSNAMES,
21
22
  items: {
22
- type: "string",
23
+ type: "string"
23
24
  },
24
25
  minItems: 1,
25
- uniqueItems: true,
26
- },
26
+ uniqueItems: true
27
+ }
27
28
  },
28
- additionalProperties: false,
29
- },
29
+ additionalProperties: false
30
+ }
30
31
  ],
31
32
  messages: {
32
33
  classlistRemoved:
33
- "The `classList` prop was removed in Solid 2.0. Pass the object to `class` instead.",
34
+ "`{{ name }}` was removed in Solid 2.0; on a native element it is a compile error. `class` takes the object itself. Fix: `{{ fix }}`.",
34
35
  preferClassObject:
35
- "Pass the object to `class` directly instead of through {{ classnames }}.",
36
- },
36
+ "`{{ classnames }}(…)` turns the object into a string, which replaces the whole `class` attribute on every change. Solid 2.0's `class` takes the object and toggles single classes. Fix: `{{ fix }}`."
37
+ }
37
38
  },
38
39
  defaultOptions: [],
39
40
  create(context) {
40
41
  const classnames = context.options[0]?.classnames ?? DEFAULT_CLASSNAMES;
42
+ const sourceCode = getSourceCode(context);
43
+ // An attribute's value as an expression: `"a"` or the braced code.
44
+ const valueText = (attribute) => {
45
+ if (!attribute.value) {
46
+ return "true";
47
+ }
48
+ return sourceCode.getText(
49
+ attribute.value.type === "JSXExpressionContainer"
50
+ ? attribute.value.expression
51
+ : attribute.value
52
+ );
53
+ };
41
54
  return {
42
55
  JSXAttribute(node) {
43
56
  const name = jsxPropName(node);
@@ -50,17 +63,30 @@ export default {
50
63
  // With a `class` attribute next to it, renaming would
51
64
  // write the attribute twice (a parse error in TSX); the
52
65
  // two have to be merged by hand.
53
- const hasClassAttribute = node.parent.attributes.some(
66
+ const classAttribute = node.parent.attributes.find(
54
67
  (attribute) =>
55
68
  attribute.type === "JSXAttribute" &&
56
- jsxPropName(attribute) === "class",
69
+ jsxPropName(attribute) === "class"
57
70
  );
71
+ const hasClassAttribute = classAttribute !== undefined;
58
72
  context.report({
59
73
  node,
60
74
  messageId: "classlistRemoved",
75
+ data: {
76
+ name,
77
+ // Next to a `class`, both go into the array form.
78
+ fix: messageCode(
79
+ hasClassAttribute
80
+ ? `class={[${valueText(classAttribute)}, ${valueText(node)}]}`
81
+ : `class={${valueText(node)}}`,
82
+ hasClassAttribute
83
+ ? 'class={["card", { active: active() }]}'
84
+ : "class={{ active: active() }}"
85
+ )
86
+ },
61
87
  fix: hasClassAttribute
62
88
  ? null
63
- : (fixer) => fixer.replaceText(node.name, "class"),
89
+ : (fixer) => fixer.replaceText(node.name, "class")
64
90
  });
65
91
  return;
66
92
  }
@@ -84,23 +110,29 @@ export default {
84
110
  context.report({
85
111
  node,
86
112
  messageId: "preferClassObject",
87
- data: { classnames: expr.callee.name },
113
+ data: {
114
+ classnames: expr.callee.name,
115
+ fix: messageCode(
116
+ `class={${sourceCode.getText(expr.arguments[0])}}`,
117
+ "class={{ active: active() }}"
118
+ )
119
+ },
88
120
  fix: (fixer) => {
89
121
  const objectRange = expr.arguments[0].range;
90
122
  return [
91
123
  fixer.replaceTextRange(
92
124
  [node.range[0], objectRange[0]],
93
- "class={",
125
+ "class={"
94
126
  ),
95
127
  fixer.replaceTextRange(
96
128
  [objectRange[1], node.range[1]],
97
- "}",
98
- ),
129
+ "}"
130
+ )
99
131
  ];
100
- },
132
+ }
101
133
  });
102
134
  }
103
- },
135
+ }
104
136
  };
105
- },
137
+ }
106
138
  };
@@ -0,0 +1,164 @@
1
+ // Fork of eslint's prefer-destructuring for Solid code. Destructuring is
2
+ // preferred everywhere except on reactive sources: `const { x } = props` or
3
+ // `const { items } = store` copies the value once at setup and drops
4
+ // reactivity, so there `props.x` read where it is used is the right form, and
5
+ // eslint's rule pushed toward the bug. Defaults as in eslint (declarations and
6
+ // assignments, arrays and objects, no renamed properties); like
7
+ // typescript-eslint, a declaration with a type annotation is left alone.
8
+ import { findVariable, getSourceCode } from "../compat.mjs";
9
+ import {
10
+ getFunctionName,
11
+ isFunctionNode,
12
+ isPropsByName,
13
+ trackImports
14
+ } from "../utils.mjs";
15
+
16
+ /** Calls whose result is a reactive proxy read by property access. */
17
+ const REACTIVE_OBJECT_SOURCES = [
18
+ "createStore",
19
+ "createProjection",
20
+ "createOptimisticStore",
21
+ "merge",
22
+ "omit"
23
+ ];
24
+
25
+ function isIndexAccess(member) {
26
+ return (
27
+ member.computed &&
28
+ member.property.type === "Literal" &&
29
+ Number.isInteger(member.property.value)
30
+ );
31
+ }
32
+
33
+ function isComponentProps(definition) {
34
+ if (definition.type !== "Parameter") {
35
+ return false;
36
+ }
37
+ const fn = definition.node;
38
+ return (
39
+ isFunctionNode(fn) &&
40
+ fn.params[0] === definition.name &&
41
+ /^[A-Z]/u.test(getFunctionName(fn) ?? "")
42
+ );
43
+ }
44
+
45
+ export default {
46
+ meta: {
47
+ type: "suggestion",
48
+ docs: {
49
+ description:
50
+ "Prefer destructuring, except from props and stores, where it drops reactivity."
51
+ },
52
+ schema: [],
53
+ messages: {
54
+ preferDestructuring:
55
+ "`{{statement}}` reads `{{member}}` into a variable by hand; {{type}} destructuring states the source once. Fix: `{{fix}}`."
56
+ }
57
+ },
58
+ defaultOptions: [],
59
+ create(context) {
60
+ const { matchImport, handleImportDeclaration } = trackImports();
61
+
62
+ function isReactiveSource(object) {
63
+ if (object.type !== "Identifier") {
64
+ return false;
65
+ }
66
+ if (isPropsByName(object.name)) {
67
+ return true;
68
+ }
69
+ const definition = findVariable(context, object)?.defs[0];
70
+ if (!definition) {
71
+ return false;
72
+ }
73
+ if (isComponentProps(definition)) {
74
+ return true;
75
+ }
76
+ const init =
77
+ definition.type === "Variable" ? definition.node.init : null;
78
+ if (
79
+ init?.type !== "CallExpression" ||
80
+ init.callee.type !== "Identifier" ||
81
+ !matchImport(REACTIVE_OBJECT_SOURCES, init.callee.name)
82
+ ) {
83
+ return false;
84
+ }
85
+ // `const [store] = createStore(...)` or `const local = merge(...)`.
86
+ const { id } = definition.node;
87
+ return id.type === "ArrayPattern"
88
+ ? id.elements[0] === definition.name
89
+ : id === definition.name;
90
+ }
91
+
92
+ const sourceCode = getSourceCode(context);
93
+
94
+ /**
95
+ * The destructuring form of `reportNode`: `const { x } = obj` or `const
96
+ * [, x] = list`, and `({ x } = obj)` for an assignment.
97
+ */
98
+ function buildData(value, reportNode, pattern) {
99
+ const object = sourceCode.getText(value.object);
100
+ const statement =
101
+ reportNode.type === "VariableDeclarator"
102
+ ? `${reportNode.parent.kind} ${sourceCode.getText(reportNode)}`
103
+ : sourceCode.getText(reportNode);
104
+ const fix =
105
+ reportNode.type === "VariableDeclarator"
106
+ ? `${reportNode.parent.kind} ${pattern} = ${object}`
107
+ : `(${pattern} = ${object})`;
108
+ return {
109
+ fix,
110
+ member: sourceCode.getText(value),
111
+ statement,
112
+ type: pattern.startsWith("[") ? "array" : "object"
113
+ };
114
+ }
115
+
116
+ function check(target, value, reportNode) {
117
+ if (
118
+ target.type !== "Identifier" ||
119
+ value?.type !== "MemberExpression"
120
+ ) {
121
+ return;
122
+ }
123
+ if (isIndexAccess(value)) {
124
+ context.report({
125
+ data: buildData(
126
+ value,
127
+ reportNode,
128
+ `[${", ".repeat(value.property.value)}${target.name}]`
129
+ ),
130
+ messageId: "preferDestructuring",
131
+ node: reportNode
132
+ });
133
+ return;
134
+ }
135
+ if (
136
+ !value.computed &&
137
+ value.property.type === "Identifier" &&
138
+ value.property.name === target.name &&
139
+ !isReactiveSource(value.object)
140
+ ) {
141
+ context.report({
142
+ data: buildData(value, reportNode, `{ ${target.name} }`),
143
+ messageId: "preferDestructuring",
144
+ node: reportNode
145
+ });
146
+ }
147
+ }
148
+
149
+ return {
150
+ ImportDeclaration: handleImportDeclaration,
151
+ VariableDeclarator(node) {
152
+ if (node.id.typeAnnotation) {
153
+ return;
154
+ }
155
+ check(node.id, node.init, node);
156
+ },
157
+ AssignmentExpression(node) {
158
+ if (node.operator === "=") {
159
+ check(node.left, node.right, node);
160
+ }
161
+ }
162
+ };
163
+ }
164
+ };
@@ -1,25 +1,33 @@
1
1
  import { getPropertyName } from "@eslint-community/eslint-utils";
2
2
 
3
- import { isFunctionNode, isJSXElementOrFragment } from "../utils.mjs";
3
+ import { getSourceCode } from "../compat.mjs";
4
+ import {
5
+ isFunctionNode,
6
+ isJSXElementOrFragment,
7
+ messageCode
8
+ } from "../utils.mjs";
4
9
  export default {
5
10
  meta: {
6
11
  type: "problem",
7
12
  docs: {
8
13
  description:
9
14
  "Enforce using Solid's `<For />` component for mapping an array to JSX elements.",
10
- url: "https://github.com/solidjs-community/eslint-plugin-solid/blob/main/packages/eslint-plugin-solid/docs/prefer-for.md",
15
+ url: "https://github.com/solidjs-community/eslint-plugin-solid/blob/main/packages/eslint-plugin-solid/docs/prefer-for.md"
11
16
  },
12
17
  fixable: "code",
13
18
  schema: [],
14
19
  messages: {
15
20
  preferFor:
16
- "Use Solid's `<For />` component for efficiently rendering lists. Array#map causes DOM elements to be recreated.",
21
+ "`{{array}}.map(…)` in JSX re-runs the whole map when `{{array}}` changes, so the DOM of every row is created again. Fix: `<For each={{{array}}}>{{{callback}}}</For>`.",
17
22
  preferForOrIndex:
18
- "Use Solid's `<For />` component for rendering lists (`keyed={false}` for the index-based form). Array#map causes DOM elements to be recreated.",
19
- },
23
+ "`{{array}}.map(…)` in JSX re-runs the whole map when `{{array}}` changes, so the DOM of every row is created again. Fix: `<For each={{{array}}}>{({{item}}, {{index}}) => …}</For>`, where `{{index}}` is an accessor (read `{{index}}()`); with `keyed={false}`, `{{item}}` is the accessor (`{{item}}()`) and `{{index}}` a plain number."
24
+ }
20
25
  },
21
26
  defaultOptions: [],
22
27
  create(context) {
28
+ const sourceCode = getSourceCode(context);
29
+ const arrayText = (node) =>
30
+ messageCode(sourceCode.getText(node.callee.object), "items()");
23
31
  const reportPreferFor = (node) => {
24
32
  const jsxExpressionContainerNode = node.parent;
25
33
  const arrayNode = node.callee.object;
@@ -27,26 +35,33 @@ export default {
27
35
  context.report({
28
36
  node,
29
37
  messageId: "preferFor",
38
+ data: {
39
+ array: arrayText(node),
40
+ callback: messageCode(
41
+ sourceCode.getText(mapFnNode),
42
+ "(item) => …"
43
+ )
44
+ },
30
45
  fix: (fixer) => {
31
46
  const beforeArray = [
32
47
  jsxExpressionContainerNode.range[0],
33
- arrayNode.range[0],
48
+ arrayNode.range[0]
34
49
  ];
35
50
  const betweenArrayAndMapFn = [
36
51
  arrayNode.range[1],
37
- mapFnNode.range[0],
52
+ mapFnNode.range[0]
38
53
  ];
39
54
  const afterMapFn = [
40
55
  mapFnNode.range[1],
41
- jsxExpressionContainerNode.range[1],
56
+ jsxExpressionContainerNode.range[1]
42
57
  ];
43
58
  // We can insert the <For /> component
44
59
  return [
45
60
  fixer.replaceTextRange(beforeArray, "<For each={"),
46
61
  fixer.replaceTextRange(betweenArrayAndMapFn, "}>{"),
47
- fixer.replaceTextRange(afterMapFn, "}</For>"),
62
+ fixer.replaceTextRange(afterMapFn, "}</For>")
48
63
  ];
49
- },
64
+ }
50
65
  });
51
66
  };
52
67
  return {
@@ -77,14 +92,29 @@ export default {
77
92
  reportPreferFor(node);
78
93
  } else {
79
94
  // Too many possible solutions to make a suggestion or fix
95
+ const [item, index] = mapFnNode.params.map(
96
+ (param) => {
97
+ if (param.type === "RestElement") {
98
+ return null;
99
+ }
100
+ return param.type === "Identifier"
101
+ ? param.name
102
+ : sourceCode.getText(param);
103
+ }
104
+ );
80
105
  context.report({
81
106
  node,
82
107
  messageId: "preferForOrIndex",
108
+ data: {
109
+ array: arrayText(node),
110
+ item: item ?? "item",
111
+ index: index ?? "index"
112
+ }
83
113
  });
84
114
  }
85
115
  }
86
116
  }
87
- },
117
+ }
88
118
  };
89
- },
119
+ }
90
120
  };
@@ -0,0 +1,142 @@
1
+ // A single `ref={el}` is rewritten by Solid's compiler to `el = node`, so a
2
+ // callback that only does that assignment is the long form of the shorthand.
3
+ // The rewrite is single-ref only: inside `ref={[…]}` every entry is a callback
4
+ // and a bare `el` is never assigned.
5
+ import { findVariable, getSourceCode } from "../compat.mjs";
6
+ import { jsxPropName } from "../utils.mjs";
7
+
8
+ function unwrapNonNull(node) {
9
+ return node?.type === "TSNonNullExpression" ? node.expression : node;
10
+ }
11
+
12
+ /** `el` in `(node) => { el = node; }` or `(node) => (el = node)`. */
13
+ function getStoredIdentifier(callback) {
14
+ if (
15
+ (callback.type !== "ArrowFunctionExpression" &&
16
+ callback.type !== "FunctionExpression") ||
17
+ callback.async ||
18
+ callback.generator ||
19
+ callback.params.length !== 1 ||
20
+ callback.params[0].type !== "Identifier"
21
+ ) {
22
+ return null;
23
+ }
24
+ let expression = callback.body;
25
+ if (expression.type === "BlockStatement") {
26
+ const [statement] = expression.body;
27
+ if (
28
+ expression.body.length !== 1 ||
29
+ statement.type !== "ExpressionStatement"
30
+ ) {
31
+ return null;
32
+ }
33
+ expression = statement.expression;
34
+ }
35
+ const param = callback.params[0].name;
36
+ if (
37
+ expression.type === "AssignmentExpression" &&
38
+ expression.operator === "=" &&
39
+ expression.left.type === "Identifier" &&
40
+ expression.left.name !== param &&
41
+ expression.right.type === "Identifier" &&
42
+ expression.right.name === param
43
+ ) {
44
+ return expression.left;
45
+ }
46
+ return null;
47
+ }
48
+
49
+ export default {
50
+ meta: {
51
+ type: "suggestion",
52
+ docs: {
53
+ description:
54
+ "Prefer `ref={el}` over a callback that only stores the element, and report a bare variable in a ref array, which is never assigned."
55
+ },
56
+ fixable: "code",
57
+ hasSuggestions: true,
58
+ schema: [],
59
+ messages: {
60
+ callbackOnlyStores:
61
+ "The `ref` callback `{{callback}}` only stores the element in `{{name}}`, which `{{shorthand}}` does on its own: Solid's compiler rewrites a single `ref` variable to that assignment. Fix: `{{shorthand}}`.",
62
+ bareEntryInArray:
63
+ "`{{name}}` in the `ref` array is never assigned and stays `undefined`: Solid rewrites only a single `{{shorthand}}` to an assignment, and an array entry must be a callback. Fix: `{{callback}}` in its place. Do not: add `!` or a default to `{{name}}`; it stays unassigned either way.",
64
+ useCallback: "Replace `{{name}}` with `{{callback}}`."
65
+ }
66
+ },
67
+ defaultOptions: [],
68
+ create(context) {
69
+ const sourceCode = getSourceCode(context);
70
+
71
+ /**
72
+ * A `let el;` waiting for its element. A directive in the array
73
+ * (`ref={[autofocus]}`) is a function or a variable with a value.
74
+ */
75
+ function isElementVariable(identifier) {
76
+ const definition = findVariable(context, identifier)?.defs[0];
77
+ return (
78
+ definition?.type === "Variable" &&
79
+ definition.parent.kind !== "const" &&
80
+ !definition.parent.declare &&
81
+ definition.node.init === null
82
+ );
83
+ }
84
+
85
+ function checkArrayEntry(entry) {
86
+ const identifier = unwrapNonNull(entry);
87
+ if (
88
+ identifier?.type !== "Identifier" ||
89
+ !isElementVariable(identifier)
90
+ ) {
91
+ return;
92
+ }
93
+ const { name } = identifier;
94
+ const param = name === "node" ? "element" : "node";
95
+ const callback = `(${param}) => { ${name} = ${param}; }`;
96
+ context.report({
97
+ data: { callback, name, shorthand: `ref={${name}}` },
98
+ messageId: "bareEntryInArray",
99
+ node: entry,
100
+ suggest: [
101
+ {
102
+ data: { callback, name },
103
+ fix: (fixer) => fixer.replaceText(entry, callback),
104
+ messageId: "useCallback"
105
+ }
106
+ ]
107
+ });
108
+ }
109
+
110
+ return {
111
+ JSXAttribute(node) {
112
+ if (
113
+ jsxPropName(node) !== "ref" ||
114
+ node.value?.type !== "JSXExpressionContainer"
115
+ ) {
116
+ return;
117
+ }
118
+ const { expression } = node.value;
119
+ if (expression.type === "ArrayExpression") {
120
+ for (const entry of expression.elements) {
121
+ checkArrayEntry(entry);
122
+ }
123
+ return;
124
+ }
125
+ const stored = getStoredIdentifier(expression);
126
+ if (stored === null) {
127
+ return;
128
+ }
129
+ context.report({
130
+ data: {
131
+ callback: sourceCode.getText(expression),
132
+ name: stored.name,
133
+ shorthand: `ref={${stored.name}}`
134
+ },
135
+ fix: (fixer) => fixer.replaceText(expression, stored.name),
136
+ messageId: "callbackOnlyStores",
137
+ node: expression
138
+ });
139
+ }
140
+ };
141
+ }
142
+ };
@@ -1,22 +1,28 @@
1
1
  import { getSourceCode } from "../compat.mjs";
2
- import { isJSXElementOrFragment } from "../utils.mjs";
3
- const EXPENSIVE_TYPES = ["JSXElement", "JSXFragment", "Identifier"];
2
+ import { isJSXElementOrFragment, messageCode } from "../utils.mjs";
3
+ // Only a branch that is visibly JSX is reported. A text ternary is the
4
+ // cheapest form, and an Identifier may hold text, where a `<Show>` is slower:
5
+ // the compiler does not lower it. Oxlint's tree drops parentheses, so
6
+ // `(<A/>)` is a JSXElement here too.
4
7
  export default {
5
8
  meta: {
6
9
  type: "problem",
7
10
  docs: {
8
11
  description:
9
12
  "Enforce using Solid's `<Show />` component for conditionally showing content. Solid's compiler covers this case, so it's a stylistic rule only.",
10
- url: "https://github.com/solidjs-community/eslint-plugin-solid/blob/main/packages/eslint-plugin-solid/docs/prefer-show.md",
13
+ url: "https://github.com/solidjs-community/eslint-plugin-solid/blob/main/packages/eslint-plugin-solid/docs/prefer-show.md"
11
14
  },
12
15
  fixable: "code",
16
+ hasSuggestions: true,
13
17
  schema: [],
14
18
  messages: {
15
19
  preferShowAnd:
16
- "Use Solid's `<Show />` component for conditionally showing content.",
20
+ '`{{test}} && …` renders an element, and when `{{test}}` is `0` or `""` it renders that value instead of nothing. Fix: `{{fix}}`; `<Show>` renders nothing for every falsy value.',
17
21
  preferShowTernary:
18
- "Use Solid's `<Show />` component for conditionally showing content with a fallback.",
19
- },
22
+ "`{{test}} ? … : …` switches between elements, which is what `<Show>` is for; a ternary is the cheaper form only when both branches are text. Fix: `{{fix}}`.",
23
+ useShow:
24
+ "Replace with `<Show>`. A falsy value such as `0` is then no longer rendered."
25
+ }
20
26
  },
21
27
  defaultOptions: [],
22
28
  create(context) {
@@ -25,41 +31,66 @@ export default {
25
31
  const text = sourceCode.getText(node);
26
32
  return isJSXElementOrFragment(node) ? text : `{${text}}`;
27
33
  };
34
+ // `{count() && <A/>}` renders `0` when count() is 0, `<Show>` renders
35
+ // nothing, so the rewrite is a suggestion, not a fix.
36
+ const testText = (node) =>
37
+ messageCode(sourceCode.getText(node), "condition");
28
38
  const logicalExpressionHandler = (node) => {
29
- if (
30
- node.operator === "&&" &&
31
- EXPENSIVE_TYPES.includes(node.right.type)
32
- ) {
39
+ if (node.operator === "&&" && isJSXElementOrFragment(node.right)) {
40
+ const test = sourceCode.getText(node.left);
33
41
  context.report({
34
42
  node,
35
43
  messageId: "preferShowAnd",
36
- fix: (fixer) =>
37
- fixer.replaceText(
38
- node.parent?.type === "JSXExpressionContainer" &&
39
- isJSXElementOrFragment(node.parent.parent)
40
- ? node.parent
41
- : node,
42
- `<Show when={${sourceCode.getText(node.left)}}>${putIntoJSX(node.right)}</Show>`,
43
- ),
44
+ data: {
45
+ test: testText(node.left),
46
+ fix: messageCode(
47
+ `<Show when={${test}}>${putIntoJSX(node.right)}</Show>`,
48
+ `<Show when={${testText(node.left)}}>…</Show>`
49
+ )
50
+ },
51
+ suggest: [
52
+ {
53
+ messageId: "useShow",
54
+ fix: (fixer) =>
55
+ fixer.replaceText(
56
+ node.parent?.type ===
57
+ "JSXExpressionContainer" &&
58
+ isJSXElementOrFragment(
59
+ node.parent.parent
60
+ )
61
+ ? node.parent
62
+ : node,
63
+ `<Show when={${sourceCode.getText(node.left)}}>${putIntoJSX(node.right)}</Show>`
64
+ )
65
+ }
66
+ ]
44
67
  });
45
68
  }
46
69
  };
47
70
  const conditionalExpressionHandler = (node) => {
48
71
  if (
49
- EXPENSIVE_TYPES.includes(node.consequent.type) ||
50
- EXPENSIVE_TYPES.includes(node.alternate.type)
72
+ isJSXElementOrFragment(node.consequent) ||
73
+ isJSXElementOrFragment(node.alternate)
51
74
  ) {
75
+ const test = sourceCode.getText(node.test);
52
76
  context.report({
53
77
  node,
54
78
  messageId: "preferShowTernary",
79
+ data: {
80
+ test: testText(node.test),
81
+ fix: messageCode(
82
+ `<Show when={${test}} fallback={${sourceCode.getText(node.alternate)}}>${putIntoJSX(node.consequent)}</Show>`,
83
+ `<Show when={${testText(node.test)}} fallback={…}>…</Show>`
84
+ )
85
+ },
55
86
  fix: (fixer) =>
56
87
  fixer.replaceText(
57
88
  node.parent?.type === "JSXExpressionContainer" &&
58
89
  isJSXElementOrFragment(node.parent.parent)
59
90
  ? node.parent
60
91
  : node,
61
- `<Show when={${sourceCode.getText(node.test)}} fallback={${sourceCode.getText(node.alternate)}}>${putIntoJSX(node.consequent)}</Show>`,
62
- ),
92
+ `<Show when={${sourceCode.getText(node.test)}} fallback={${sourceCode.getText(node.alternate)}}>${putIntoJSX(node.consequent)}</Show>`
93
+ )
63
94
  });
64
95
  }
65
96
  };
@@ -83,7 +114,7 @@ export default {
83
114
  ) {
84
115
  conditionalExpressionHandler(node.expression.body);
85
116
  }
86
- },
117
+ }
87
118
  };
88
- },
119
+ }
89
120
  };