Skip to content

Commit

Permalink
[stylelint-plugin] fix(no-color-literal): autofix correct name (#4867)
Browse files Browse the repository at this point in the history
Co-authored-by: Patrick Szmucer <pszmucer@palantir.com>
  • Loading branch information
patrickszmucer and Patrick Szmucer authored Aug 20, 2021
1 parent 6aae550 commit b42e9ab
Showing 1 changed file with 15 additions and 5 deletions.
20 changes: 15 additions & 5 deletions packages/stylelint-plugin/src/rules/no-color-literal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,19 +103,18 @@ export default stylelint.createPlugin(ruleName, ((
if (type !== "word" || !isHexColor(value)) {
return;
}
const normalizedHex = normalizeHexColor(value);
if (hexToColorName[normalizedHex] == null) {
const cssVar = getCssColorVariable(value, cssSyntax);
if (cssVar == null) {
return;
}
const fixed = BpVariablePrefixMap[cssSyntax] + hexToColorName[normalizedHex].toLocaleLowerCase();
if ((context as any).fix && !disableFix) {
assertBpVariablesImportExists(cssSyntax);
node.value = fixed;
node.value = cssVar;
needsFix = true;
} else {
stylelint.utils.report({
index: declarationValueIndex(decl) + node.sourceIndex,
message: messages.expected(value, fixed),
message: messages.expected(value, cssVar),
node: decl,
result,
ruleName,
Expand All @@ -134,6 +133,17 @@ function declarationValueIndex(decl: postcss.Declaration) {
return beforeColon + afterColon;
}

/**
* Returns a CSS color variable for a given hex color, or undefined if one doesn't exist.
*/
function getCssColorVariable(hexColor: string, cssSyntax: CssSyntax.SASS | CssSyntax.LESS): string | undefined {
const normalizedHex = normalizeHexColor(hexColor);
if (hexToColorName[normalizedHex] == null) {
return undefined;
}
return BpVariablePrefixMap[cssSyntax] + hexToColorName[normalizedHex].toLocaleLowerCase().split("_").join("-");
}

function getHexToColorName(): { [upperHex: string]: string } {
const ret: { [key: string]: string } = {};
for (const [name, hex] of Object.entries(Colors)) {
Expand Down

1 comment on commit b42e9ab

@blueprint-bot
Copy link

Choose a reason for hiding this comment

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

[stylelint-plugin] fix(no-color-literal): autofix correct name (#4867)

Previews: documentation | landing | table

Please sign in to comment.