An open source design system that's fully customizable and agent ready
TypeScript
feat(eslint-plugin): add no-nullish-jsx-guard rule (#2538) (#3936)
Jiun Shinb26c2b287f9c
diff --git a/internal/eslint-plugin-astryx/README.md b/internal/eslint-plugin-astryx/README.mdindex 4511e2c366..25c7b19f93 100644--- a/internal/eslint-plugin-astryx/README.md+++ b/internal/eslint-plugin-astryx/README.md@@ -227,3 +227,37 @@ export function Badge({label}) {- If the component legitimately needs client behavior, remove it from the presentational listSee: https://github.com/facebook/astryx/issues/493++### `@astryx/no-nullish-jsx-guard`++Flags a bare nullish check (`!= null`, `!== null`, `!== undefined`) used as a JSX render guard for a value that is then rendered as a child. `!= null` only rejects `null`/`undefined`, but React also renders nothing for `false`, `true`, and `''` — all of which pass a `!= null` guard and leak an empty wrapper element into the DOM. Use `isRenderable(value)` from `@astryxdesign/core/utils` instead (it also excludes boolean and empty-string values; `0` stays renderable).++**Scope (deliberately conservative):** only flags when both (1) the guard renders JSX and (2) the guarded value is rendered as a JSX _child_ of that branch. A value used only as a prop (`{user != null && <Profile user={user} />}`) is **not** flagged, since it is a data object, not a rendered slot.++**Bad:**++```tsx+{+ sideNav != null && <aside>{sideNav}</aside>;+}+{+ label != null ? <span>{label}</span> : null;+}+```++**Good:**++```tsx+import {isRenderable} from '@astryxdesign/core/utils';++{+ isRenderable(sideNav) && <aside>{sideNav}</aside>;+}+{+ isRenderable(label) ? <span>{label}</span> : null;+}+```++Ships as a **warning in both tiers** while core migrates its existing call sites; promote to `error` in strict mode once migrated. Provides an ESLint suggestion that rewrites the comparison to `isRenderable(value)` (add the import manually).++See: https://github.com/facebook/astryx/issues/2538diff --git a/internal/eslint-plugin-astryx/index.js b/internal/eslint-plugin-astryx/index.jsindex fb1ed98c9c..a74614ff33 100644--- a/internal/eslint-plugin-astryx/index.js+++ b/internal/eslint-plugin-astryx/index.js@@ -10,6 +10,7 @@* - docblock-example-format: Enforces @example blocks use ``` fenced code on a separate line* - no-raw-paragraph: Disallows components from rendering a <p> by default (render <div> so any content composes)* - no-style-only-wrapper: Disallows div/span wrappers that only style a single Astryx component (use xstyle)+ * - no-nullish-jsx-guard: Flags `!= null` JSX render guards for rendered values (use isRenderable so false/''/true slots don't leak an empty element)** Philosophy: Strict for agents (CI), lenient for humans (local dev)* - "strict" config: All rules as errors - use in CI/agent environments@@ -26,6 +27,7 @@ import noReactIntrospectionRule from './no-react-introspection.js';import noClassnameClobberRule from './no-classname-clobber.js';import noHardcodedAnchorRule from './no-hardcoded-anchor.js';import noRawParagraphRule from './no-raw-paragraph.js';+import noNullishJsxGuardRule from './no-nullish-jsx-guard.js';import noBorderShorthandRule from './no-border-shorthand.js';import noPhysicalPropertiesRule from './no-physical-properties.js';import noReactNamespaceHooksRule from './no-react-namespace-hooks.js';@@ -245,6 +247,7 @@ const plugin = {'no-classname-clobber': noClassnameClobberRule,'no-hardcoded-anchor': noHardcodedAnchorRule,'no-raw-paragraph': noRawParagraphRule,+ 'no-nullish-jsx-guard': noNullishJsxGuardRule,'no-border-shorthand': noBorderShorthandRule,'no-physical-properties': noPhysicalPropertiesRule,'no-react-namespace-hooks': noReactNamespaceHooksRule,@@ -280,6 +283,11 @@ plugin.configs.strict = {'@astryx/no-classname-clobber': 'error','@astryx/no-hardcoded-anchor': 'error','@astryx/no-raw-paragraph': 'error',+ // Rolled out as a warning even in strict mode: core still has ~36 existing+ // `slot != null && <El>{slot}</El>` guards to migrate to isRenderable().+ // Kept as 'warn' so it surfaces everywhere (including CI) without failing+ // the build; promote to 'error' once core is migrated (see issue #2538).+ '@astryx/no-nullish-jsx-guard': 'warn','@astryx/no-border-shorthand': 'error',// RTL physical→logical migration complete; errors to prevent regressions.'@astryx/no-physical-properties': 'error',@@ -309,6 +317,7 @@ plugin.configs.recommended = {'@astryx/no-classname-clobber': 'error','@astryx/no-hardcoded-anchor': 'warn','@astryx/no-raw-paragraph': 'warn',+ '@astryx/no-nullish-jsx-guard': 'warn','@astryx/no-border-shorthand': 'warn',// RTL physical→logical migration complete; errors to prevent regressions.'@astryx/no-physical-properties': 'error',diff --git a/internal/eslint-plugin-astryx/no-nullish-jsx-guard.js b/internal/eslint-plugin-astryx/no-nullish-jsx-guard.jsnew file mode 100644index 0000000000..29283deffc--- /dev/null+++ b/internal/eslint-plugin-astryx/no-nullish-jsx-guard.js@@ -0,0 +1,299 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file no-nullish-jsx-guard.js+ * @description Disallow bare nullish checks (`!= null`, `!== null`,+ * `!== undefined`) as JSX conditional-rendering guards for a rendered value.+ *+ * A common pattern for optionally rendering a slot is:+ *+ * {sideNav != null && <aside>{sideNav}</aside>}+ * {label != null ? <span>{label}</span> : null}+ *+ * `!= null` only rejects `null` and `undefined`. But React treats `false`,+ * `true`, and `''` as "renders nothing" too, and every one of them passes a+ * `!= null` guard:+ *+ * false != null // → true (guard passes, wrapper renders empty)+ * true != null // → true (guard passes, wrapper renders empty)+ * '' != null // → true (guard passes, wrapper renders empty)+ *+ * So a `false`/`true`/`''` slot value slips past the guard and renders an empty+ * (or otherwise meaningless) wrapper element. `isRenderable(value)` from+ * `@astryxdesign/core/utils` is the shipped fix: it returns `false` for+ * `null`, `undefined`, `false`, `true`, and `''`. (Note: `0` is intentionally+ * treated as renderable by `isRenderable` — it produces the visible text "0" —+ * so this rule does NOT try to flag `0`.)+ *+ * @see packages/core/src/utils/isRenderable.ts+ * @see https://github.com/facebook/astryx/issues/2538+ *+ * Scope (deliberately conservative to avoid false positives):+ * Only flags a nullish comparison when BOTH hold —+ * 1. it guards a branch that renders JSX (the `&&` right-hand side, a+ * ternary consequent for `!=`/`!==`, or a ternary alternate for+ * `==`/`===`), and+ * 2. the guarded value itself is rendered as a JSX *child* of that branch+ * (e.g. `{value}` inside the element) — not merely passed as a prop.+ * This targets `ReactNode` slot values (the real leak) and ignores data+ * objects used only to gate a render, e.g.+ * {user != null && <Profile user={user} />} // NOT flagged — `user` is a+ * // data object, only a prop+ *+ * Known limitations (intentional, to keep precision high):+ * - Bare assignments like `const hasFoo = foo != null` are not flagged;+ * distinguishing a `ReactNode` slot from any other nullable value needs+ * type information this syntax-only rule does not have.+ * - Direct value renders such as `{foo != null && foo}` (no wrapper element)+ * are not flagged — the guarded branch is not a JSX element.+ */++// `!= null` / `!== null` / `!== undefined` — the "render when present" polarity.+const NOT_EQUAL_OPERATORS = new Set(['!=', '!==']);+// `== null` / `=== null` / `=== undefined` — the "render in the else branch"+// polarity (used by ternaries like `x == null ? fallback : <JSX>`).+const EQUAL_OPERATORS = new Set(['==', '===']);++/** Is this node the `null` literal? */+function isNullLiteral(node) {+ return node?.type === 'Literal' && node.value === null;+}++/** Is this node the `undefined` identifier? */+function isUndefinedIdentifier(node) {+ return node?.type === 'Identifier' && node.name === 'undefined';+}++function isNullish(node) {+ return isNullLiteral(node) || isUndefinedIdentifier(node);+}++/** Is this node a JSX element or fragment (i.e. it renders markup)? */+function isJSX(node) {+ return node?.type === 'JSXElement' || node?.type === 'JSXFragment';+}++/**+ * If `node` is a nullish comparison (`value <op> null|undefined`), return+ * `{value, equal}` where `value` is the non-nullish operand and `equal` marks+ * `==`/`===` (vs `!=`/`!==`). Otherwise return null.+ */+function parseNullishComparison(node) {+ if (node?.type !== 'BinaryExpression') {+ return null;+ }+ const isNotEqual = NOT_EQUAL_OPERATORS.has(node.operator);+ const isEqual = EQUAL_OPERATORS.has(node.operator);+ if (!isNotEqual && !isEqual) {+ return null;+ }+ let value = null;+ if (isNullish(node.left) && !isNullish(node.right)) {+ value = node.right;+ } else if (isNullish(node.right) && !isNullish(node.left)) {+ value = node.left;+ }+ if (value == null) {+ return null;+ }+ return {value, equal: isEqual};+}++/** Root identifier name of an expression (`a` for `a`, `a.b.c`, `a()`). */+function rootIdentifierName(node) {+ let current = node;+ while (current) {+ switch (current.type) {+ case 'Identifier':+ return current.name;+ case 'MemberExpression':+ current = current.object;+ break;+ case 'ChainExpression':+ current = current.expression;+ break;+ case 'CallExpression':+ current = current.callee;+ break;+ case 'TSNonNullExpression':+ current = current.expression;+ break;+ default:+ return null;+ }+ }+ return null;+}++/**+ * Generic AST walk that invokes `cb(node, parent)` for every child node.+ * Skips the `parent` back-reference to avoid cycles.+ */+function walk(node, parent, cb) {+ if (node == null || typeof node.type !== 'string') {+ return;+ }+ cb(node, parent);+ for (const key of Object.keys(node)) {+ if (key === 'parent') {+ continue;+ }+ const value = node[key];+ if (Array.isArray(value)) {+ for (const item of value) {+ if (item && typeof item.type === 'string') {+ walk(item, node, cb);+ }+ }+ } else if (value && typeof value.type === 'string') {+ walk(value, node, cb);+ }+ }+}++/**+ * Does `rootName` appear inside a JSX *child* expression container of the+ * rendered branch? A child container's parent is a JSXElement/JSXFragment;+ * an attribute value's container has a JSXAttribute parent, so props are+ * excluded.+ */+function isRenderedAsChild(branch, rootName) {+ let found = false;+ walk(branch, null, (node, parent) => {+ if (found) {+ return;+ }+ if (+ node.type === 'JSXExpressionContainer' &&+ (parent?.type === 'JSXElement' || parent?.type === 'JSXFragment')+ ) {+ walk(node.expression, node, (inner, innerParent) => {+ if (found || inner.type !== 'Identifier' || inner.name !== rootName) {+ return;+ }+ // Ignore the `b` in `a.b` (non-computed member property).+ if (+ innerParent?.type === 'MemberExpression' &&+ innerParent.property === inner &&+ !innerParent.computed+ ) {+ return;+ }+ // Ignore the key in `{b: ...}` (non-computed object-property key).+ if (+ innerParent?.type === 'Property' &&+ innerParent.key === inner &&+ !innerParent.computed+ ) {+ return;+ }+ found = true;+ });+ }+ });+ return found;+}++/** Flatten a left-nested `&&` chain into its leaf operands. */+function flattenAnd(node) {+ if (node?.type === 'LogicalExpression' && node.operator === '&&') {+ return [...flattenAnd(node.left), ...flattenAnd(node.right)];+ }+ return [node];+}++const rule = {+ meta: {+ type: 'problem',+ docs: {+ description:+ 'Disallow bare nullish checks (!= null) as JSX render guards for a rendered value — use isRenderable() so false/true/empty-string slots do not leak an empty element',+ category: 'Best Practices',+ recommended: true,+ url: 'https://github.com/facebook/astryx/issues/2538',+ },+ hasSuggestions: true,+ messages: {+ nullishGuard:+ '`{{code}}` guards rendered JSX with a bare nullish check, but `false`, ' ++ '`true`, and `""` all pass `!= null` — leaking an empty wrapper into the ' ++ 'DOM. Use `isRenderable({{value}})` from `@astryxdesign/core/utils`, which ' ++ 'also excludes boolean and empty-string values (0 stays renderable).',+ },+ schema: [],+ },+ create(context) {+ const filename = context.filename ?? context.getFilename();+ // Test/story fixtures intentionally exercise raw patterns.+ if (filename.includes('.test.') || filename.includes('.stories.')) {+ return {};+ }+ const sourceCode = context.sourceCode ?? context.getSourceCode();++ function report(comparison, value, negate) {+ const valueText = sourceCode.getText(value);+ const replacement = `${negate ? '!' : ''}isRenderable(${valueText})`;+ context.report({+ node: comparison,+ messageId: 'nullishGuard',+ data: {+ code: sourceCode.getText(comparison),+ value: valueText,+ },+ suggest: [+ {+ desc: `Replace with ${replacement}`,+ fix(fixer) {+ return fixer.replaceText(comparison, replacement);+ },+ },+ ],+ });+ }++ return {+ // `{value != null && <El>{value}</El>}`+ LogicalExpression(node) {+ if (node.operator !== '&&' || !isJSX(node.right)) {+ return;+ }+ const guards = flattenAnd(node.left);+ for (const guard of guards) {+ const parsed = parseNullishComparison(guard);+ // `&&` only renders when the guard is truthy, so only the+ // "render when present" (`!=`/`!==`) polarity is a leak here.+ if (!parsed || parsed.equal) {+ continue;+ }+ const rootName = rootIdentifierName(parsed.value);+ if (rootName && isRenderedAsChild(node.right, rootName)) {+ report(guard, parsed.value, false);+ break;+ }+ }+ },++ // `{value != null ? <El>{value}</El> : null}`+ // `{value == null ? null : <El>{value}</El>}`+ ConditionalExpression(node) {+ const parsed = parseNullishComparison(node.test);+ if (!parsed) {+ return;+ }+ // `!=`/`!==` renders in the consequent; `==`/`===` renders in the+ // alternate. Only flag when the guarded value is rendered as a child+ // of the branch the guard actually renders.+ const branch = parsed.equal ? node.alternate : node.consequent;+ if (!isJSX(branch)) {+ return;+ }+ const rootName = rootIdentifierName(parsed.value);+ if (rootName && isRenderedAsChild(branch, rootName)) {+ report(node.test, parsed.value, parsed.equal);+ }+ },+ };+ },+};++export default rule;diff --git a/internal/eslint-plugin-astryx/no-nullish-jsx-guard.test.mjs b/internal/eslint-plugin-astryx/no-nullish-jsx-guard.test.mjsnew file mode 100644index 0000000000..b56d915c44--- /dev/null+++ b/internal/eslint-plugin-astryx/no-nullish-jsx-guard.test.mjs@@ -0,0 +1,198 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file no-nullish-jsx-guard.test.mjs+ * @description Tests for the Astryx no-nullish-jsx-guard ESLint rule.+ */++import {RuleTester} from 'eslint';+import tseslint from 'typescript-eslint';+import rule from './no-nullish-jsx-guard.js';++const tester = new RuleTester({+ languageOptions: {+ parser: tseslint.parser,+ parserOptions: {+ ecmaVersion: 2022,+ sourceType: 'module',+ ecmaFeatures: {jsx: true},+ },+ },+});++// RuleTester registers its own describe/it blocks internally, so it must run+// at the top level (Vitest 4 forbids calling suite functions inside an it()).+tester.run('no-nullish-jsx-guard', rule, {+ valid: [+ // ✅ Already using isRenderable — the shipped fix.+ {code: `const C = () => <div>{isRenderable(sideNav) && <aside>{sideNav}</aside>}</div>;`},+ {code: `const C = () => <div>{isRenderable(label) ? <span>{label}</span> : null}</div>;`},++ // ✅ Guarded value is a data object used only as a prop, not rendered as a+ // child — `!= null` is the correct guard, do not flag.+ {code: `const C = () => <div>{user != null && <Profile user={user} />}</div>;`},+ {code: `const C = () => <div>{config !== undefined ? <Widget config={config} /> : null}</div>;`},++ // ✅ Boolean-style guard with no nullish comparison at all.+ {code: `const C = () => <div>{isOpen && <Menu />}</div>;`},+ {code: `const C = () => <div>{hasItems ? <List /> : null}</div>;`},++ // ✅ Nullish comparison but the branch does not render JSX.+ {code: `const C = () => <div>{title != null && title}</div>;`},+ {code: `const x = value != null && doSomething();`},++ // ✅ Nullish comparison guarding JSX, but the guarded value is NOT the+ // thing being rendered (a sibling value is).+ {code: `const C = () => <div>{count != null && <Badge>{label}</Badge>}</div>;`},++ // ✅ Non-nullish comparison (numeric) — out of scope.+ {code: `const C = () => <div>{items.length > 0 && <List>{items}</List>}</div>;`},++ // ✅ Equality nullish check whose rendered branch does not contain the value.+ {code: `const C = () => <div>{value == null ? <Empty /> : <Filled />}</div>;`},++ // ✅ Test fixtures are skipped.+ {+ code: `const C = () => <div>{sideNav != null && <aside>{sideNav}</aside>}</div>;`,+ filename: '/packages/core/src/AppShell/AppShell.test.tsx',+ },+ ],++ invalid: [+ // ❌ Canonical slot leak: `x != null && <El>{x}</El>`.+ {+ code: `const C = () => <div>{sideNav != null && <aside>{sideNav}</aside>}</div>;`,+ errors: [+ {+ messageId: 'nullishGuard',+ suggestions: [+ {+ desc: 'Replace with isRenderable(sideNav)',+ output: `const C = () => <div>{isRenderable(sideNav) && <aside>{sideNav}</aside>}</div>;`,+ },+ ],+ },+ ],+ },+ // ❌ `!== null` variant.+ {+ code: `const C = () => <div>{icon !== null && <span>{icon}</span>}</div>;`,+ errors: [+ {+ messageId: 'nullishGuard',+ suggestions: [+ {+ desc: 'Replace with isRenderable(icon)',+ output: `const C = () => <div>{isRenderable(icon) && <span>{icon}</span>}</div>;`,+ },+ ],+ },+ ],+ },+ // ❌ `!== undefined` variant.+ {+ code: `const C = () => <div>{footer !== undefined && <footer>{footer}</footer>}</div>;`,+ errors: [+ {+ messageId: 'nullishGuard',+ suggestions: [+ {+ desc: 'Replace with isRenderable(footer)',+ output: `const C = () => <div>{isRenderable(footer) && <footer>{footer}</footer>}</div>;`,+ },+ ],+ },+ ],+ },+ // ❌ Reversed operand order: `null != x`.+ {+ code: `const C = () => <div>{null != banner && <header>{banner}</header>}</div>;`,+ errors: [+ {+ messageId: 'nullishGuard',+ suggestions: [+ {+ desc: 'Replace with isRenderable(banner)',+ output: `const C = () => <div>{isRenderable(banner) && <header>{banner}</header>}</div>;`,+ },+ ],+ },+ ],+ },+ // ❌ Extra conjuncts in the `&&` chain — the nullish guard is still flagged.+ {+ code: `const C = () => <div>{metadata != null && !isSystem && <div>{metadata}</div>}</div>;`,+ errors: [+ {+ messageId: 'nullishGuard',+ suggestions: [+ {+ desc: 'Replace with isRenderable(metadata)',+ output: `const C = () => <div>{isRenderable(metadata) && !isSystem && <div>{metadata}</div>}</div>;`,+ },+ ],+ },+ ],+ },+ // ❌ Member-expression slot value rendered as a child.+ {+ code: `const C = () => <div>{call.node != null && <pre>{call.node}</pre>}</div>;`,+ errors: [+ {+ messageId: 'nullishGuard',+ suggestions: [+ {+ desc: 'Replace with isRenderable(call.node)',+ output: `const C = () => <div>{isRenderable(call.node) && <pre>{call.node}</pre>}</div>;`,+ },+ ],+ },+ ],+ },+ // ❌ Ternary consequent render (`!=` polarity).+ {+ code: `const C = () => <div>{label != null ? <span>{label}</span> : null}</div>;`,+ errors: [+ {+ messageId: 'nullishGuard',+ suggestions: [+ {+ desc: 'Replace with isRenderable(label)',+ output: `const C = () => <div>{isRenderable(label) ? <span>{label}</span> : null}</div>;`,+ },+ ],+ },+ ],+ },+ // ❌ Ternary alternate render (`==` polarity) — suggests `!isRenderable`.+ {+ code: `const C = () => <div>{label == null ? null : <span>{label}</span>}</div>;`,+ errors: [+ {+ messageId: 'nullishGuard',+ suggestions: [+ {+ desc: 'Replace with !isRenderable(label)',+ output: `const C = () => <div>{!isRenderable(label) ? null : <span>{label}</span>}</div>;`,+ },+ ],+ },+ ],+ },+ // ❌ Value rendered nested deeper inside the branch, via an expression.+ {+ code: `const C = () => <div>{title != null && <h1><Trim>{title.trim()}</Trim></h1>}</div>;`,+ errors: [+ {+ messageId: 'nullishGuard',+ suggestions: [+ {+ desc: 'Replace with isRenderable(title)',+ output: `const C = () => <div>{isRenderable(title) && <h1><Trim>{title.trim()}</Trim></h1>}</div>;`,+ },+ ],+ },+ ],+ },+ ],+});