|
| 1 | +import { createRule } from "../utils" |
| 2 | +import type { AST } from "svelte-eslint-parser" |
| 3 | + |
| 4 | +export default createRule("no-spaces-around-equal-signs-in-attribute", { |
| 5 | + meta: { |
| 6 | + docs: { |
| 7 | + description: "disallow spaces around equal signs in attribute", |
| 8 | + category: "Stylistic Issues", |
| 9 | + recommended: false, |
| 10 | + conflictWithPrettier: true, |
| 11 | + }, |
| 12 | + schema: {}, |
| 13 | + fixable: "whitespace", |
| 14 | + messages: { |
| 15 | + noSpaces: "Unexpected spaces found around equal signs.", |
| 16 | + }, |
| 17 | + type: "layout", |
| 18 | + }, |
| 19 | + create(ctx) { |
| 20 | + const source = ctx.getSourceCode() |
| 21 | + |
| 22 | + /** |
| 23 | + * Returns source text between attribute key and value, and range of that source |
| 24 | + */ |
| 25 | + function getAttrEq( |
| 26 | + node: |
| 27 | + | AST.SvelteAttribute |
| 28 | + | AST.SvelteDirective |
| 29 | + | AST.SvelteStyleDirective |
| 30 | + | AST.SvelteSpecialDirective, |
| 31 | + ): [string, AST.Range] { |
| 32 | + const keyRange = node.key.range |
| 33 | + const eqSource = /^[\s=]*/u.exec( |
| 34 | + source.text.slice(keyRange[1], node.range[1]), |
| 35 | + )![0] |
| 36 | + const valueStart = keyRange[1] + eqSource.length |
| 37 | + return [eqSource, [keyRange[1], valueStart]] |
| 38 | + } |
| 39 | + |
| 40 | + /** |
| 41 | + * Returns true if string contains whitespace characters |
| 42 | + */ |
| 43 | + function containsWhitespace(string: string): boolean { |
| 44 | + return /\s/u.test(string) |
| 45 | + } |
| 46 | + |
| 47 | + return { |
| 48 | + "SvelteAttribute, SvelteDirective, SvelteStyleDirective, SvelteSpecialDirective"( |
| 49 | + node: |
| 50 | + | AST.SvelteAttribute |
| 51 | + | AST.SvelteDirective |
| 52 | + | AST.SvelteStyleDirective |
| 53 | + | AST.SvelteSpecialDirective, |
| 54 | + ) { |
| 55 | + const [eqSource, range] = getAttrEq(node) |
| 56 | + |
| 57 | + if (!containsWhitespace(eqSource)) return |
| 58 | + |
| 59 | + const loc = { |
| 60 | + start: source.getLocFromIndex(range[0]), |
| 61 | + end: source.getLocFromIndex(range[1]), |
| 62 | + } |
| 63 | + |
| 64 | + ctx.report({ |
| 65 | + loc, |
| 66 | + messageId: "noSpaces", |
| 67 | + *fix(fixer) { |
| 68 | + yield fixer.replaceTextRange(range, "=") |
| 69 | + }, |
| 70 | + }) |
| 71 | + }, |
| 72 | + } |
| 73 | + }, |
| 74 | +}) |
0 commit comments