Skip to content

Improve prefer-style-directive rule #111

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

Merged
merged 1 commit into from
Feb 8, 2022
Merged
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
243 changes: 187 additions & 56 deletions src/rules/prefer-style-directive.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import type { AST } from "svelte-eslint-parser"
import type * as ESTree from "estree"
import type { Root } from "postcss"
import { parse as parseCss } from "postcss"
import { createRule } from "../utils"

Expand All @@ -11,6 +13,13 @@ function safeParseCss(cssCode: string) {
}
}

/** Checks wether the given node is string literal or not */
function isStringLiteral(
node: ESTree.Expression,
): node is ESTree.Literal & { value: string } {
return node.type === "Literal" && typeof node.value === "string"
}

export default createRule("prefer-style-directive", {
meta: {
docs: {
Expand All @@ -27,6 +36,179 @@ export default createRule("prefer-style-directive", {
},
create(context) {
const sourceCode = context.getSourceCode()

/**
* Process for `style=" ... "`
*/
function processStyleValue(
node: AST.SvelteAttribute,
root: Root,
mustacheTags: AST.SvelteMustacheTagText[],
) {
const valueStartIndex = node.value[0].range[0]

root.walkDecls((decl) => {
if (
node.parent.attributes.some(
(attr) =>
attr.type === "SvelteStyleDirective" &&
attr.key.name.name === decl.prop,
)
) {
// has style directive
return
}

const declRange: AST.Range = [
valueStartIndex + decl.source!.start!.offset,
valueStartIndex + decl.source!.end!.offset + 1,
]
if (
mustacheTags.some(
(tag) =>
(tag.range[0] < declRange[0] && declRange[0] < tag.range[1]) ||
(tag.range[0] < declRange[1] && declRange[1] < tag.range[1]),
)
) {
// intersection
return
}
const declValueStartIndex =
declRange[0] + decl.prop.length + (decl.raws.between || "").length
const declValueRange: AST.Range = [
declValueStartIndex,
declValueStartIndex + (decl.raws.value?.value || decl.value).length,
]

context.report({
node,
messageId: "unexpected",
*fix(fixer) {
const styleDirective = `style:${decl.prop}="${sourceCode.text.slice(
...declValueRange,
)}"`
if (root.nodes.length === 1 && root.nodes[0] === decl) {
yield fixer.replaceTextRange(node.range, styleDirective)
} else {
yield fixer.removeRange(declRange)
yield fixer.insertTextAfterRange(node.range, ` ${styleDirective}`)
}
},
})
})
}

/**
* Process for `style="{a ? 'color: red;': ''}"`
*/
function processMustacheTags(
mustacheTags: AST.SvelteMustacheTagText[],
attrNode: AST.SvelteAttribute,
) {
for (const mustacheTag of mustacheTags) {
processMustacheTag(mustacheTag, attrNode)
}
}

/**
* Process for `style="{a ? 'color: red;': ''}"`
*/
function processMustacheTag(
mustacheTag: AST.SvelteMustacheTagText,
attrNode: AST.SvelteAttribute,
) {
const node = mustacheTag.expression

if (node.type !== "ConditionalExpression") {
return
}
if (
!isStringLiteral(node.consequent) ||
!isStringLiteral(node.alternate)
) {
return
}
if (node.consequent.value && node.alternate.value) {
// e.g. t ? 'top: 20px' : 'left: 30px'
return
}
const positive = node.alternate.value === ""
const root = safeParseCss(
positive ? node.consequent.value : node.alternate.value,
)
if (!root || root.nodes.length !== 1) {
return
}
const decl = root.nodes[0]
if (decl.type !== "decl") {
return
}
if (
attrNode.parent.attributes.some(
(attr) =>
attr.type === "SvelteStyleDirective" &&
attr.key.name.name === decl.prop,
)
) {
// has style directive
return
}

context.report({
node,
messageId: "unexpected",
*fix(fixer) {
let valueText = sourceCode.text.slice(
node.test.range![0],
node.consequent.range![0],
)
if (positive) {
valueText +=
sourceCode.text[node.consequent.range![0]] +
decl.value +
sourceCode.text[node.consequent.range![1] - 1]
} else {
valueText += "null"
}
valueText += sourceCode.text.slice(
node.consequent.range![1],
node.alternate.range![0],
)
if (positive) {
valueText += "null"
} else {
valueText +=
sourceCode.text[node.alternate.range![0]] +
decl.value +
sourceCode.text[node.alternate.range![1] - 1]
}
const styleDirective = `style:${decl.prop}={${valueText}}`
if (
attrNode.value
.filter((v) => v !== mustacheTag)
.every((v) => v.type === "SvelteLiteral" && !v.value.trim())
) {
yield fixer.replaceTextRange(attrNode.range, styleDirective)
} else {
const first = attrNode.value[0]
if (first !== mustacheTag) {
yield fixer.replaceTextRange(
[first.range[0], mustacheTag.range[0]],
sourceCode.text
.slice(first.range[0], mustacheTag.range[0])
.trimEnd(),
)
}
yield fixer.removeRange(mustacheTag.range)
yield fixer.insertTextAfterRange(
attrNode.range,
` ${styleDirective}`,
)
}
},
})
}

return {
"SvelteStartTag > SvelteAttribute"(
node: AST.SvelteAttribute & {
Expand All @@ -37,9 +219,8 @@ export default createRule("prefer-style-directive", {
return
}
const mustacheTags = node.value.filter(
(v) => v.type === "SvelteMustacheTag",
(v): v is AST.SvelteMustacheTagText => v.type === "SvelteMustacheTag",
)
const valueStartIndex = node.value[0].range[0]
const cssCode = node.value
.map((value) => {
if (value.type === "SvelteMustacheTag") {
Expand All @@ -49,61 +230,11 @@ export default createRule("prefer-style-directive", {
})
.join("")
const root = safeParseCss(cssCode)
if (!root) {
return
if (root) {
processStyleValue(node, root, mustacheTags)
} else {
processMustacheTags(mustacheTags, node)
}
root.walkDecls((decl) => {
if (
node.parent.attributes.some(
(attr) =>
attr.type === "SvelteStyleDirective" &&
attr.key.name.name === decl.prop,
)
) {
// has style directive
return
}

const declRange: AST.Range = [
valueStartIndex + decl.source!.start!.offset,
valueStartIndex + decl.source!.end!.offset + 1,
]
if (
mustacheTags.some(
(tag) =>
(tag.range[0] < declRange[0] && declRange[0] < tag.range[1]) ||
(tag.range[0] < declRange[1] && declRange[1] < tag.range[1]),
)
) {
// intersection
return
}
const declValueStartIndex =
declRange[0] + decl.prop.length + (decl.raws.between || "").length
const declValueRange: AST.Range = [
declValueStartIndex,
declValueStartIndex + (decl.raws.value?.value || decl.value).length,
]

context.report({
node,
messageId: "unexpected",
*fix(fixer) {
const styleDirective = `style:${
decl.prop
}="${sourceCode.text.slice(...declValueRange)}"`
if (root.nodes.length === 1 && root.nodes[0] === decl) {
yield fixer.replaceTextRange(node.range, styleDirective)
} else {
yield fixer.removeRange(declRange)
yield fixer.insertTextAfterRange(
node.range,
` ${styleDirective}`,
)
}
},
})
})
},
}
},
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
[
{
"message": "Can use style directives instead.",
"line": 4,
"column": 6
},
{
"message": "Can use style directives instead.",
"line": 5,
"column": 6
},
{
"message": "Can use style directives instead.",
"line": 9,
"column": 13
}
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<div
style="
position: {position};
{position === 'absolute' ? 'top: 20px;' : ''}
{pointerEvents === false ? 'pointer-events:none;' : ''}
"
/>

<div style={position === "absolute" ? "top: 20px;" : ""} />
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<div
style="
position: {position};
{pointerEvents === false ? 'pointer-events:none;' : ''}
" style:top={position === 'absolute' ? '20px' : null}
/>

<div style:top={position === "absolute" ? "20px" : null} />
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[
{
"message": "Can use style directives instead.",
"line": 4,
"column": 6
}
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<div
style="
position: {position};
{pointerEvents === false ? 'pointer-events:none;' : ''}
"
style:top={position === "absolute" ? "20px" : null}
/>
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<div
style="
position: {position};
" style:pointer-events={pointerEvents === false ? 'none' : null}
style:top={position === "absolute" ? "20px" : null}
/>
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[
{
"message": "Can use style directives instead.",
"line": 3,
"column": 6
}
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<div
style="
{pointerEvents ? '' : 'pointer-events:none'}
"
/>
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<div
style:pointer-events={pointerEvents ? null : 'none'}
/>