Skip to content

Add sort-styles rule #211

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

Merged
merged 2 commits into from
Jan 2, 2019
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
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ ESLint plugin for React Native

[![Greenkeeper badge](https://badges.greenkeeper.io/Intellicode/eslint-plugin-react-native.svg)](https://greenkeeper.io/)

[![Maintenance Status][status-image]][status-url] [![NPM version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Dependency Status][deps-image]][deps-url] [![Coverage Status][coverage-image]][coverage-url] [![Code Climate][climate-image]][climate-url] [![BCH compliance][bettercode-image]][bettercode-url]
[![Maintenance Status][status-image]][status-url] [![NPM version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Dependency Status][deps-image]][deps-url] [![Coverage Status][coverage-image]][coverage-url] [![Code Climate][climate-image]][climate-url] [![BCH compliance][bettercode-image]][bettercode-url]

React Native specific linting rules for ESLint. This repository is structured like (and contains code from) the excellent [eslint-plugin-react](http://github.com/yannickcr/eslint-plugin-react).

Expand Down Expand Up @@ -79,6 +79,7 @@ Finally, enable all of the rules that you would like to use.
# List of supported rules

* [no-unused-styles](docs/rules/no-unused-styles.md): Detect `StyleSheet` rules which are not used in your React components
* [sort-styles](docs/rules/sort-styles.md): Require style definitions to be sorted alphabetically
* [split-platform-components](docs/rules/split-platform-components.md): Enforce using platform specific filenames when necessary
* [no-inline-styles](docs/rules/no-inline-styles.md): Detect JSX components with inline styles that contain literal values
* [no-color-literals](docs/rules/no-color-literals.md): Detect `StyleSheet` rules and inline styles containing color literals instead of variables
Expand Down
132 changes: 132 additions & 0 deletions docs/rules/sort-styles.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
# Require StyleSheet keys to be sorted
It's like [sort-keys](https://eslint.org/docs/rules/sort-keys), but just for React Native styles.

Keeping your style definitions sorted is a common convention that helps with readability. This rule lets you enforce an ascending (default) or descending alphabetical order for both "class names" and style properties.

## Rule Details

The following patterns are considered warnings:

```js
const styles = StyleSheet.create({
button: {
width: 100,
color: 'green',
},
});
```

```js
const styles = StyleSheet.create({
button: {},
anchor: {},
});
```

The following patterns are not considered warnings:

```js
const styles = StyleSheet.create({
button: {
color: 'green',
width: 100,
},
});
```

```js
const styles = StyleSheet.create({
anchor: {},
button: {},
});
```

## Options

```
{
"react-native/sort-styles": ["error", "asc", { "ignoreClassNames": false, "ignoreStyleProperties": false }]
}
```

The 1st option is "asc" or "desc".

* `"asc"` (default) - enforce properties to be in ascending order.
* `"desc"` - enforce properties to be in descending order.

The 2nd option is an object which has 2 properties.

* `ignoreClassNames` - if `true`, order will not be enforced on the class name level. Default is `false`.
* `ignoreStyleProperties` - if `true`, order will not be enforced on the style property level. Default is `false`.

### desc

`/* eslint react-native/sort-styles: ["error", "desc"] */`

The following patterns are considered warnings:

```js
const styles = StyleSheet.create({
button: {
color: 'green',
width: 100,
},
});
```

```js
const styles = StyleSheet.create({
anchor: {},
button: {},
});
```

The following patterns are not considered warnings:

```js
const styles = StyleSheet.create({
button: {
width: 100,
color: 'green',
},
});
```

```js
const styles = StyleSheet.create({
button: {},
anchor: {},
});
```

### ignoreClassNames

`/* eslint react-native/sort-styles: ["error", "asc", { "ignoreClassNames": true }] */`

The following patterns are not considered warnings:

```js
const styles = StyleSheet.create({
button: {
color: 'green',
width: 100,
},
anchor: {},
});
```

# ignoreStyleProperties

`/* eslint react-native/sort-styles: ["error", "asc", { "ignoreStyleProperties": true }] */`

The following patterns are not considered warnings:

```js
const styles = StyleSheet.create({
anchor: {},
button: {
width: 100,
color: 'green',
},
});
```
2 changes: 2 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const allRules = {
'no-unused-styles': require('./lib/rules/no-unused-styles'),
'no-inline-styles': require('./lib/rules/no-inline-styles'),
'no-color-literals': require('./lib/rules/no-color-literals'),
'sort-styles': require('./lib/rules/sort-styles'),
'split-platform-components': require('./lib/rules/split-platform-components'),
'no-raw-text': require('./lib/rules/no-raw-text'),
};
Expand All @@ -30,6 +31,7 @@ module.exports = {
'no-unused-styles': 0,
'no-inline-styles': 0,
'no-color-literals': 0,
'sort-styles': 0,
'split-platform-components': 0,
'no-raw-text': 0,
},
Expand Down
94 changes: 94 additions & 0 deletions lib/rules/sort-styles.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/**
* @fileoverview Rule to require StyleSheet object keys to be sorted
* @author Mats Byrkjeland
*/

'use strict';

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const { astHelpers } = require('../util/stylesheet');

const { getStyleDeclarations, isStyleSheetDeclaration } = astHelpers;

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

module.exports = (context) => {
const order = context.options[0] || 'asc';
const options = context.options[1] || {};
const ignoreClassNames = options.ignoreClassNames;
const ignoreStyleProperties = options.ignoreStyleProperties;
const isValidOrder = order === 'asc' ? (a, b) => a <= b : (a, b) => a >= b;

function report(type, node, prev, current) {
const currentName = current.key.name;
const prevName = prev.key.name;
context.report({
node,
message: `Expected ${type} to be in ${order}ending order. '${currentName}' should be before '${prevName}'.`,
loc: current.key.loc,
});
}

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;
}

if (!isValidOrder(previous.key.name, current.key.name)) {
return report(arrayName, node, previous, current);
}
}
}

return {
VariableDeclarator: function (node) {
if (!isStyleSheetDeclaration(node, context.settings)) {
return;
}

const classDefinitions = getStyleDeclarations(node);

if (!ignoreClassNames) {
checkIsSorted(classDefinitions, 'class names', node);
}

if (ignoreStyleProperties) return;

classDefinitions.forEach((classDefinition) => {
const styleProperties = classDefinition.value.properties;
if (!styleProperties || styleProperties.length < 2) {
return;
}

checkIsSorted(styleProperties, 'style properties', node);
});
},
};
};

module.exports.schema = [
{
enum: ['asc', 'desc'],
},
{
type: 'object',
properties: {
ignoreClassNames: {
type: 'boolean',
},
ignoreStyleProperties: {
type: 'boolean',
},
},
additionalProperties: false,
},
];
Loading