Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

lint: add no-prevent-default-in-passive-react-handler (#10248)

Cindy Zhangaf701d2428ff
diff --git a/.changeset/carousel-passive-wheel-lint-note.md b/.changeset/carousel-passive-wheel-lint-note.md
new file mode 100644
index 0000000000..d460a70952
--- /dev/null
+++ b/.changeset/carousel-passive-wheel-lint-note.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: Carousel's Shift+wheel handler carries a lint suppression for the new passive-handler rule until it moves to a native listener. Apps see no change.
+
+@cixzhang
diff --git a/eslint.config.js b/eslint.config.js
index 98c32c219d..b83b626f8c 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -1006,6 +1006,19 @@ export default defineConfig(
],
},
},
+ // React attaches its wheel, touchstart and touchmove listeners as passive,
+ // so preventDefault() in those handlers does nothing. Shipped package
+ // source, the same files as the block above.
+ {
+ files: privateAttributeScope.files,
+ ignores: privateAttributeScope.ignores,
+ plugins: {
+ '@astryx': astryxEslintPlugin,
+ },
+ rules: {
+ '@astryx/no-prevent-default-in-passive-react-handler': 'error',
+ },
+ },
// A source comment explains a reason, a constraint, or a quirk. It does not
// cite a record, a claim, a pull request, an issue, or a date, and it does
// not quote requirement text: the record links the code, and
diff --git a/internal/eslint-plugin-astryx/README.md b/internal/eslint-plugin-astryx/README.md
index 813045a370..b4704565b0 100644
--- a/internal/eslint-plugin-astryx/README.md
+++ b/internal/eslint-plugin-astryx/README.md
@@ -1233,3 +1233,41 @@ existing. Each wants a token decision rather
than a mechanical substitution, so they are tracked separately; promote a
package to `error` once it reaches zero, the same path
`no-physical-properties` took.
+
+### `@astryx/no-prevent-default-in-passive-react-handler`
+
+Reports `preventDefault()` on the event inside a React `onWheel`,
+`onTouchStart` or `onTouchMove` handler, or their capture forms. React attaches
+its root `wheel`, `touchstart` and `touchmove` listeners as passive, and the
+browser ignores `preventDefault()` in a passive listener: the page still
+scrolls or zooms, and `event.defaultPrevented` stays `false`. A handler that
+must cancel the default uses a native listener added with `{passive: false}`,
+in an Effect or a ref callback.
+
+```tsx
+// flagged
+<div
+ onWheel={e => {
+ e.preventDefault();
+ zoom(e.deltaY);
+ }}
+/>;
+const handleWheel = useCallback(event => event.preventDefault(), []);
+<div onWheel={handleWheel} />;
+
+// fine
+<div onTouchEnd={e => e.preventDefault()} />;
+useEffect(() => {
+ const node = ref.current;
+ const onWheel = event => event.preventDefault();
+ node.addEventListener('wheel', onWheel, {passive: false});
+ return () => node.removeEventListener('wheel', onWheel);
+}, []);
+```
+
+It follows an inline function, or an identifier that names a function in the
+same file (a declaration, a function or arrow, or a `useCallback` of one), and
+reports `<event>.preventDefault()` and `<event>.nativeEvent.preventDefault()`
+on the handler's first parameter. It does not follow a handler imported from
+another module or a function the handler calls. The repo config turns it on at
+`error` for `packages/*/src`, outside tests, stories and test helpers.
diff --git a/internal/eslint-plugin-astryx/index.js b/internal/eslint-plugin-astryx/index.js
index addd1befb4..0ba702e350 100644
--- a/internal/eslint-plugin-astryx/index.js
+++ b/internal/eslint-plugin-astryx/index.js
@@ -24,6 +24,7 @@
* - no-light-dark-outside-theme: Flags CSS light-dark() in component source (a light/dark decision belongs to the theme layer, where a token pair reaches both schemes in every theme)
* - no-core-internal-import: Keeps Core's internal subpaths (@astryxdesign/core/internal/*) inside Core and Lab
* - no-internal-barrel-import: Flags a package-internal relative import that resolves to a folder's index (a barrel) instead of the defining module
+ * - no-prevent-default-in-passive-react-handler: Flags preventDefault() on the event in a React onWheel/onTouchStart/onTouchMove handler (React attaches those listeners as passive, so the call is ignored)
* - no-raw-private-attribute: Flags a private data-astryx-* attribute written by hand outside its owner module in packages/<package>/src/privateAttributes (INV23 lists the public ones)
* - no-comment-provenance: Flags record and claim ids, pull request and issue references, date stamps, and quoted MUST/SHALL text in source comments (the record links the code; `pnpm specs:for <path>` finds it)
* - no-raw-color: Flags a raw colour value (hex, rgb(), hsl(), oklch(), …) anywhere in component source, including inside light-dark()/color-mix(), behind a const, in a template literal, or as a var() fallback — the shapes no-hardcoded-styles cannot see
@@ -70,6 +71,7 @@ import requireTableSectionRule from './require-table-section.js';
import noLightDarkOutsideThemeRule from './no-light-dark-outside-theme.js';
import noRawColorRule from './no-raw-color.js';
import noRawPrivateAttributeRule from './no-raw-private-attribute.js';
+import noPreventDefaultInPassiveReactHandlerRule from './no-prevent-default-in-passive-react-handler.js';
// =============================================================================
// Rule: no-hardcoded-styles
@@ -376,6 +378,8 @@ const plugin = {
'no-light-dark-outside-theme': noLightDarkOutsideThemeRule,
'no-raw-color': noRawColorRule,
'no-raw-private-attribute': noRawPrivateAttributeRule,
+ 'no-prevent-default-in-passive-react-handler':
+ noPreventDefaultInPassiveReactHandlerRule,
'no-comment-provenance': noCommentProvenanceRule,
},
configs: {},
diff --git a/internal/eslint-plugin-astryx/no-prevent-default-in-passive-react-handler.js b/internal/eslint-plugin-astryx/no-prevent-default-in-passive-react-handler.js
new file mode 100644
index 0000000000..b803cc99b7
--- /dev/null
+++ b/internal/eslint-plugin-astryx/no-prevent-default-in-passive-react-handler.js
@@ -0,0 +1,186 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file no-prevent-default-in-passive-react-handler.js
+ * @description Reports `preventDefault()` on the event inside a React
+ * `onWheel`, `onTouchStart` or `onTouchMove` handler (capture forms too).
+ *
+ * React attaches its root `wheel`, `touchstart` and `touchmove` listeners as
+ * passive. The browser ignores `preventDefault()` in a passive listener, so
+ * the default action (scroll, zoom) still runs and `defaultPrevented` stays
+ * false. A handler that must cancel the default uses a native listener added
+ * with `{passive: false}`, in an Effect or a ref callback.
+ *
+ * Reported: a call to `<event>.preventDefault()` or
+ * `<event>.nativeEvent.preventDefault()`, where `<event>` is the first
+ * parameter of a function passed to one of those JSX props as an inline
+ * function, or as an identifier that names a function declared in the same
+ * file (a function declaration, a function or arrow, or a `useCallback` of
+ * one).
+ *
+ * Not reported: other props (`onTouchEnd`, `onPointer*`), native
+ * `addEventListener` listeners, a handler imported from another module or
+ * reached through another variable, and a call inside a function that the
+ * handler only calls.
+ */
+
+const PASSIVE_PROPS = new Set([
+ 'onWheel',
+ 'onWheelCapture',
+ 'onTouchStart',
+ 'onTouchStartCapture',
+ 'onTouchMove',
+ 'onTouchMoveCapture',
+]);
+
+const FUNCTIONS = new Set([
+ 'FunctionDeclaration',
+ 'FunctionExpression',
+ 'ArrowFunctionExpression',
+]);
+
+function isUseCallback(node) {
+ if (node?.type !== 'CallExpression') {
+ return false;
+ }
+ const callee = node.callee;
+ return (
+ (callee.type === 'Identifier' && callee.name === 'useCallback') ||
+ (callee.type === 'MemberExpression' &&
+ !callee.computed &&
+ callee.property.type === 'Identifier' &&
+ callee.property.name === 'useCallback')
+ );
+}
+
+/** The function an initializer holds, directly or through `useCallback`. */
+function functionOf(node) {
+ if (node == null) {
+ return null;
+ }
+ if (FUNCTIONS.has(node.type)) {
+ return node;
+ }
+ if (isUseCallback(node) && FUNCTIONS.has(node.arguments[0]?.type)) {
+ return node.arguments[0];
+ }
+ return null;
+}
+
+function isPropertyNamed(member, name) {
+ return (
+ member.type === 'MemberExpression' &&
+ !member.computed &&
+ member.property.type === 'Identifier' &&
+ member.property.name === name
+ );
+}
+
+const rule = {
+ meta: {
+ type: 'problem',
+ docs: {
+ description:
+ 'Disallow preventDefault() in React onWheel, onTouchStart and onTouchMove handlers, which React attaches as passive listeners',
+ },
+ schema: [],
+ messages: {
+ passive:
+ 'React attaches wheel/touchstart/touchmove listeners as passive; preventDefault() here is ignored. ' +
+ 'Use a native listener with {passive: false} (addEventListener in an Effect or a ref callback) instead.',
+ },
+ },
+ create(context) {
+ const sourceCode = context.sourceCode ?? context.getSourceCode();
+ // One handler can serve several props; report each call once.
+ const reported = new Set();
+
+ /** The handler function a JSX prop value names, when it can be read. */
+ function handlerOf(expression, attribute) {
+ const direct = functionOf(expression);
+ if (direct != null) {
+ return direct;
+ }
+ if (expression.type !== 'Identifier') {
+ return null;
+ }
+ let scope = sourceCode.getScope(attribute);
+ while (scope != null) {
+ const variable = scope.set.get(expression.name);
+ if (variable != null) {
+ const definition = variable.defs[0];
+ if (definition?.type === 'FunctionName') {
+ return definition.node;
+ }
+ if (
+ definition?.type === 'Variable' &&
+ definition.node.id.type === 'Identifier'
+ ) {
+ return functionOf(definition.node.init);
+ }
+ return null;
+ }
+ scope = scope.upper;
+ }
+ return null;
+ }
+
+ function checkHandler(fn) {
+ const event = fn.params[0];
+ if (event?.type !== 'Identifier') {
+ return;
+ }
+ const variable = sourceCode
+ .getDeclaredVariables(fn)
+ .find(declared => declared.name === event.name);
+ if (variable == null) {
+ return;
+ }
+ for (const reference of variable.references) {
+ let target = reference.identifier;
+ if (
+ isPropertyNamed(target.parent, 'nativeEvent') &&
+ target.parent.object === target
+ ) {
+ target = target.parent;
+ }
+ const member = target.parent;
+ if (
+ member == null ||
+ member.object !== target ||
+ !isPropertyNamed(member, 'preventDefault')
+ ) {
+ continue;
+ }
+ const call = member.parent;
+ if (
+ call?.type !== 'CallExpression' ||
+ call.callee !== member ||
+ reported.has(call)
+ ) {
+ continue;
+ }
+ reported.add(call);
+ context.report({node: call, messageId: 'passive'});
+ }
+ }
+
+ return {
+ JSXAttribute(node) {
+ if (
+ node.name.type !== 'JSXIdentifier' ||
+ !PASSIVE_PROPS.has(node.name.name) ||
+ node.value?.type !== 'JSXExpressionContainer'
+ ) {
+ return;
+ }
+ const fn = handlerOf(node.value.expression, node);
+ if (fn != null) {
+ checkHandler(fn);
+ }
+ },
+ };
+ },
+};
+
+export default rule;
diff --git a/internal/eslint-plugin-astryx/no-prevent-default-in-passive-react-handler.test.mjs b/internal/eslint-plugin-astryx/no-prevent-default-in-passive-react-handler.test.mjs
new file mode 100644
index 0000000000..213985a6ab
--- /dev/null
+++ b/internal/eslint-plugin-astryx/no-prevent-default-in-passive-react-handler.test.mjs
@@ -0,0 +1,120 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file no-prevent-default-in-passive-react-handler.test.mjs
+ * @description Tests for the Astryx no-prevent-default-in-passive-react-handler
+ * ESLint rule.
+ */
+
+import {RuleTester} from 'eslint';
+import tseslint from 'typescript-eslint';
+import rule from './no-prevent-default-in-passive-react-handler.js';
+
+const tester = new RuleTester({
+ languageOptions: {
+ parser: tseslint.parser,
+ parserOptions: {
+ ecmaVersion: 2022,
+ sourceType: 'module',
+ ecmaFeatures: {jsx: true},
+ },
+ },
+});
+
+const passive = [{messageId: 'passive'}];
+
+// 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-prevent-default-in-passive-react-handler', rule, {
+ valid: [
+ // ✅ onTouchEnd is not passive.
+ {code: `const C = () => <div onTouchEnd={e => e.preventDefault()} />;`},
+ // ✅ Pointer handlers are not passive.
+ {
+ code: `const C = () => <div onPointerDown={e => e.preventDefault()} onPointerMove={e => e.preventDefault()} />;`,
+ },
+ // ✅ A native listener added with {passive: false}.
+ {
+ code: `
+ function useWheel(ref) {
+ useEffect(() => {
+ const node = ref.current;
+ const onWheel = event => event.preventDefault();
+ node.addEventListener('wheel', onWheel, {passive: false});
+ return () => node.removeEventListener('wheel', onWheel);
+ }, [ref]);
+ }
+ `,
+ },
+ // ✅ A passive handler that does not cancel.
+ {
+ code: `const C = () => <div onWheel={() => { last.current = 'wheel'; }} />;`,
+ },
+ {code: `const C = () => <div onTouchMove={e => track(e.touches[0])} />;`},
+ // ✅ preventDefault on something other than the handler's event.
+ {
+ code: `const C = ({other}) => <div onWheel={() => other.preventDefault()} />;`,
+ },
+ // ✅ A handler imported from another module is not followed.
+ {
+ code: `import {handleWheel} from './wheel'; const C = () => <div onWheel={handleWheel} />;`,
+ },
+ ],
+ invalid: [
+ // ❌ An inline arrow.
+ {
+ code: `const C = () => <div onWheel={e => { e.preventDefault(); }} />;`,
+ errors: passive,
+ },
+ // ❌ A useCallback handler.
+ {
+ code: `
+ function Carousel() {
+ const handleWheel = useCallback((event) => {
+ if (!event.shiftKey) return;
+ event.preventDefault();
+ scroll(event.deltaY);
+ }, []);
+ return <div onWheel={handleWheel} />;
+ }
+ `,
+ errors: passive,
+ },
+ // ❌ React.useCallback, a function declaration and a function expression.
+ {
+ code: `
+ function C() {
+ const onMove = React.useCallback(function (e) { e.preventDefault(); }, []);
+ return <div onTouchMove={onMove} />;
+ }
+ `,
+ errors: passive,
+ },
+ {
+ code: `
+ function onStart(e) { e.preventDefault(); }
+ const C = () => <div onTouchStart={onStart} />;
+ `,
+ errors: passive,
+ },
+ // ❌ Capture forms, nativeEvent, optional call.
+ {
+ code: `const C = () => <div onWheelCapture={e => e.nativeEvent.preventDefault()} />;`,
+ errors: passive,
+ },
+ {
+ code: `const C = () => <div onTouchMoveCapture={e => e.preventDefault?.()} />;`,
+ errors: passive,
+ },
+ // ❌ One handler on two passive props is reported once.
+ {
+ code: `
+ function C() {
+ const stop = e => e.preventDefault();
+ return <div onTouchStart={stop} onTouchMove={stop} />;
+ }
+ `,
+ errors: passive,
+ },
+ ],
+});
diff --git a/packages/core/src/Carousel/Carousel.tsx b/packages/core/src/Carousel/Carousel.tsx
index 24eed800a0..77ae24ab93 100644
--- a/packages/core/src/Carousel/Carousel.tsx
+++ b/packages/core/src/Carousel/Carousel.tsx
@@ -504,6 +504,7 @@ export function Carousel({
if (el.scrollWidth <= el.clientWidth) {
return;
}
+ // eslint-disable-next-line @astryx/no-prevent-default-in-passive-react-handler -- passive React handler: preventDefault() is ignored; a native non-passive listener replaces it
event.preventDefault();
el.scrollBy({left: event.deltaY, behavior: 'auto'});
}, []);