Skip to content
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
41 changes: 38 additions & 3 deletions src/rules/no-important.js
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right now, if somehow the CSS comment before the !important flag contains the !important, then the rule reports the one inside the comment.

a { color: red /* !important flag 1 */ !important; }


/* after fix the output will be */
a { color: red /*  flag 1 */ !important; }

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I opened #218 to address this.

Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,17 @@ import { findOffsets } from "../util.js";

/**
* @import { CSSRuleDefinition } from "../types.js"
* @typedef {"unexpectedImportant"} NoImportantMessageIds
* @typedef {"unexpectedImportant" | "removeImportant"} NoImportantMessageIds
* @typedef {CSSRuleDefinition<{ RuleOptions: [], MessageIds: NoImportantMessageIds }>} NoImportantRuleDefinition
*/

//-----------------------------------------------------------------------------
// Helpers
//-----------------------------------------------------------------------------

const importantPattern = /!(\s|\/\*.*?\*\/)*important/iu;
const trailingWhitespacePattern = /\s*$/u;

//-----------------------------------------------------------------------------
// Rule Definition
//-----------------------------------------------------------------------------
Expand All @@ -29,6 +36,8 @@ export default {
meta: {
type: "problem",

hasSuggestions: true,

docs: {
description: "Disallow !important flags",
recommended: true,
Expand All @@ -37,12 +46,11 @@ export default {

messages: {
unexpectedImportant: "Unexpected !important flag found.",
removeImportant: "Remove !important flag.",
},
},

create(context) {
const importantPattern = /!(\s|\/\*.*?\*\/)*important/iu;

return {
Declaration(node) {
if (node.important) {
Expand Down Expand Up @@ -86,6 +94,33 @@ export default {
},
},
messageId: "unexpectedImportant",
suggest: [
{
messageId: "removeImportant",
fix(fixer) {
const importantStart = importantMatch.index;
const importantEnd =
importantStart +
importantMatch[0].length;

// Find any trailing whitespace before the !important
const valuePart = declarationText.slice(
0,
importantStart,
);
const whitespaceEnd = valuePart.search(
trailingWhitespacePattern,
);

const start =
node.loc.start.offset + whitespaceEnd;
const end =
node.loc.start.offset + importantEnd;

return fixer.removeRange([start, end]);
},
},
],
});
}
},
Expand Down
Loading
Loading