|
| 1 | +import type { AST } from "svelte-eslint-parser" |
| 2 | +import { createRule } from "../utils" |
| 3 | + |
| 4 | +export default createRule("first-attribute-linebreak", { |
| 5 | + meta: { |
| 6 | + docs: { |
| 7 | + description: "enforce the location of first attribute", |
| 8 | + category: "Stylistic Issues", |
| 9 | + recommended: false, |
| 10 | + }, |
| 11 | + fixable: "whitespace", |
| 12 | + schema: [ |
| 13 | + { |
| 14 | + type: "object", |
| 15 | + properties: { |
| 16 | + multiline: { enum: ["below", "beside"] }, |
| 17 | + singleline: { enum: ["below", "beside"] }, |
| 18 | + }, |
| 19 | + additionalProperties: false, |
| 20 | + }, |
| 21 | + ], |
| 22 | + messages: { |
| 23 | + expected: "Expected a linebreak before this attribute.", |
| 24 | + unexpected: "Expected no linebreak before this attribute.", |
| 25 | + }, |
| 26 | + type: "layout", |
| 27 | + }, |
| 28 | + create(context) { |
| 29 | + const multiline: "below" | "beside" = |
| 30 | + context.options[0]?.multiline || "below" |
| 31 | + const singleline: "below" | "beside" = |
| 32 | + context.options[0]?.singleline || "beside" |
| 33 | + const sourceCode = context.getSourceCode() |
| 34 | + |
| 35 | + /** |
| 36 | + * Report attribute |
| 37 | + */ |
| 38 | + function report( |
| 39 | + firstAttribute: AST.SvelteStartTag["attributes"][number], |
| 40 | + location: "below" | "beside", |
| 41 | + ) { |
| 42 | + context.report({ |
| 43 | + node: firstAttribute, |
| 44 | + messageId: location === "beside" ? "unexpected" : "expected", |
| 45 | + fix(fixer) { |
| 46 | + const prevToken = sourceCode.getTokenBefore(firstAttribute, { |
| 47 | + includeComments: true, |
| 48 | + })! |
| 49 | + return fixer.replaceTextRange( |
| 50 | + [prevToken.range[1], firstAttribute.range[0]], |
| 51 | + location === "beside" ? " " : "\n", |
| 52 | + ) |
| 53 | + }, |
| 54 | + }) |
| 55 | + } |
| 56 | + |
| 57 | + return { |
| 58 | + SvelteStartTag(node) { |
| 59 | + const firstAttribute = node.attributes[0] |
| 60 | + if (!firstAttribute) return |
| 61 | + |
| 62 | + const lastAttribute = node.attributes[node.attributes.length - 1] |
| 63 | + |
| 64 | + const location = |
| 65 | + firstAttribute.loc.start.line === lastAttribute.loc.end.line |
| 66 | + ? singleline |
| 67 | + : multiline |
| 68 | + |
| 69 | + if (location === "beside") { |
| 70 | + if ( |
| 71 | + node.parent.name.loc!.end.line === firstAttribute.loc.start.line |
| 72 | + ) { |
| 73 | + return |
| 74 | + } |
| 75 | + } else { |
| 76 | + if (node.parent.name.loc!.end.line < firstAttribute.loc.start.line) { |
| 77 | + return |
| 78 | + } |
| 79 | + } |
| 80 | + report(firstAttribute, location) |
| 81 | + }, |
| 82 | + } |
| 83 | + }, |
| 84 | +}) |
0 commit comments