Skip to content

feat: Validate property values containing variables #148

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 10 commits into from
Jun 10, 2025
Merged
Show file tree
Hide file tree
Changes from 2 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
14 changes: 13 additions & 1 deletion docs/rules/no-invalid-properties.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,19 @@ body {

### Limitations

This rule uses the lexer from [CSSTree](https://github.com/csstree/csstree), which does not support validation of property values that contain variable references (i.e., `var(--bg-color)`). The lexer throws an error when it comes across a variable reference, and rather than displaying that error, this rule ignores it. This unfortunately means that this rule cannot properly validate properties values that contain variable references. We'll continue to work towards a solution for this.
When a variable is used in a property value, such as `var(--my-color)`, this rule can only properly validate the value if the parser has already encountered the `--my-color` custom property. For example, this will validate correctly:

```css
:root {
--my-color: red;
}

a {
color: var(--my-color);
}
```

This code defines `--my-color` before it is used and therefore the rule can validate the `color` property. If `--my-color` was not defined before `var(--my-color)` was used, it results in a lint error because the validation cannot be completed. If the custom property is defined in another file, it's recommended to create a dummy rule just for the purpose of ensuring proper validation.

## When Not to Use It

Expand Down
127 changes: 109 additions & 18 deletions src/rules/no-invalid-properties.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,39 @@ import { isSyntaxMatchError } from "../util.js";

/**
* @import { CSSRuleDefinition } from "../types.js"
* @typedef {"invalidPropertyValue" | "unknownProperty"} NoInvalidPropertiesMessageIds
* @import { ValuePlain, FunctionNodePlain, CssLocationRange } from "@eslint/css-tree";
* @typedef {"invalidPropertyValue" | "unknownProperty" | "unknownVar"} NoInvalidPropertiesMessageIds
* @typedef {CSSRuleDefinition<{ RuleOptions: [], MessageIds: NoInvalidPropertiesMessageIds }>} NoInvalidPropertiesRuleDefinition
*/

//-----------------------------------------------------------------------------
// Helpers
//-----------------------------------------------------------------------------

/**
* Replaces all instances of a search string with a replacement and tracks the offsets
* @param {string} text The text to perform replacements on
* @param {string} searchValue The string to search for
* @param {string} replaceValue The string to replace with
* @returns {{text: string, offsets: Array<number>}} The updated text and array of offsets where replacements occurred
*/
function replaceWithOffsets(text, searchValue, replaceValue) {
const offsets = [];
let result = "";
let lastIndex = 0;
let index;

while ((index = text.indexOf(searchValue, lastIndex)) !== -1) {
result += text.slice(lastIndex, index);
result += replaceValue;
offsets.push(index);
lastIndex = index + searchValue.length;
}

result += text.slice(lastIndex);
return { text: result, offsets };
}

//-----------------------------------------------------------------------------
// Rule Definition
//-----------------------------------------------------------------------------
Expand All @@ -38,26 +67,100 @@ export default {
invalidPropertyValue:
"Invalid value '{{value}}' for property '{{property}}'. Expected {{expected}}.",
unknownProperty: "Unknown property '{{property}}' found.",
unknownVar: "Can't validate with unknown variable '{{var}}'.",
},
},

create(context) {
const lexer = context.sourceCode.lexer;
const sourceCode = context.sourceCode;
const lexer = sourceCode.lexer;

/** @type {Map<string,ValuePlain>} */
const vars = new Map();

/** @type {Array<Map<string,FunctionNodePlain>>} */
const replacements = [];

return {
"Rule > Block > Declaration"(node) {
// don't validate custom properties
"Rule > Block > Declaration"() {
replacements.push(new Map());
},

"Function[name=var]"(node) {
const map = replacements.at(-1);
if (!map) {
return;
}

/*
* Store the custom property name and the function node
* so can use these to validate the value later.
*/
const name = node.children[0].name;
map.set(name, node);
},

"Rule > Block > Declaration:exit"(node) {
if (node.property.startsWith("--")) {
// store the custom property name and value to validate later
vars.set(node.property, node.value);

// don't validate custom properties
return;
}

const { error } = lexer.matchDeclaration(node);
const varsFound = replacements.pop();

/** @type {Map<number,CssLocationRange>} */
const varsFoundLocs = new Map();
let value = node.value;

if (varsFound?.size > 0) {
// need to use a text version of the value here
value = sourceCode.getText(node.value);
let offsets;

// replace any custom properties with their values
for (const [name, func] of varsFound) {
const varValue = vars.get(name);

if (varValue) {
({ text: value, offsets } = replaceWithOffsets(
value,
`var(${name})`,
sourceCode.getText(varValue).trim(),
));

/*
* Store the offsets of the replacements so we can
* report the correct location of any validation error.
*/
offsets.forEach(offset => {
varsFoundLocs.set(offset, func.loc);
});
} else {
context.report({
loc: func.children[0].loc,
messageId: "unknownVar",
data: {
var: name,
},
});

return;
}
}
}

const { error } = lexer.matchProperty(node.property, value);

if (error) {
// validation failure
if (isSyntaxMatchError(error)) {
context.report({
loc: error.loc,
loc:
varsFoundLocs.get(error.mismatchOffset) ??
error.loc,
messageId: "invalidPropertyValue",
data: {
property: node.property,
Expand All @@ -68,18 +171,6 @@ export default {
return;
}

/*
* There's no current way to get lexing to work when a
* `var()` is present in a value. Rather than blowing up,
* we'll just ignore it.
*
* https://github.com/csstree/csstree/issues/317
*/

if (error.message.endsWith("var() is not supported")) {
return;
}

// unknown property
context.report({
loc: {
Expand Down
89 changes: 89 additions & 0 deletions tests/rules/no-invalid-properties.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ ruleTester.run("no-invalid-properties", rule, {
"@font-face { font-weight: 100 400 }",
'@property --foo { syntax: "*"; inherits: false; }',
"a { --my-color: red; color: var(--my-color) }",
":root { --my-color: red; }\na { color: var(--my-color) }",
{
code: "a { my-custom-color: red; }",
languageOptions: {
Expand Down Expand Up @@ -229,5 +230,93 @@ ruleTester.run("no-invalid-properties", rule, {
},
],
},
{
code: "a { color: var(--my-color); }",
errors: [
{
messageId: "unknownVar",
data: {
var: "--my-color",
},
line: 1,
column: 16,
endLine: 1,
endColumn: 26,
},
],
},
{
code: "a { --my-color: 10px; color: var(--my-color); }",
errors: [
{
messageId: "invalidPropertyValue",
data: {
property: "color",
value: "10px",
expected: "<color>",
},
line: 1,
column: 30,
endLine: 1,
endColumn: 45,
},
],
},
{
code: "a { --my-color: 10px; color: var(--my-color); background-color: var(--my-color); }",
errors: [
{
messageId: "invalidPropertyValue",
data: {
property: "color",
value: "10px",
expected: "<color>",
},
line: 1,
column: 30,
endLine: 1,
endColumn: 45,
},
{
messageId: "invalidPropertyValue",
data: {
property: "background-color",
value: "10px",
expected: "<color>",
},
line: 1,
column: 65,
endLine: 1,
endColumn: 80,
},
],
},
{
code: "a { --my-color: 10px; color: var(--my-color); background-color: var(--unknown-var); }",
errors: [
{
messageId: "invalidPropertyValue",
data: {
property: "color",
value: "10px",
expected: "<color>",
},
line: 1,
column: 30,
endLine: 1,
endColumn: 45,
},
{
messageId: "unknownVar",
data: {
var: "--unknown-var",
},
line: 1,
column: 69,
endLine: 1,
endColumn: 82,
},
],
},
],
});