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

Add insideFunctions: {"function": int} to number-max-precision #6932

Merged
5 changes: 5 additions & 0 deletions .changeset/hungry-cherries-promise.md
@@ -0,0 +1,5 @@
---
"stylelint": minor
---

Added: `insideFunctions: {"function": number}` to `number-max-precision`
41 changes: 41 additions & 0 deletions lib/rules/number-max-precision/README.md
Expand Up @@ -133,3 +133,44 @@ a {
width: 10.989my-other-unit;
}
```

### `insideFunctions: {"/regex/": 1, /regex/: 1, "string": 1}`
romainmenke marked this conversation as resolved.
Show resolved Hide resolved

The `insideFunctions` option can change a primary option value for specified functions.

For example, with `2`.

Given:

```json
{"/^(oklch|oklab|lch|lab)$/", 4}
```

The following patterns are considered problems:

<!-- prettier-ignore -->
```css
a { color: rgb(127.333 0 0) }
romainmenke marked this conversation as resolved.
Show resolved Hide resolved
```

<!-- prettier-ignore -->
```css
a { color: rgb(calc(127.333 / 3) 0 0) }
```

The following patterns are _not_ considered problems:

<!-- prettier-ignore -->
```css
a { color: oklch(0.333 0 0) }
```

<!-- prettier-ignore -->
```css
a { color: lab(0.3333 0 0) }
```

<!-- prettier-ignore -->
```css
a { color: oklab(calc(127.333 / 3) 0 0) }
```
52 changes: 51 additions & 1 deletion lib/rules/number-max-precision/__tests__/index.js
Expand Up @@ -41,7 +41,7 @@ testRule({
code: "@IMPORT '1.123.css'",
},
{
code: 'a { background: url(1.123.jpg) }',
code: 'a { background: url(1.123.jpg) url("foo" 1.123.jpg) }',
},
Mouvedia marked this conversation as resolved.
Show resolved Hide resolved
{
code: 'a { my-string: "1.2345"; }',
Mouvedia marked this conversation as resolved.
Show resolved Hide resolved
Expand Down Expand Up @@ -373,3 +373,53 @@ testRule({
},
],
});

testRule({
ruleName,
config: [
2,
{
insideFunctions: {
oklch: 4,
zero: 0,
one: 1,
two: 2,
romainmenke marked this conversation as resolved.
Show resolved Hide resolved
[/^three/i]: 3,
},
},
],

accept: [
{
code: 'a { color: oklch(0.1234 0.1234 0.1234) }',
},
{
code: 'a { color: oklch(calc(0.1234 + 1.0001) 0.1234 0.1234) }',
},
{
code: 'a { color: zero(0, one(1.1, tWo(2.22%, ThReE(3.333px), three-percentage(3.333%)))) }',
},
{
code: 'a { color: three(zero(0) 3.333) }',
},
],

reject: [
{
code: 'a { color: oklch(0.12345 0.1234 0.1234) }',
message: messages.expected(0.12345, 0.1235),
line: 1,
column: 18,
endLine: 1,
endColumn: 25,
},
{
code: 'a { color: zero(0, one(1.1, two(2.22, ThReE(3.333, zero(calc(0.1)))))) }',
message: messages.expected(0.1, 0),
line: 1,
column: 62,
endLine: 1,
endColumn: 65,
},
],
});
152 changes: 120 additions & 32 deletions lib/rules/number-max-precision/index.js
@@ -1,16 +1,24 @@
'use strict';

const valueParser = require('postcss-value-parser');
const { tokenize, TokenType } = require('@csstools/css-tokenizer');
const {
isFunctionNode,
isSimpleBlockNode,
isTokenNode,
parseListOfComponentValues,
} = require('@csstools/css-parser-algorithms');

const atRuleParamIndex = require('../../utils/atRuleParamIndex');
const declarationValueIndex = require('../../utils/declarationValueIndex');
const getDimension = require('../../utils/getDimension');
const getAtRuleParams = require('../../utils/getAtRuleParams');
const getDeclarationValue = require('../../utils/getDeclarationValue');
const matchesStringOrRegExp = require('../../utils/matchesStringOrRegExp');
const optionsMatches = require('../../utils/optionsMatches');
const report = require('../../utils/report');
const ruleMessages = require('../../utils/ruleMessages');
const { isAtRule } = require('../../utils/typeGuards');
const validateOptions = require('../../utils/validateOptions');
const { isNumber, isRegExp, isString } = require('../../utils/validateTypes');
const validateObjectWithProps = require('../../utils/validateObjectWithProps');

const ruleName = 'number-max-precision';

Expand Down Expand Up @@ -38,6 +46,7 @@ const rule = (primary, secondaryOptions) => {
possible: {
ignoreProperties: [isString, isRegExp],
ignoreUnits: [isString, isRegExp],
insideFunctions: [validateObjectWithProps(isNumber)],
},
},
);
Expand All @@ -51,16 +60,20 @@ const rule = (primary, secondaryOptions) => {
return;
}

check(atRule, atRule.params);
check(atRule, atRuleParamIndex, getAtRuleParams(atRule));
});

root.walkDecls((decl) => check(decl, decl.value));
root.walkDecls((decl) => {
check(decl, declarationValueIndex, getDeclarationValue(decl));
});

/**
* @param {import('postcss').AtRule | import('postcss').Declaration} node
* @template {import('postcss').AtRule | import('postcss').Declaration} T
* @param {T} node
* @param {(node: T) => number} getIndex
* @param {string} value
*/
function check(node, value) {
function check(node, getIndex, value) {
// Get out quickly if there are no periods
if (!value.includes('.')) {
return;
Expand All @@ -72,47 +85,122 @@ const rule = (primary, secondaryOptions) => {
return;
}

valueParser(value).walk((valueNode) => {
const { unit } = getDimension(valueNode);
parseListOfComponentValues(tokenize({ css: value })).forEach((componentValue) => {
/** @type {{ ignored: boolean, precision: number }} */
romainmenke marked this conversation as resolved.
Show resolved Hide resolved
const state = {
ignored: false,
precision: primary,
};

if (optionsMatches(secondaryOptions, 'ignoreUnits', unit)) {
return;
}
walker(node, getIndex, componentValue, state);

if (isFunctionNode(componentValue) || isSimpleBlockNode(componentValue)) {
componentValue.walk((entry) => {
if (!entry.state) return;

if (entry.state.ignored) return;

// Ignore `url` function
if (valueNode.type === 'function' && valueNode.value.toLowerCase() === 'url') {
return false;
walker(node, getIndex, entry.node, entry.state);
}, state);
}
});
}

/**
* @template {import('postcss').AtRule | import('postcss').Declaration} T
* @param {T} node
* @param {(node: T) => number} getIndex
* @param {import('@csstools/css-parser-algorithms').ComponentValue} componentValue
* @param {{ ignored: boolean, precision: number }} state
*/
function walker(node, getIndex, componentValue, state) {
if (isFunctionNode(componentValue)) {
const name = componentValue.getName().toLowerCase();

if (name === 'url') {
state.ignored = true;

// Ignore strings, comments, etc
if (valueNode.type !== 'word') {
return;
}

const match = /\d*\.(\d+)/.exec(valueNode.value);
state.precision = precisionInsideFunction(name, state.precision);

return;
}

if (!isTokenNode(componentValue)) {
return;
}

const [tokenType, raw, startIndex, endIndex, parsedValue] = componentValue.value;

if (
tokenType !== TokenType.Number &&
tokenType !== TokenType.Dimension &&
tokenType !== TokenType.Percentage
) {
return;
}

let unitStringLength = 0;

if (tokenType === TokenType.Dimension) {
const unit = parsedValue.unit;

unitStringLength = unit.length;

if (match == null || match[0] == null || match[1] == null) {
if (optionsMatches(secondaryOptions, 'ignoreUnits', unit)) {
return;
}
} else if (tokenType === TokenType.Percentage) {
unitStringLength = 1;

if (match[1].length <= primary) {
if (optionsMatches(secondaryOptions, 'ignoreUnits', '%')) {
return;
}
}

const match = /\d*\.(\d+)/.exec(raw);

if (match == null || match[0] == null || match[1] == null) {
return;
}

if (match[1].length <= state.precision) {
return;
}

const nodeIndex = getIndex(node);

const baseIndex = isAtRule(node) ? atRuleParamIndex(node) : declarationValueIndex(node);
const actual = Number.parseFloat(match[0]);

report({
result,
ruleName,
node,
index: baseIndex + valueNode.sourceIndex + match.index,
word: actual.toString(),
message: messages.expected,
messageArgs: [actual, actual.toFixed(primary)],
});
report({
result,
ruleName,
node,
index: nodeIndex + startIndex,
endIndex: nodeIndex + (endIndex + 1) - unitStringLength,
message: messages.expected,
messageArgs: [parsedValue.value, parsedValue.value.toFixed(state.precision)],
});
}

/**
* @param {string} functionName
* @param {number} currentPrecision
* @returns {number}
*/
function precisionInsideFunction(functionName, currentPrecision) {
if (functionName in secondaryOptions.insideFunctions) {
return secondaryOptions.insideFunctions[functionName];
}

for (const [name, precision] of Object.entries(secondaryOptions.insideFunctions)) {
romainmenke marked this conversation as resolved.
Show resolved Hide resolved
if (matchesStringOrRegExp(functionName, name)) {
return precision;
}
}

return currentPrecision;
}
};
};

Expand Down