Skip to content

feat: add no-add-event-listener rule #1197

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,7 @@ These rules relate to better ways of doing things to help you avoid problems:
|:--------|:------------|:---|
| [svelte/block-lang](https://sveltejs.github.io/eslint-plugin-svelte/rules/block-lang/) | disallows the use of languages other than those specified in the configuration for the lang attribute of `<script>` and `<style>` blocks. | :bulb: |
| [svelte/button-has-type](https://sveltejs.github.io/eslint-plugin-svelte/rules/button-has-type/) | disallow usage of button without an explicit type attribute | |
| [svelte/no-add-event-listener](https://sveltejs.github.io/eslint-plugin-svelte/rules/no-add-event-listener/) | Warns against the use of `addEventListener` | :bulb: |
| [svelte/no-at-debug-tags](https://sveltejs.github.io/eslint-plugin-svelte/rules/no-at-debug-tags/) | disallow the use of `{@debug}` | :star::bulb: |
| [svelte/no-ignored-unsubscribe](https://sveltejs.github.io/eslint-plugin-svelte/rules/no-ignored-unsubscribe/) | disallow ignoring the unsubscribe method returned by the `subscribe()` on Svelte stores. | |
| [svelte/no-immutable-reactive-statements](https://sveltejs.github.io/eslint-plugin-svelte/rules/no-immutable-reactive-statements/) | disallow reactive statements that don't reference reactive values. | :star: |
Expand Down
1 change: 1 addition & 0 deletions docs/rules.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ These rules relate to better ways of doing things to help you avoid problems:
| :--------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------- | :------------- |
| [svelte/block-lang](./rules/block-lang.md) | disallows the use of languages other than those specified in the configuration for the lang attribute of `<script>` and `<style>` blocks. | :bulb: |
| [svelte/button-has-type](./rules/button-has-type.md) | disallow usage of button without an explicit type attribute | |
| [svelte/no-add-event-listener](./rules/no-add-event-listener.md) | Warns against the use of `addEventListener` | :bulb: |
| [svelte/no-at-debug-tags](./rules/no-at-debug-tags.md) | disallow the use of `{@debug}` | :star::bulb: |
| [svelte/no-ignored-unsubscribe](./rules/no-ignored-unsubscribe.md) | disallow ignoring the unsubscribe method returned by the `subscribe()` on Svelte stores. | |
| [svelte/no-immutable-reactive-statements](./rules/no-immutable-reactive-statements.md) | disallow reactive statements that don't reference reactive values. | :star: |
Expand Down
42 changes: 42 additions & 0 deletions docs/rules/no-add-event-listener.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
---
pageClass: 'rule-details'
sidebarDepth: 0
title: 'svelte/no-add-event-listener'
description: 'Warns against the use of `addEventListener`'
---

# svelte/no-add-event-listener

> Warns against the use of `addEventListener`

- :exclamation: <badge text="This rule has not been released yet." vertical="middle" type="error"> **_This rule has not been released yet._** </badge>
- :bulb: Some problems reported by this rule are manually fixable by editor [suggestions](https://eslint.org/docs/developer-guide/working-with-rules#providing-suggestions).

## :book: Rule Details

This rule reports usages of `addEventListener`:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it better?

Suggested change
This rule reports usages of `addEventListener`:
Svelte relies on event delegation for performance and predictable handler order. Calling `addEventListener` inside a component skips this mechanism. This rule reports any call to `addEventListener` suggests converting to the `on()` helper from `svelte/events`.


<!--eslint-skip-->

```svelte
<!-- ✓ GOOD -->
<script>
/* eslint svelte/no-add-event-listener: "error" */
on(window, 'resize', handler);
</script>
```

<!--eslint-skip-->

```svelte
<!-- ✗ BAD -->
<script>
/* eslint svelte/no-add-event-listener: "error" */
window.addEventListener('resize', handler);
</script>
```

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add these 2 links in Further reading section? (IIRC, the original template has "Further reading" section.)

https://svelte.dev/docs/svelte/basic-markup#Events-Event-delegation
https://svelte.dev/docs/svelte/svelte-events#on

## :mag: Implementation

- [Rule source](https://github.com/sveltejs/eslint-plugin-svelte/blob/main/packages/eslint-plugin-svelte/src/rules/no-add-event-listener.ts)
- [Test source](https://github.com/sveltejs/eslint-plugin-svelte/blob/main/packages/eslint-plugin-svelte/tests/src/rules/no-add-event-listener.ts)
5 changes: 5 additions & 0 deletions packages/eslint-plugin-svelte/src/rule-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,11 @@ export interface RuleOptions {
* @see https://sveltejs.github.io/eslint-plugin-svelte/rules/mustache-spacing/
*/
'svelte/mustache-spacing'?: Linter.RuleEntry<SvelteMustacheSpacing>
/**
* Warns against the use of `addEventListener`
* @see https://sveltejs.github.io/eslint-plugin-svelte/rules/no-add-event-listener/
*/
'svelte/no-add-event-listener'?: Linter.RuleEntry<[]>
/**
* disallow the use of `{@debug}`
* @see https://sveltejs.github.io/eslint-plugin-svelte/rules/no-at-debug-tags/
Expand Down
74 changes: 74 additions & 0 deletions packages/eslint-plugin-svelte/src/rules/no-add-event-listener.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import type { TSESTree } from '@typescript-eslint/types';

import { createRule } from '../utils/index.js';
import type { SuggestionReportDescriptor } from '../types.js';

export default createRule('no-add-event-listener', {
meta: {
docs: {
description: 'Warns against the use of `addEventListener`',
category: 'Best Practices',
recommended: false,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you think this should be shipped as a recommended rule? (It might cause a lot of errors in existing code, though.)
cc: @ota-meshi

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ultimately i think it should be recommended, but im not sure how we can do that without introducing loads of errors like you say 🤔 it'd have to be in the next major i suppose

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let’s make it recommended in the next major release.

default: 'warn'
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why was the default set to warn?

},
hasSuggestions: true,
schema: [],
messages: {
unexpected:
'Do not use `addEventListener`. Use the `on` function from `svelte/events` instead.'
},
type: 'suggestion',
conditions: [
{
svelteVersions: ['5']
}
]
},
create(context) {
return {
CallExpression(node: TSESTree.CallExpression) {
const { callee, arguments: args } = node;
let target: string | null = null;

if (args.length < 2 || args.length > 3) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we check such weird pattern? 😅

<script>
	const foo = ['resize', () => { console.log('resized!') }]
	window.addEventListner(...foo);
</script>

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Even if suggestions aren’t possible, maybe it’s fine to just report any use of addEventListener.

return;
}

if (
callee.type === 'MemberExpression' &&
callee.property.type === 'Identifier' &&
callee.property.name === 'addEventListener'
) {
target = context.sourceCode.getText(callee.object);
} else if (callee.type === 'Identifier' && callee.name === 'addEventListener') {
target = 'window';
}

if (target === null) {
return;
}

const openParen = context.sourceCode.getTokenAfter(callee);
const suggest: SuggestionReportDescriptor[] = [];

if (openParen !== null) {
suggest.push({
desc: 'Use `on` from `svelte/events` instead',
fix(fixer) {
return [
fixer.replaceText(callee, 'on'),
fixer.insertTextAfter(openParen, `${target}, `)
];
}
});
}

context.report({
node,
messageId: 'unexpected',
suggest
});
}
};
}
});
2 changes: 2 additions & 0 deletions packages/eslint-plugin-svelte/src/utils/rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import indent from '../rules/indent.js';
import infiniteReactiveLoop from '../rules/infinite-reactive-loop.js';
import maxAttributesPerLine from '../rules/max-attributes-per-line.js';
import mustacheSpacing from '../rules/mustache-spacing.js';
import noAddEventListener from '../rules/no-add-event-listener.js';
import noAtDebugTags from '../rules/no-at-debug-tags.js';
import noAtHtmlTags from '../rules/no-at-html-tags.js';
import noDomManipulating from '../rules/no-dom-manipulating.js';
Expand Down Expand Up @@ -94,6 +95,7 @@ export const rules = [
infiniteReactiveLoop,
maxAttributesPerLine,
mustacheSpacing,
noAddEventListener,
noAtDebugTags,
noAtHtmlTags,
noDomManipulating,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"svelte": ">=5.0.0-0"
}
Loading
Loading