Skip to content
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

[stylelint-plugin] feat: add no-color-literal rule #4853

Merged
merged 8 commits into from
Aug 11, 2021
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
1 change: 1 addition & 0 deletions .stylelintrc
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
],
"rules": {
"@blueprintjs/no-prefix-literal": [true, { "disableFix": true }],
"@blueprintjs/no-color-literal": [true, { "disableFix": true }],
"declaration-empty-line-before": null,
"indentation": [2, {
"ignore": ["value"]
Expand Down
2 changes: 2 additions & 0 deletions packages/core/src/blueprint-hi-contrast.scss
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ Licensed under the Apache License, Version 2.0.

*/

/* stylelint-disable @blueprintjs/no-color-literal */

// override some intent colors to pass contrast requirements
$pt-intent-primary: #106ba3 !default; // $blue2
$pt-intent-success: #0d8050 !default; // $green2;
Expand Down
2 changes: 2 additions & 0 deletions packages/core/src/common/_colors.scss
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Copyright 2015 Palantir Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0.

/* stylelint-disable @blueprintjs/no-color-literal */

// Gray scale

$black: #10161a !default;
Expand Down
30 changes: 30 additions & 0 deletions packages/stylelint-plugin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,43 @@ Simply add this plugin in your `.stylelintrc` file and then pick the rules that
"@blueprintjs/stylelint-plugin"
],
"rules": {
"@blueprintjs/no-color-literal": true,
"@blueprintjs/no-prefix-literal": true
}
}
```

## Rules

### `@blueprintjs/no-color-literal` (autofixable)

Enforce usage of the color variables instead of color literals.

```json
{
"rules": {
"@blueprintjs/no-color-literal": true
}
}
```

```diff
-.my-class {
- border: 1px solid #137CBD;
-}
+ @import "~@blueprntjs/core/lib/scss/variables";
+
+.my-class {
+ border: 1px solid $blue3;
+}
```

Optional secondary options:

- `disableFix: boolean` - if true, autofix will be disabled
- `variablesImportPath: { less?: string, sass?: string }` - can be used to configure a custom path for importing Blueprint variables when autofixing.


### `@blueprintjs/no-prefix-literal` (autofixable)

Enforce usage of the `bp-ns` constant over namespaced string literals.
Expand Down
4 changes: 3 additions & 1 deletion packages/stylelint-plugin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@
"test": "mocha test/index.js"
},
"dependencies": {
"@blueprintjs/core": "^3.47.0",
"postcss": "^7.0.35",
"postcss-selector-parser": "^6.0.5"
"postcss-selector-parser": "^6.0.5",
"postcss-value-parser": "^4.1.0"
},
"peerDependencies": {
"stylelint": "^13.0.0"
Expand Down
3 changes: 2 additions & 1 deletion packages/stylelint-plugin/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
* limitations under the License.
*/

import noColorLiteral from "./rules/no-color-literal";
import noPrefixLiteral from "./rules/no-prefix-literal";

export default [noPrefixLiteral];
export default [noPrefixLiteral, noColorLiteral];
145 changes: 145 additions & 0 deletions packages/stylelint-plugin/src/rules/no-color-literal.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
/*
* Copyright 2021 Palantir Technologies, Inc. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import postcss, { Root, Result } from "postcss";
import valueParser from "postcss-value-parser";
import stylelint, { RuleTesterContext } from "stylelint";
import type { Plugin } from "stylelint";

import { Colors } from "@blueprintjs/core";

import { checkImportExists } from "../utils/checkImportExists";
import {
BpVariableImportMap,
BpVariablePrefixMap,
CssExtensionMap,
CssSyntax,
getCssSyntax,
isCssSyntaxToStringMap,
} from "../utils/cssSyntax";
import { isHexColor, normalizeHexColor } from "../utils/hexColor";
import { insertImport } from "../utils/insertImport";

const ruleName = "@blueprintjs/no-color-literal";

const messages = stylelint.utils.ruleMessages(ruleName, {
expected: (unfixed: string, fixed: string) => `Use the \`${fixed}\` variable instead of the \`${unfixed}\` literal`,
});

interface Options {
disableFix?: boolean;
variablesImportPath?: Partial<Record<Exclude<CssSyntax, CssSyntax.OTHER>, string>>;
}

export default stylelint.createPlugin(ruleName, ((
enabled: boolean,
options: Options | undefined,
context: RuleTesterContext,
) => (root: Root, result: Result) => {
if (!enabled) {
return;
}

const validOptions = stylelint.utils.validateOptions(
result,
ruleName,
{
actual: enabled,
optional: false,
possible: [true, false],
},
{
actual: options,
optional: true,
possible: {
disableFix: [true, false],
variablesImportPath: isCssSyntaxToStringMap,
},
},
);

if (!validOptions) {
return;
}

const disableFix = options?.disableFix ?? false;

const cssSyntax = getCssSyntax(root.source?.input.file || "");
if (cssSyntax === CssSyntax.OTHER) {
return;
}

let hasBpVariablesImport: boolean | undefined; // undefined means not checked yet
function assertBpVariablesImportExists(cssSyntaxType: CssSyntax.SASS | CssSyntax.LESS) {
const importPath = options?.variablesImportPath?.[cssSyntaxType] ?? BpVariableImportMap[cssSyntaxType];
const extension = CssExtensionMap[cssSyntaxType];
if (hasBpVariablesImport == null) {
hasBpVariablesImport = checkImportExists(root, [importPath, `${importPath}.${extension}`]);
}
if (!hasBpVariablesImport) {
insertImport(root, context, importPath);
hasBpVariablesImport = true;
}
}

root.walkDecls(decl => {
let needsFix = false;
const parsedValue = valueParser(decl.value);
parsedValue.walk(node => {
const value = node.value;
const type = node.type;
if (type !== "word" || !isHexColor(value)) {
return;
}
const normalizedHex = normalizeHexColor(value);
if (hexToColorName[normalizedHex] == null) {
return;
}
const fixed = BpVariablePrefixMap[cssSyntax] + hexToColorName[normalizedHex].toLocaleLowerCase();
if ((context as any).fix && !disableFix) {
assertBpVariablesImportExists(cssSyntax);
node.value = fixed;
needsFix = true;
} else {
stylelint.utils.report({
index: declarationValueIndex(decl) + node.sourceIndex,
message: messages.expected(value, fixed),
node: decl,
result,
ruleName,
});
}
});
if (needsFix) {
decl.value = parsedValue.toString();
}
});
}) as Plugin);

function declarationValueIndex(decl: postcss.Declaration) {
const beforeColon = decl.toString().indexOf(":");
const afterColon = decl.raw("between").length - decl.raw("between").indexOf(":");
return beforeColon + afterColon;
}

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

const hexToColorName = getHexToColorName();
50 changes: 9 additions & 41 deletions packages/stylelint-plugin/src/rules/no-prefix-literal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,14 @@ import stylelint from "stylelint";
import type { Plugin, RuleTesterContext } from "stylelint";

import { checkImportExists } from "../utils/checkImportExists";
import {
BpPrefixVariableMap,
BpVariableImportMap,
CssExtensionMap,
CssSyntax,
getCssSyntax,
isCssSyntaxToStringMap,
} from "../utils/cssSyntax";
import { insertImport } from "../utils/insertImport";

const ruleName = "@blueprintjs/no-prefix-literal";
Expand Down Expand Up @@ -56,14 +64,7 @@ export default stylelint.createPlugin(ruleName, ((
optional: true,
possible: {
disableFix: [true, false],
variablesImportPath: (obj: unknown) => {
if (typeof obj !== "object" || obj == null) {
return false;
}
// Check that the keys and their values are correct
const allowedKeys = new Set<string>(Object.values(CssSyntax).filter(v => v !== CssSyntax.OTHER));
return Object.keys(obj).every(key => allowedKeys.has(key) && typeof (obj as any)[key] === "string");
},
variablesImportPath: isCssSyntaxToStringMap,
},
},
);
Expand Down Expand Up @@ -120,36 +121,3 @@ export default stylelint.createPlugin(ruleName, ((
}).processSync(rule.selector);
});
}) as Plugin);

enum CssSyntax {
SASS = "sass",
LESS = "less",
OTHER = "other",
}

const CssExtensionMap: Record<Exclude<CssSyntax, CssSyntax.OTHER>, string> = {
[CssSyntax.SASS]: "scss",
[CssSyntax.LESS]: "less",
};

const BpPrefixVariableMap: Record<Exclude<CssSyntax, CssSyntax.OTHER>, string> = {
[CssSyntax.SASS]: "#{$bp-ns}",
[CssSyntax.LESS]: "@{bp-ns}",
};

const BpVariableImportMap: Record<Exclude<CssSyntax, CssSyntax.OTHER>, string> = {
[CssSyntax.SASS]: "~@blueprintjs/core/lib/scss/variables",
[CssSyntax.LESS]: "~@blueprintjs/core/lib/less/variables",
};

/**
* Returns the flavor of the CSS we're dealing with.
*/
function getCssSyntax(fileName: string): CssSyntax {
for (const cssSyntax of Object.keys(CssExtensionMap)) {
if (fileName.endsWith(`.${CssExtensionMap[cssSyntax as Exclude<CssSyntax, CssSyntax.OTHER>]}`)) {
return cssSyntax as Exclude<CssSyntax, CssSyntax.OTHER>;
}
}
return CssSyntax.OTHER;
}
60 changes: 60 additions & 0 deletions packages/stylelint-plugin/src/utils/cssSyntax.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/* Copyright 2020 Palantir Technologies, Inc. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/

export enum CssSyntax {
SASS = "sass",
LESS = "less",
OTHER = "other",
}

export const CssExtensionMap: Record<Exclude<CssSyntax, CssSyntax.OTHER>, string> = {
[CssSyntax.SASS]: "scss",
[CssSyntax.LESS]: "less",
};

export const BpVariablePrefixMap: Record<Exclude<CssSyntax, CssSyntax.OTHER>, string> = {
[CssSyntax.SASS]: "$",
[CssSyntax.LESS]: "@",
};

export const BpPrefixVariableMap: Record<Exclude<CssSyntax, CssSyntax.OTHER>, string> = {
[CssSyntax.SASS]: "#{$bp-ns}",
[CssSyntax.LESS]: "@{bp-ns}",
};

export const BpVariableImportMap: Record<Exclude<CssSyntax, CssSyntax.OTHER>, string> = {
[CssSyntax.SASS]: "~@blueprintjs/core/lib/scss/variables",
[CssSyntax.LESS]: "~@blueprintjs/core/lib/less/variables",
};

/**
* Returns the flavor of the CSS we're dealing with.
*/
export function getCssSyntax(fileName: string): CssSyntax {
for (const cssSyntax of Object.keys(CssExtensionMap)) {
if (fileName.endsWith(`.${CssExtensionMap[cssSyntax as Exclude<CssSyntax, CssSyntax.OTHER>]}`)) {
return cssSyntax as Exclude<CssSyntax, CssSyntax.OTHER>;
}
}
return CssSyntax.OTHER;
}

export const isCssSyntaxToStringMap = (obj: unknown): obj is { [S in CssSyntax]?: string } => {
if (typeof obj !== "object" || obj == null) {
return false;
}
// Check that the keys and their values are correct
const allowedKeys = new Set<string>(Object.values(CssSyntax).filter(v => v !== CssSyntax.OTHER));
return Object.keys(obj).every(key => allowedKeys.has(key) && typeof (obj as any)[key] === "string");
};
32 changes: 32 additions & 0 deletions packages/stylelint-plugin/src/utils/hexColor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/* Copyright 2020 Palantir Technologies, Inc. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/

const HEX_COLOR_REGEX = /^#(?:[0-9a-fA-F]{3}){1,2}$/;

export function isHexColor(maybeHex: string): boolean {
return HEX_COLOR_REGEX.test(maybeHex);
}

export function normalizeHexColor(hex: string): string {
if (!isHexColor(hex)) {
return hex;
}
let normalized = hex.toLocaleUpperCase();
const isThreeLetterHex = normalized.length === 4; // Three letters plus "#"
if (isThreeLetterHex) {
const [, r, g, b] = normalized;
normalized = `#${r}${r}${g}${g}${b}${b}`;
}
return normalized;
}
Loading