Skip to content

Commit 47e26b3

Browse files
authored
feat: add suggestion to no-important rule to remove !important flag (eslint#217)
* feat: add suggestion to no-important rule to remove !important flag * trim whitespace before !important
1 parent 933d71c commit 47e26b3

File tree

2 files changed

+226
-3
lines changed

2 files changed

+226
-3
lines changed

src/rules/no-important.js

Lines changed: 38 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,17 @@ import { findOffsets } from "../util.js";
1616

1717
/**
1818
* @import { CSSRuleDefinition } from "../types.js"
19-
* @typedef {"unexpectedImportant"} NoImportantMessageIds
19+
* @typedef {"unexpectedImportant" | "removeImportant"} NoImportantMessageIds
2020
* @typedef {CSSRuleDefinition<{ RuleOptions: [], MessageIds: NoImportantMessageIds }>} NoImportantRuleDefinition
2121
*/
2222

23+
//-----------------------------------------------------------------------------
24+
// Helpers
25+
//-----------------------------------------------------------------------------
26+
27+
const importantPattern = /!(\s|\/\*.*?\*\/)*important/iu;
28+
const trailingWhitespacePattern = /\s*$/u;
29+
2330
//-----------------------------------------------------------------------------
2431
// Rule Definition
2532
//-----------------------------------------------------------------------------
@@ -29,6 +36,8 @@ export default {
2936
meta: {
3037
type: "problem",
3138

39+
hasSuggestions: true,
40+
3241
docs: {
3342
description: "Disallow !important flags",
3443
recommended: true,
@@ -37,12 +46,11 @@ export default {
3746

3847
messages: {
3948
unexpectedImportant: "Unexpected !important flag found.",
49+
removeImportant: "Remove !important flag.",
4050
},
4151
},
4252

4353
create(context) {
44-
const importantPattern = /!(\s|\/\*.*?\*\/)*important/iu;
45-
4654
return {
4755
Declaration(node) {
4856
if (node.important) {
@@ -86,6 +94,33 @@ export default {
8694
},
8795
},
8896
messageId: "unexpectedImportant",
97+
suggest: [
98+
{
99+
messageId: "removeImportant",
100+
fix(fixer) {
101+
const importantStart = importantMatch.index;
102+
const importantEnd =
103+
importantStart +
104+
importantMatch[0].length;
105+
106+
// Find any trailing whitespace before the !important
107+
const valuePart = declarationText.slice(
108+
0,
109+
importantStart,
110+
);
111+
const whitespaceEnd = valuePart.search(
112+
trailingWhitespacePattern,
113+
);
114+
115+
const start =
116+
node.loc.start.offset + whitespaceEnd;
117+
const end =
118+
node.loc.start.offset + importantEnd;
119+
120+
return fixer.removeRange([start, end]);
121+
},
122+
},
123+
],
89124
});
90125
}
91126
},

0 commit comments

Comments
 (0)