Skip to content

feat: added the require-event-prefix rule #1069

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 5 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
5 changes: 5 additions & 0 deletions .changeset/rich-dogs-design.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'eslint-plugin-svelte': minor
---

feat: added the `require-event-prefix` rule
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,7 @@ These rules relate to style guidelines, and are therefore quite subjective:
| [svelte/no-spaces-around-equal-signs-in-attribute](https://sveltejs.github.io/eslint-plugin-svelte/rules/no-spaces-around-equal-signs-in-attribute/) | disallow spaces around equal signs in attribute | :wrench: |
| [svelte/prefer-class-directive](https://sveltejs.github.io/eslint-plugin-svelte/rules/prefer-class-directive/) | require class directives instead of ternary expressions | :wrench: |
| [svelte/prefer-style-directive](https://sveltejs.github.io/eslint-plugin-svelte/rules/prefer-style-directive/) | require style directives instead of style attribute | :wrench: |
| [svelte/require-event-prefix](https://sveltejs.github.io/eslint-plugin-svelte/rules/require-event-prefix/) | require component event names to start with "on" | |
| [svelte/shorthand-attribute](https://sveltejs.github.io/eslint-plugin-svelte/rules/shorthand-attribute/) | enforce use of shorthand syntax in attribute | :wrench: |
| [svelte/shorthand-directive](https://sveltejs.github.io/eslint-plugin-svelte/rules/shorthand-directive/) | enforce use of shorthand syntax in directives | :wrench: |
| [svelte/sort-attributes](https://sveltejs.github.io/eslint-plugin-svelte/rules/sort-attributes/) | enforce order of attributes | :wrench: |
Expand Down
1 change: 1 addition & 0 deletions docs/rules.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ These rules relate to style guidelines, and are therefore quite subjective:
| [svelte/no-spaces-around-equal-signs-in-attribute](./rules/no-spaces-around-equal-signs-in-attribute.md) | disallow spaces around equal signs in attribute | :wrench: |
| [svelte/prefer-class-directive](./rules/prefer-class-directive.md) | require class directives instead of ternary expressions | :wrench: |
| [svelte/prefer-style-directive](./rules/prefer-style-directive.md) | require style directives instead of style attribute | :wrench: |
| [svelte/require-event-prefix](./rules/require-event-prefix.md) | require component event names to start with "on" | |
| [svelte/shorthand-attribute](./rules/shorthand-attribute.md) | enforce use of shorthand syntax in attribute | :wrench: |
| [svelte/shorthand-directive](./rules/shorthand-directive.md) | enforce use of shorthand syntax in directives | :wrench: |
| [svelte/sort-attributes](./rules/sort-attributes.md) | enforce order of attributes | :wrench: |
Expand Down
71 changes: 71 additions & 0 deletions docs/rules/require-event-prefix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
---
pageClass: 'rule-details'
sidebarDepth: 0
title: 'svelte/require-event-prefix'
description: 'require component event names to start with "on"'
---

# svelte/require-event-prefix

> require component event names to start with "on"

- :exclamation: <badge text="This rule has not been released yet." vertical="middle" type="error"> **_This rule has not been released yet._** </badge>

## :book: Rule Details

Starting with Svelte 5, component events are just component props that are functions and so can be called like any function. Events for HTML elements all have their name begin with "on" (e.g. `onclick`). This rule enforces that all component events (i.e. function props) also begin with "on".

<!--eslint-skip-->

```svelte
<script lang="ts">
/* eslint svelte/require-event-prefix: "error" */

/* ✓ GOOD */

interface Props {
regularProp: string;
onclick(): void;
}

let { regularProp, onclick }: Props = $props();
</script>
```

```svelte
<script lang="ts">
/* eslint svelte/require-event-prefix: "error" */

/* ✗ BAD */

interface Props {
click(): void;
}

let { click }: Props = $props();
</script>
```

## :wrench: Options

```json
{
"svelte/require-event-prefix": [
"error",
{
"checkAsyncFunctions": false
}
]
}
```

- `checkAsyncFunctions` ... Whether to also report asychronous function properties. Default `false`.

## :books: Further Reading

- [Svelte docs on events in version 5](https://svelte.dev/docs/svelte/v5-migration-guide#Event-changes)

## :mag: Implementation

- [Rule source](https://github.com/sveltejs/eslint-plugin-svelte/blob/main/packages/eslint-plugin-svelte/src/rules/require-event-prefix.ts)
- [Test source](https://github.com/sveltejs/eslint-plugin-svelte/blob/main/packages/eslint-plugin-svelte/tests/src/rules/require-event-prefix.ts)
9 changes: 9 additions & 0 deletions packages/eslint-plugin-svelte/src/rule-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,11 @@ export interface RuleOptions {
* @see https://sveltejs.github.io/eslint-plugin-svelte/rules/require-event-dispatcher-types/
*/
'svelte/require-event-dispatcher-types'?: Linter.RuleEntry<[]>
/**
* require component event names to start with "on"
* @see https://sveltejs.github.io/eslint-plugin-svelte/rules/require-event-prefix/
*/
'svelte/require-event-prefix'?: Linter.RuleEntry<SvelteRequireEventPrefix>
/**
* require style attributes that can be optimized
* @see https://sveltejs.github.io/eslint-plugin-svelte/rules/require-optimized-style-attribute/
Expand Down Expand Up @@ -553,6 +558,10 @@ type SveltePreferConst = []|[{
ignoreReadBeforeAssign?: boolean
excludedRunes?: string[]
}]
// ----- svelte/require-event-prefix -----
type SvelteRequireEventPrefix = []|[{
checkAsyncFunctions?: boolean
}]
// ----- svelte/shorthand-attribute -----
type SvelteShorthandAttribute = []|[{
prefer?: ("always" | "never")
Expand Down
123 changes: 123 additions & 0 deletions packages/eslint-plugin-svelte/src/rules/require-event-prefix.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import { createRule } from '../utils/index.js';
import {
type TSTools,
getTypeScriptTools,
isMethodSymbol,
isPropertySignatureKind,
isFunctionTypeKind,
isMethodSignatureKind,
isTypeReferenceKind,
isIdentifierKind
} from '../utils/ts-utils/index.js';
import type { Symbol, Type } from 'typescript';
import type { CallExpression } from 'estree';

export default createRule('require-event-prefix', {
meta: {
docs: {
description: 'require component event names to start with "on"',
category: 'Stylistic Issues',
conflictWithPrettier: false,
recommended: false
},
schema: [
{
type: 'object',
properties: {
checkAsyncFunctions: {
type: 'boolean'
}
},
additionalProperties: false
}
],
messages: {
nonPrefixedFunction: 'Component event name must start with "on".'
},
type: 'suggestion',
conditions: [
{
svelteVersions: ['5'],
svelteFileTypes: ['.svelte']
}
]
},
create(context) {
const tsTools = getTypeScriptTools(context);
if (!tsTools) {
return {};
}

const checkAsyncFunctions = context.options[0]?.checkAsyncFunctions ?? false;

return {
CallExpression(node) {
const propsType = getPropsType(node, tsTools);
if (propsType === undefined) {
return;
}
for (const property of propsType.getProperties()) {
if (
isFunctionLike(property, tsTools) &&
!property.getName().startsWith('on') &&
(checkAsyncFunctions || !isFunctionAsync(property, tsTools))
) {
const declarationTsNode = property.getDeclarations()?.[0];
const declarationEstreeNode =
declarationTsNode !== undefined
? tsTools.service.tsNodeToESTreeNodeMap.get(declarationTsNode)
: undefined;
context.report({
node: declarationEstreeNode ?? node,
messageId: 'nonPrefixedFunction'
});
}
}
}
};
}
});

function getPropsType(node: CallExpression, tsTools: TSTools): Type | undefined {
if (
node.callee.type !== 'Identifier' ||
node.callee.name !== '$props' ||
node.parent.type !== 'VariableDeclarator'
) {
return undefined;
}

const tsNode = tsTools.service.esTreeNodeToTSNodeMap.get(node.parent.id);
if (tsNode === undefined) {
return undefined;
}

return tsTools.service.program.getTypeChecker().getTypeAtLocation(tsNode);
}

function isFunctionLike(functionSymbol: Symbol, tsTools: TSTools): boolean {
return (
isMethodSymbol(functionSymbol, tsTools.ts) ||
(functionSymbol.valueDeclaration !== undefined &&
isPropertySignatureKind(functionSymbol.valueDeclaration, tsTools.ts) &&
functionSymbol.valueDeclaration.type !== undefined &&
isFunctionTypeKind(functionSymbol.valueDeclaration.type, tsTools.ts))
);
}

function isFunctionAsync(functionSymbol: Symbol, tsTools: TSTools): boolean {
return (
functionSymbol.getDeclarations()?.some((declaration) => {
if (!isMethodSignatureKind(declaration, tsTools.ts)) {
return false;
}
if (declaration.type === undefined || !isTypeReferenceKind(declaration.type, tsTools.ts)) {
return false;
}
return (
isIdentifierKind(declaration.type.typeName, tsTools.ts) &&
declaration.type.typeName.escapedText === 'Promise'
);
}) ?? false
);
}
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 @@ -62,6 +62,7 @@ import preferDestructuredStoreProps from '../rules/prefer-destructured-store-pro
import preferStyleDirective from '../rules/prefer-style-directive.js';
import requireEachKey from '../rules/require-each-key.js';
import requireEventDispatcherTypes from '../rules/require-event-dispatcher-types.js';
import requireEventPrefix from '../rules/require-event-prefix.js';
import requireOptimizedStyleAttribute from '../rules/require-optimized-style-attribute.js';
import requireStoreCallbacksUseSetParam from '../rules/require-store-callbacks-use-set-param.js';
import requireStoreReactiveAccess from '../rules/require-store-reactive-access.js';
Expand Down Expand Up @@ -137,6 +138,7 @@ export const rules = [
preferStyleDirective,
requireEachKey,
requireEventDispatcherTypes,
requireEventPrefix,
requireOptimizedStyleAttribute,
requireStoreCallbacksUseSetParam,
requireStoreReactiveAccess,
Expand Down
45 changes: 45 additions & 0 deletions packages/eslint-plugin-svelte/src/utils/ts-utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -307,3 +307,48 @@ export function getTypeOfPropertyOfType(
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- getTypeOfPropertyOfType is an internal API of TS.
return (checker as any).getTypeOfPropertyOfType(type, name);
}

/**
* Check whether the given symbol is a method type or not.
*/
export function isMethodSymbol(type: TS.Symbol, ts: TypeScript): boolean {
return (type.getFlags() & ts.SymbolFlags.Method) !== 0;
}

/**
* Check whether the given node is a property signature kind or not.
*/
export function isPropertySignatureKind(
node: TS.Node,
ts: TypeScript
): node is TS.PropertySignature {
return node.kind === ts.SyntaxKind.PropertySignature;
}

/**
* Check whether the given node is a function type kind or not.
*/
export function isFunctionTypeKind(node: TS.Node, ts: TypeScript): node is TS.FunctionTypeNode {
return node.kind === ts.SyntaxKind.FunctionType;
}

/**
* Check whether the given node is a method signature kind or not.
*/
export function isMethodSignatureKind(node: TS.Node, ts: TypeScript): node is TS.MethodSignature {
return node.kind === ts.SyntaxKind.MethodSignature;
}

/**
* Check whether the given node is a type reference kind or not.
*/
export function isTypeReferenceKind(node: TS.Node, ts: TypeScript): node is TS.TypeReferenceNode {
return node.kind === ts.SyntaxKind.TypeReference;
}

/**
* Check whether the given node is an identifier kind or not.
*/
export function isIdentifierKind(node: TS.Node, ts: TypeScript): node is TS.Identifier {
return node.kind === ts.SyntaxKind.Identifier;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"svelte": ">=5.0.0"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"options": [{ "checkAsyncFunctions": true }]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"svelte": ">=5.0.0"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
- message: Component event name must start with "on".
line: 3
column: 5
suggestions: null
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<script lang="ts">
interface Props {
custom: () => Promise<void>;
}

let { custom }: Props = $props();

void custom();
</script>
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
- message: Component event name must start with "on".
line: 3
column: 5
suggestions: null
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<script lang="ts">
interface Props {
custom(): Promise<void>;
}

let { custom }: Props = $props();

void custom();
</script>
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
- message: Component event name must start with "on".
line: 3
column: 5
suggestions: null
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<script lang="ts">
interface Props {
custom: () => void;
}

let { custom }: Props = $props();

custom();
</script>
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
- message: Component event name must start with "on".
line: 2
column: 21
suggestions: null
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<script lang="ts">
let { custom }: { custom(): void } = $props();

custom();
</script>
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
- message: Component event name must start with "on".
line: 3
column: 5
suggestions: null
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<script lang="ts">
interface Props {
custom(): void;
}

let { custom }: Props = $props();

custom();
</script>
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"svelte": ">=5.0.0"
}
Loading
Loading