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

chore: Eslint custom plugin to warn about hex and literal colors #19239

Merged
merged 9 commits into from
Mar 28, 2022
Merged
Show file tree
Hide file tree
Changes from 4 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
3 changes: 2 additions & 1 deletion superset-frontend/.eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ module.exports = {
version: 'detect',
},
},
plugins: ['prettier', 'react', 'file-progress'],
plugins: ['prettier', 'react', 'file-progress', 'theme-colors'],
overrides: [
{
files: ['*.ts', '*.tsx'],
Expand Down Expand Up @@ -185,6 +185,7 @@ module.exports = {
},
],
rules: {
'theme-colors/no-literal-colors': 1,
camelcase: [
'error',
{
Expand Down
172 changes: 172 additions & 0 deletions superset-frontend/buildtools/eslint-plugin-theme-colors/colors.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/

// https://www.w3.org/wiki/CSS/Properties/color/keywords
module.exports = [
'black',
'silver',
'gray',
'grey',
'white',
'maroon',
'red',
'purple',
'fuchsia',
'green',
'lime',
'olive',
'yellow',
'navy',
'blue',
'teal',
'aqua',
'aliceblue',
'antiquewhite',
'aquamarine',
'azure',
'beige',
'bisque',
'blanchedalmond',
'blueviolet',
'brown',
'burlywood',
'cadetblue',
'chartreuse',
'chocolate',
'coral',
'cornflowerblue',
'cornsilk',
'crimson',
'cyan',
'darkblue',
'darkcyan',
'darkgoldenrod',
'darkgray',
'darkgreen',
'darkgrey',
'darkkhaki',
'darkmagenta',
'darkolivegreen',
'darkorange',
'darkorchid',
'darkred',
'darksalmon',
'darkseagreen',
'darkslateblue',
'darkslategray',
'darkslategrey',
'darkturquoise',
'darkviolet',
'deeppink',
'deepskyblue',
'dimgray',
'dimgrey',
'dodgerblue',
'firebrick',
'floralwhite',
'forestgreen',
'fuchsia',
'gainsboro',
'ghostwhite',
'gold',
'goldenrod',
'greenyellow',
'honeydew',
'hotpink',
'indianred',
'indigo',
'ivory',
'khaki',
'lavender',
'lavenderblush',
'lawngreen',
'lemonchiffon',
'lightblue',
'lightcoral',
'lightcyan',
'lightgoldenrodyellow',
'lightgray',
'lightgreen',
'lightgrey',
'lightpink',
'lightsalmon',
'lightseagreen',
'lightskyblue',
'lightslategray',
'lightslategrey',
'lightsteelblue',
'lightyellow',
'limegreen',
'linen',
'magenta',
'maroon',
'mediumaquamarine',
'mediumblue',
'mediumorchid',
'mediumpurple',
'mediumseagreen',
'mediumslateblue',
'mediumspringgreen',
'mediumturquoise',
'mediumvioletred',
'midnightblue',
'mintcream',
'mistyrose',
'moccasin',
'navajowhite',
'oldlace',
'olivedrab',
'orange',
'orangered',
'orchid',
'palegoldenrod',
'palegreen',
'paleturquoise',
'palevioletred',
'papayawhip',
'peachpuff',
'peru',
'pink',
'plum',
'powderblue',
'rosybrown',
'royalblue',
'saddlebrown',
'salmon',
'sandybrown',
'seagreen',
'seashell',
'sienna',
'skyblue',
'slateblue',
'slategray',
'slategrey',
'snow',
'springgreen',
'steelblue',
'tan',
'teal',
'thistle',
'tomato',
'turquoise',
'violet',
'wheat',
'whitesmoke',
'yellowgreen',
];
144 changes: 144 additions & 0 deletions superset-frontend/buildtools/eslint-plugin-theme-colors/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/

/**
* @fileoverview Rule to warn about literal colors
* @author Apache
*/

const _ = require('lodash');
const COLOR_KEYWORDS = require('./colors');

function getObjectExpressionPropertyNodes(
objectExpressionNode,
propertyNodes = [],
) {
_.each(objectExpressionNode.properties, propertyNode => {
propertyNodes.push(propertyNode);

if (propertyNode?.value?.type === 'ObjectExpression') {
propertyNodes.concat(
getObjectExpressionPropertyNodes(propertyNode.value, propertyNodes),
);
}
});

return propertyNodes;
}

function hasHexColor(quasi) {
if (typeof quasi === 'string') {
const regex = /#([a-f0-9]{3}|[a-f0-9]{4}(?:[a-f0-9]{2}){0,2})\b/gi;
return quasi.match(regex);
}

geido marked this conversation as resolved.
Show resolved Hide resolved
return false;
}

function hasRgbColor(quasi) {
if (typeof quasi === 'string') {
const regex = /rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)/i;
return quasi.match(regex);
}
return false;
}

function hasLiteralColor(quasi, strict = false) {
let match = false;
if (typeof quasi === 'string') {
// matches literal colors at the start or end of a CSS prop
COLOR_KEYWORDS.forEach(color => {
const regexColon = new RegExp(`: ${color}`);
const regexSemicolon = new RegExp(` ${color};`);
if (
quasi.match(regexColon) ||
quasi.match(regexSemicolon) ||
(strict && quasi === color)
) {
match = true;
}
});
}
return match;
}
geido marked this conversation as resolved.
Show resolved Hide resolved

const WARNING_MESSAGE =
'Theme color variables are preferred over rgb(a)/hex/literal colors';
const parsedNodes = [];

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

/** @type {import('eslint').Rule.RuleModule} */
module.exports = {
rules: {
'no-literal-colors': {
create(context) {
return {
TaggedTemplateExpression(node) {
if (
(node.tag.name === 'css' ||
node?.tag?.object?.name === 'styled') &&
node?.quasi?.quasis.length
) {
if (node.quasi.type === 'TemplateLiteral') {
const { quasis } = node.quasi;
quasis.forEach(quasi => {
if (quasi?.type === 'TemplateElement' && quasi?.value?.raw) {
const rawValue = quasi.value.raw;
if (
hasHexColor(rawValue) ||
hasRgbColor(rawValue) ||
hasLiteralColor(rawValue)
) {
context.report(node, node.loc, WARNING_MESSAGE);
}
}
});
}
}
},
ObjectExpression(node) {
const propertyNodes = getObjectExpressionPropertyNodes(node);
propertyNodes.forEach(prop => {
if (prop?.value?.type === 'Literal' && prop?.value?.value) {
const value = prop?.value?.value;
if (
!parsedNodes.find(
p => JSON.stringify(p.loc) === JSON.stringify(prop.loc),
)
) {
if (
hasHexColor(value) ||
hasRgbColor(value) ||
hasLiteralColor(value, true)
) {
context.report(node, prop.loc, WARNING_MESSAGE);
}
}
}
parsedNodes.push(prop);
});
},
};
},
},
},
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"name": "eslint-plugin-theme-colors",
"version": "1.0.0",
"description": "Warns about rgb(a)/hex/literal colors",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"license": "Apache-2.0",
"author": "Apache",
"dependencies": {
"lodash": "^4.17.21"
},
"engines": {
"node": "^16.9.1",
"npm": "^7.5.4"
}
}
Loading