Skip to content
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

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

Open
wants to merge 3 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 @@ -335,6 +335,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 @@ -92,6 +92,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 @@ -306,6 +306,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 @@ -532,6 +537,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
122 changes: 122 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,122 @@
import { createRule } from '../utils/index.js';
import { type TSTools, getTypeScriptTools } from '../utils/ts-utils/index.js';
import {
type MethodSignature,
type Symbol,
SymbolFlags,
SyntaxKind,
type Type,
type TypeReferenceNode,
type PropertySignature
} 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) &&
!property.getName().startsWith('on') &&
(checkAsyncFunctions || !isFunctionAsync(property))
) {
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): boolean {
return (
(functionSymbol.getFlags() & SymbolFlags.Method) !== 0 ||
(functionSymbol.valueDeclaration?.kind === SyntaxKind.PropertySignature &&
(functionSymbol.valueDeclaration as PropertySignature).type?.kind === SyntaxKind.FunctionType)
);
}

function isFunctionAsync(functionSymbol: Symbol): boolean {
return (
functionSymbol.getDeclarations()?.some((declaration) => {
if (declaration.kind !== SyntaxKind.MethodSignature) {
return false;
}
const declarationType = (declaration as MethodSignature).type;
if (declarationType?.kind !== SyntaxKind.TypeReference) {
return false;
}
const declarationTypeName = (declarationType as TypeReferenceNode).typeName;
return (
declarationTypeName.kind === SyntaxKind.Identifier &&
declarationTypeName.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 @@ -60,6 +60,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 @@ -133,6 +134,7 @@ export const rules = [
preferStyleDirective,
requireEachKey,
requireEventDispatcherTypes,
requireEventPrefix,
requireOptimizedStyleAttribute,
requireStoreCallbacksUseSetParam,
requireStoreReactiveAccess,
Expand Down
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"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<script lang="ts">
interface Props {
custom: any;
}

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

console.log(custom);
</script>
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,9 @@
<script lang="ts">
interface Props {
custom: number;
}

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

console.log(custom);
</script>
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<script lang="ts">
interface Props {
oncustom(): void;
}

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

oncustom();
</script>
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { RuleTester } from '../../utils/eslint-compat.js';
import rule from '../../../src/rules/require-event-prefix.js';
import { loadTestCases } from '../../utils/utils.js';

const tester = new RuleTester({
languageOptions: {
ecmaVersion: 2020,
sourceType: 'module'
}
});

tester.run('require-event-prefix', rule as any, loadTestCases('require-event-prefix'));