Add a custom rule to prevent colors from being hardcoded outside of theme (#288)

* Add a custom rule to prevent colors from being hardcoded in ESLint

* Refactor colors

* Create packages folder and fix colors

* Remove external dependency for css alphabetical order linting

* Fix install with yarn

---------

Co-authored-by: Charles Bochet <charles@twenty.com>
This commit is contained in:
Félix Malfait
2023-06-14 16:56:29 +02:00
committed by GitHub
parent bf6fb0ba70
commit 31f3950439
61 changed files with 31490 additions and 62652 deletions

View File

@ -0,0 +1,10 @@
// eslint-disable-next-line @typescript-eslint/no-var-requires
const noHardcodedColors = require('./rules/no-hardcoded-colors');
const cssAlphabetically = require('./rules/sort-css-properties-alphabetically');
module.exports = {
rules: {
'no-hardcoded-colors': noHardcodedColors,
'sort-css-properties-alphabetically': cssAlphabetically,
},
};

View File

@ -0,0 +1,8 @@
{
"name": "eslint-plugin-twenty",
"version": "0.0.1",
"main": "index.js",
"dependencies": {
"postcss": "^8.4.24"
}
}

View File

@ -0,0 +1,24 @@
module.exports = {
create: function (context) {
return {
TaggedTemplateExpression(node) {
if (context.getFilename().endsWith('themes.ts')) {
return;
}
node.quasi.quasis.forEach((quasi) => {
const colorRegex =
/(?:rgba?\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})(,\s*\d+\.?\d*)?\))|(?:#[0-9a-fA-F]{6})/i;
if (colorRegex.test(quasi.value.raw)) {
context.report({
node,
message:
'Do not use hardcoded RGBA or Hex colors. Please use a color from the theme file.',
});
}
});
},
};
},
};

View File

@ -0,0 +1,208 @@
"use strict";
const postcss = require("postcss");
function isStyledTagname(node) {
return (
(node.tag.type === "Identifier" && node.tag.name === "css") ||
(node.tag.type === "MemberExpression" &&
node.tag.object.name === "styled") ||
(node.tag.type === "CallExpression" &&
(node.tag.callee.name === "styled" ||
(node.tag.callee.object &&
((node.tag.callee.object.callee &&
node.tag.callee.object.callee.name === "styled") ||
(node.tag.callee.object.object &&
node.tag.callee.object.object.name === "styled")))))
);
}
/**
* An atomic rule is a rule without nested rules.
*/
function isValidAtomicRule(rule) {
const decls = rule.nodes.filter(node => node.type === "decl");
if (decls.length < 0) {
return { isValid: true };
}
for (let i = 1; i < decls.length; i++) {
const current = decls[i].prop;
const prev = decls[i - 1].prop;
if (current < prev) {
const loc = {
start: {
line: decls[i - 1].source.start.line,
column: decls[i - 1].source.start.column - 1
},
end: {
line: decls[i].source.end.line,
column: decls[i].source.end.column - 1
}
};
return { isValid: false, loc };
}
}
return { isValid: true };
}
function isValidRule(rule) {
// check each rule recursively
const { isValid, loc } = rule.nodes.reduce(
(map, node) => {
return node.type === "rule" ? isValidRule(node) : map;
},
{ isValid: true }
);
// if there is any invalid rule, return result
if (!isValid) {
return { isValid, loc };
}
// check declarations
return isValidAtomicRule(rule);
}
function getNodeStyles(node) {
const [firstQuasi, ...quasis] = node.quasi.quasis;
// remove line break added to the first quasi
const lineBreakCount = node.quasi.loc.start.line - 1;
let styles = `${"\n".repeat(lineBreakCount)}${" ".repeat(
node.quasi.loc.start.column + 1
)}${firstQuasi.value.raw}`;
// replace expression by spaces and line breaks
quasis.forEach(({ value, loc }, idx) => {
const prevLoc = idx === 0 ? firstQuasi.loc : quasis[idx - 1].loc;
const lineBreaksCount = loc.start.line - prevLoc.end.line;
const spacesCount =
loc.start.line === prevLoc.end.line
? loc.start.column - prevLoc.end.column + 2
: loc.start.column + 1;
styles = `${styles}${" "}${"\n".repeat(lineBreaksCount)}${" ".repeat(
spacesCount
)}${value.raw}`;
});
return styles;
}
function create(context) {
return {
TaggedTemplateExpression(node) {
if (isStyledTagname(node)) {
try {
const root = postcss.parse(getNodeStyles(node));
const { isValid, loc } = isValidRule(root);
if (!isValid) {
return context.report({
node,
messageId: "sort-css-properties-alphabetically",
loc,
fix: fixer =>
fix({
rule: root,
fixer,
src: context.getSourceCode()
})
});
}
} catch (e) {
return true;
}
}
}
};
}
function fix({ rule, fixer, src }) {
let fixings = [];
// concat fixings recursively
rule.nodes.forEach(node => {
if (node.type === "rule") {
fixings = [...fixings, ...fix({ rule: node, fixer, src })];
}
});
const declarations = rule.nodes.filter(node => node.type === "decl");
const sortedDeclarations = sortDeclarations(declarations);
declarations.forEach((decl, idx) => {
if (!areSameDeclarations(decl, sortedDeclarations[idx])) {
try {
const range = getDeclRange({ decl, src });
const sortedDeclText = getDeclText({
decl: sortedDeclarations[idx],
src
});
fixings.push(fixer.removeRange([range.startIdx, range.endIdx + 1]));
fixings.push(
fixer.insertTextAfterRange(
[range.startIdx, range.startIdx],
sortedDeclText
)
);
} catch (e) {
console.log(e);
}
}
});
return fixings;
}
function areSameDeclarations(a, b) {
return (
a.source.start.line === b.source.start.line &&
a.source.start.column === b.source.start.column
);
}
function getDeclRange({ decl, src }) {
const loc = {
start: {
line: decl.source.start.line,
column: decl.source.start.column - 1
},
end: {
line: decl.source.end.line,
column: decl.source.end.column - 1
}
};
const startIdx = src.getIndexFromLoc(loc.start);
const endIdx = src.getIndexFromLoc(loc.end);
return { startIdx, endIdx };
}
function getDeclText({ decl, src }) {
const { startIdx, endIdx } = getDeclRange({ decl, src });
return src.getText().substring(startIdx, endIdx + 1);
}
function sortDeclarations(declarations) {
return declarations
.slice()
.sort((declA, declB) => (declA.prop > declB.prop ? 1 : -1));
}
module.exports = {
meta: {
docs: {
description: "Styles are sorted alphabetically.",
category: "Fill me in",
recommended: false
},
messages: {
"sort-css-properties-alphabetically":
"Declarations should be sorted alphabetically."
},
fixable: "code"
},
create
};

View File

@ -0,0 +1,27 @@
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1
nanoid@^3.3.6:
version "3.3.6"
resolved "https://registry.yarnpkg.com/nanoid/-/nanoid-3.3.6.tgz#443380c856d6e9f9824267d960b4236ad583ea4c"
integrity sha512-BGcqMMJuToF7i1rt+2PWSNVnWIkGCU78jBG3RxO/bZlnZPK2Cmi2QaffxGO/2RvWi9sL+FAiRiXMgsyxQ1DIDA==
picocolors@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/picocolors/-/picocolors-1.0.0.tgz#cb5bdc74ff3f51892236eaf79d68bc44564ab81c"
integrity sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==
postcss@^8.4.24:
version "8.4.24"
resolved "https://registry.yarnpkg.com/postcss/-/postcss-8.4.24.tgz#f714dba9b2284be3cc07dbd2fc57ee4dc972d2df"
integrity sha512-M0RzbcI0sO/XJNucsGjvWU9ERWxb/ytp1w6dKtxTKgixdtQDq4rmx/g8W1hnaheq9jgwL/oyEdH5Bc4WwJKMqg==
dependencies:
nanoid "^3.3.6"
picocolors "^1.0.0"
source-map-js "^1.0.2"
source-map-js@^1.0.2:
version "1.0.2"
resolved "https://registry.yarnpkg.com/source-map-js/-/source-map-js-1.0.2.tgz#adbc361d9c62df380125e7f161f71c826f1e490c"
integrity sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw==