Initial commit

This commit is contained in:
2025-03-07 19:22:02 +01:00
commit 4a98255d83
55743 changed files with 5280367 additions and 0 deletions
+63
View File
@@ -0,0 +1,63 @@
/**
* @fileoverview Detects color literals
* @author Aaron Greenwald
*/
'use strict';
const util = require('util');
const Components = require('../util/Components');
const styleSheet = require('../util/stylesheet');
const { StyleSheets } = styleSheet;
const { astHelpers } = styleSheet;
const create = Components.detect((context) => {
const styleSheets = new StyleSheets();
function reportColorLiterals(colorLiterals) {
if (colorLiterals) {
colorLiterals.forEach((style) => {
if (style) {
const expression = util.inspect(style.expression);
context.report({
node: style.node,
message: 'Color literal: {{expression}}',
data: { expression },
});
}
});
}
}
return {
CallExpression: (node) => {
if (astHelpers.isStyleSheetDeclaration(node, context.settings)) {
const styles = astHelpers.getStyleDeclarations(node);
if (styles) {
styles.forEach((style) => {
const literals = astHelpers.collectColorLiterals(style.value, context);
styleSheets.addColorLiterals(literals);
});
}
}
},
JSXAttribute: (node) => {
if (astHelpers.isStyleAttribute(node)) {
const literals = astHelpers.collectColorLiterals(node.value, context);
styleSheets.addColorLiterals(literals);
}
},
'Program:exit': () => reportColorLiterals(styleSheets.getColorLiterals()),
};
});
module.exports = {
meta: {
schema: [],
},
create,
};
+50
View File
@@ -0,0 +1,50 @@
/**
* @fileoverview Detects inline styles
* @author Aaron Greenwald
*/
'use strict';
const util = require('util');
const Components = require('../util/Components');
const styleSheet = require('../util/stylesheet');
const { StyleSheets } = styleSheet;
const { astHelpers } = styleSheet;
const create = Components.detect((context) => {
const styleSheets = new StyleSheets();
function reportInlineStyles(inlineStyles) {
if (inlineStyles) {
inlineStyles.forEach((style) => {
if (style) {
const expression = util.inspect(style.expression);
context.report({
node: style.node,
message: 'Inline style: {{expression}}',
data: { expression },
});
}
});
}
}
return {
JSXAttribute: (node) => {
if (astHelpers.isStyleAttribute(node)) {
const styles = astHelpers.collectStyleObjectExpressions(node.value, context);
styleSheets.addObjectExpressions(styles);
}
},
'Program:exit': () => reportInlineStyles(styleSheets.getObjectExpressions()),
};
});
module.exports = {
meta: {
schema: [],
},
create,
};
+125
View File
@@ -0,0 +1,125 @@
/**
* @fileoverview Detects raw text outside of Text component
* @author Alex Zhukov
*/
'use strict';
const elementName = (node) => {
const reversedIdentifiers = [];
if (
node.type === 'JSXElement'
&& node.openingElement.type === 'JSXOpeningElement'
) {
let object = node.openingElement.name;
while (object.type === 'JSXMemberExpression') {
if (object.property.type === 'JSXIdentifier') {
reversedIdentifiers.push(object.property.name);
}
object = object.object;
}
if (object.type === 'JSXIdentifier') {
reversedIdentifiers.push(object.name);
}
}
return reversedIdentifiers.reverse().join('.');
};
const hasAllowedParent = (parent, allowedElements) => {
let curNode = parent;
while (curNode) {
if (curNode.type === 'JSXElement') {
const name = elementName(curNode);
if (allowedElements.includes(name)) {
return true;
}
}
curNode = curNode.parent;
}
return false;
};
function create(context) {
const options = context.options[0] || {};
const report = (node) => {
const errorValue = node.type === 'TemplateLiteral'
? `TemplateLiteral: ${node.expressions[0].name}`
: node.value.trim();
const formattedErrorValue = errorValue.length > 0
? `Raw text (${errorValue})`
: 'Whitespace(s)';
context.report({
node,
message: `${formattedErrorValue} cannot be used outside of a <Text> tag`,
});
};
const skippedElements = options.skip ? options.skip : [];
const allowedElements = ['Text', 'TSpan', 'StyledText', 'Animated.Text'].concat(skippedElements);
const hasOnlyLineBreak = (value) => /^[\r\n\t\f\v]+$/.test(value.replace(/ /g, ''));
const getValidation = (node) => !hasAllowedParent(node.parent, allowedElements);
return {
Literal(node) {
const parentType = node.parent.type;
const onlyFor = ['JSXExpressionContainer', 'JSXElement'];
if (typeof node.value !== 'string'
|| hasOnlyLineBreak(node.value)
|| !onlyFor.includes(parentType)
|| (node.parent.parent && node.parent.parent.type === 'JSXAttribute')
) return;
const isStringLiteral = parentType === 'JSXExpressionContainer';
if (getValidation(isStringLiteral ? node.parent : node)) {
report(node);
}
},
JSXText(node) {
if (typeof node.value !== 'string' || hasOnlyLineBreak(node.value)) return;
if (getValidation(node)) {
report(node);
}
},
TemplateLiteral(node) {
if (
node.parent.type !== 'JSXExpressionContainer'
|| (node.parent.parent && node.parent.parent.type === 'JSXAttribute')
) return;
if (getValidation(node.parent)) {
report(node);
}
},
};
}
module.exports = {
meta: {
schema: [
{
type: 'object',
properties: {
skip: {
type: 'array',
items: {
type: 'string',
},
},
},
additionalProperties: false,
},
],
},
create,
};
@@ -0,0 +1,48 @@
/**
* @fileoverview Enforce no single element style arrays
* @author Michael Gall
*/
'use strict';
module.exports = {
meta: {
docs: {
description:
'Disallow single element style arrays. These cause unnecessary re-renders as the identity of the array always changes',
category: 'Stylistic Issues',
recommended: false,
url: '',
},
fixable: 'code',
},
create(context) {
function reportNode(JSXExpressionNode) {
context.report({
node: JSXExpressionNode,
message:
'Single element style arrays are not necessary and cause unnecessary re-renders',
fix(fixer) {
const realStyleNode = JSXExpressionNode.value.expression.elements[0];
const styleSource = context.getSourceCode().getText(realStyleNode);
return fixer.replaceText(JSXExpressionNode.value.expression, styleSource);
},
});
}
// --------------------------------------------------------------------------
// Public
// --------------------------------------------------------------------------
return {
JSXAttribute(node) {
if (node.name.name !== 'style') return;
if (!node.value.expression) return;
if (node.value.expression.type !== 'ArrayExpression') return;
if (node.value.expression.elements.length === 1) {
reportNode(node);
}
},
};
},
};
+70
View File
@@ -0,0 +1,70 @@
/**
* @fileoverview Detects unused styles
* @author Tom Hastjarjanto
*/
'use strict';
const Components = require('../util/Components');
const styleSheet = require('../util/stylesheet');
const { StyleSheets } = styleSheet;
const { astHelpers } = styleSheet;
const create = Components.detect((context, components) => {
const styleSheets = new StyleSheets();
const styleReferences = new Set();
function reportUnusedStyles(unusedStyles) {
Object.keys(unusedStyles).forEach((key) => {
if ({}.hasOwnProperty.call(unusedStyles, key)) {
const styles = unusedStyles[key];
styles.forEach((node) => {
const message = [
'Unused style detected: ',
key,
'.',
node.key.name,
].join('');
context.report(node, message);
});
}
});
}
return {
MemberExpression: function (node) {
const styleRef = astHelpers.getPotentialStyleReferenceFromMemberExpression(node);
if (styleRef) {
styleReferences.add(styleRef);
}
},
CallExpression: function (node) {
if (astHelpers.isStyleSheetDeclaration(node, context.settings)) {
const styleSheetName = astHelpers.getStyleSheetName(node);
const styles = astHelpers.getStyleDeclarations(node);
styleSheets.add(styleSheetName, styles);
}
},
'Program:exit': function () {
const list = components.all();
if (Object.keys(list).length > 0) {
styleReferences.forEach((reference) => {
styleSheets.markAsUsed(reference);
});
reportUnusedStyles(styleSheets.getUnusedReferences());
}
},
};
});
module.exports = {
meta: {
schema: [],
},
create,
};
+157
View File
@@ -0,0 +1,157 @@
/**
* @fileoverview Rule to require StyleSheet object keys to be sorted
* @author Mats Byrkjeland
*/
'use strict';
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const { astHelpers } = require('../util/stylesheet');
const {
getStyleDeclarationsChunks,
getPropertiesChunks,
getStylePropertyIdentifier,
isStyleSheetDeclaration,
isEitherShortHand,
} = astHelpers;
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
function create(context) {
const order = context.options[0] || 'asc';
const options = context.options[1] || {};
const { ignoreClassNames } = options;
const { ignoreStyleProperties } = options;
const isValidOrder = order === 'asc' ? (a, b) => a <= b : (a, b) => a >= b;
const sourceCode = context.getSourceCode();
function sort(array) {
return [].concat(array).sort((a, b) => {
const identifierA = getStylePropertyIdentifier(a);
const identifierB = getStylePropertyIdentifier(b);
let sortOrder = 0;
if (isEitherShortHand(identifierA, identifierB)) {
return a.range[0] - b.range[0];
} if (identifierA < identifierB) {
sortOrder = -1;
} else if (identifierA > identifierB) {
sortOrder = 1;
}
return sortOrder * (order === 'asc' ? 1 : -1);
});
}
function report(array, type, node, prev, current) {
const currentName = getStylePropertyIdentifier(current);
const prevName = getStylePropertyIdentifier(prev);
const hasComments = array
.map((prop) => [...sourceCode.getCommentsBefore(prop), ...sourceCode.getCommentsAfter(prop)])
.reduce(
(hasComment, comment) => hasComment || comment.length > 0,
false
);
context.report({
node,
message: `Expected ${type} to be in ${order}ending order. '${currentName}' should be before '${prevName}'.`,
loc: current.key.loc,
fix: hasComments ? undefined : (fixer) => {
const sortedArray = sort(array);
return array
.map((item, i) => {
if (item !== sortedArray[i]) {
return fixer.replaceText(
item,
sourceCode.getText(sortedArray[i])
);
}
return null;
})
.filter(Boolean);
},
});
}
function checkIsSorted(array, arrayName, node) {
for (let i = 1; i < array.length; i += 1) {
const previous = array[i - 1];
const current = array[i];
if (previous.type !== 'Property' || current.type !== 'Property') {
return;
}
const prevName = getStylePropertyIdentifier(previous);
const currentName = getStylePropertyIdentifier(current);
const oneIsShorthandForTheOther = arrayName === 'style properties' && isEitherShortHand(prevName, currentName);
if (!oneIsShorthandForTheOther && !isValidOrder(prevName, currentName)) {
return report(array, arrayName, node, previous, current);
}
}
}
return {
CallExpression: function (node) {
if (!isStyleSheetDeclaration(node, context.settings)) {
return;
}
const classDefinitionsChunks = getStyleDeclarationsChunks(node);
if (!ignoreClassNames) {
classDefinitionsChunks.forEach((classDefinitions) => {
checkIsSorted(classDefinitions, 'class names', node);
});
}
if (ignoreStyleProperties) return;
classDefinitionsChunks.forEach((classDefinitions) => {
classDefinitions.forEach((classDefinition) => {
const styleProperties = classDefinition.value.properties;
if (!styleProperties || styleProperties.length < 2) {
return;
}
const stylePropertyChunks = getPropertiesChunks(styleProperties);
stylePropertyChunks.forEach((stylePropertyChunk) => {
checkIsSorted(stylePropertyChunk, 'style properties', node);
});
});
});
},
};
}
module.exports = {
meta: {
fixable: 'code',
schema: [
{
enum: ['asc', 'desc'],
},
{
type: 'object',
properties: {
ignoreClassNames: {
type: 'boolean',
},
ignoreStyleProperties: {
type: 'boolean',
},
},
additionalProperties: false,
},
],
},
create,
};
@@ -0,0 +1,97 @@
/**
* @fileoverview Android and IOS components should be
* used in platform specific React Native components.
* @author Tom Hastjarjanto
*/
'use strict';
function create(context) {
let reactComponents = [];
const androidMessage = 'Android components should be placed in android files';
const iosMessage = 'IOS components should be placed in ios files';
const conflictMessage = 'IOS and Android components can\'t be mixed';
const iosPathRegex = context.options[0] && context.options[0].iosPathRegex
? new RegExp(context.options[0].iosPathRegex)
: /\.ios\.[j|t]sx?$/;
const androidPathRegex = context.options[0] && context.options[0].androidPathRegex
? new RegExp(context.options[0].androidPathRegex)
: /\.android\.[j|t]sx?$/;
function getName(node) {
if (node.type === 'Property') {
const key = node.key || node.argument;
return key.type === 'Identifier' ? key.name : key.value;
} if (node.type === 'Identifier') {
return node.name;
}
}
function hasNodeWithName(nodes, name) {
return nodes.some((node) => {
const nodeName = getName(node);
return nodeName && nodeName.includes(name);
});
}
function reportErrors(components, filename) {
const containsAndroidAndIOS = (
hasNodeWithName(components, 'IOS')
&& hasNodeWithName(components, 'Android')
);
components.forEach((node) => {
const propName = getName(node);
if (propName.includes('IOS') && !filename.match(iosPathRegex)) {
context.report(node, containsAndroidAndIOS ? conflictMessage : iosMessage);
}
if (propName.includes('Android') && !filename.match(androidPathRegex)) {
context.report(node, containsAndroidAndIOS ? conflictMessage : androidMessage);
}
});
}
return {
VariableDeclarator: function (node) {
const destructuring = node.init && node.id && node.id.type === 'ObjectPattern';
const statelessDestructuring = destructuring && node.init.name === 'React';
if (destructuring && statelessDestructuring) {
reactComponents = reactComponents.concat(node.id.properties);
}
},
ImportDeclaration: function (node) {
if (node.source.value === 'react-native') {
node.specifiers.forEach((importSpecifier) => {
if (importSpecifier.type === 'ImportSpecifier') {
reactComponents = reactComponents.concat(importSpecifier.imported);
}
});
}
},
'Program:exit': function () {
const filename = context.getFilename();
reportErrors(reactComponents, filename);
},
};
}
module.exports = {
meta: {
fixable: 'code',
schema: [{
type: 'object',
properties: {
androidPathRegex: {
type: 'string',
},
iosPathRegex: {
type: 'string',
},
},
additionalProperties: false,
}],
},
create,
};