diff --git a/docs/rules/no-invalid-properties.md b/docs/rules/no-invalid-properties.md index 767a1010..d26e8aa3 100644 --- a/docs/rules/no-invalid-properties.md +++ b/docs/rules/no-invalid-properties.md @@ -44,7 +44,21 @@ 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)`, the rule can only properly be validated 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 to ensure proper validation. ## When Not to Use It diff --git a/src/rules/no-invalid-properties.js b/src/rules/no-invalid-properties.js index d88de047..5b785395 100644 --- a/src/rules/no-invalid-properties.js +++ b/src/rules/no-invalid-properties.js @@ -15,10 +15,48 @@ 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 regex pattern with a replacement and tracks the offsets + * @param {string} text The text to perform replacements on + * @param {string} varName The regex pattern string to search for + * @param {string} replaceValue The string to replace with + * @returns {{text: string, offsets: Array}} The updated text and array of offsets + * where replacements occurred + */ +function replaceWithOffsets(text, varName, replaceValue) { + const offsets = []; + let result = ""; + let lastIndex = 0; + + const regex = new RegExp(`var\\(\\s*${varName}\\s*\\)`, "gu"); + let match; + + while ((match = regex.exec(text)) !== null) { + result += text.slice(lastIndex, match.index); + + /* + * We need the offset of the replacement after other replacements have + * been made, so we push the current length of the result before appending + * the replacement value. + */ + offsets.push(result.length); + result += replaceValue; + lastIndex = match.index + match[0].length; + } + + result += text.slice(lastIndex); + return { text: result, offsets }; +} + //----------------------------------------------------------------------------- // Rule Definition //----------------------------------------------------------------------------- @@ -38,48 +76,135 @@ 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} */ + const vars = new Map(); + + /** + * We need to track this as a stack because we can have nested + * rules that use the `var()` function, and we need to + * ensure that we validate the innermost rule first. + * @type {Array>} + */ + 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} */ + const varsFoundLocs = new Map(); + const usingVars = varsFound?.size > 0; + let value = node.value; + + if (usingVars) { + // 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, + 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, + /* + * When using variables, check to see if the error + * occurred at a location where a variable was replaced. + * If so, use that location; otherwise, use the error's + * reported location. + */ + loc: usingVars + ? (varsFoundLocs.get(error.mismatchOffset) ?? + node.value.loc) + : error.loc, messageId: "invalidPropertyValue", data: { property: node.property, - value: error.css, + + /* + * When using variables, slice the value to + * only include the part that caused the error. + * Otherwise, use the full value from the error. + */ + value: usingVars + ? value.slice( + error.mismatchOffset, + error.mismatchOffset + + error.mismatchLength, + ) + : error.css, expected: error.syntax, }, }); 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: { diff --git a/tests/rules/no-invalid-properties.test.js b/tests/rules/no-invalid-properties.test.js index 6f3cfd00..1d77e5c8 100644 --- a/tests/rules/no-invalid-properties.test.js +++ b/tests/rules/no-invalid-properties.test.js @@ -33,6 +33,9 @@ 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) }", + ":root { --my-color: red; }\na { color: var( --my-color ) }", + ":root { --my-color: red;\n.foo { color: var(--my-color) }\n}", { code: "a { my-custom-color: red; }", languageOptions: { @@ -79,6 +82,23 @@ ruleTester.run("no-invalid-properties", rule, { }, ], }, + { + code: "a { border-top: 10px solid foo }", + errors: [ + { + messageId: "invalidPropertyValue", + data: { + property: "border-top", + value: "10px solid foo", + expected: " || || ", + }, + line: 1, + column: 28, + endLine: 1, + endColumn: 31, + }, + ], + }, { code: "a { width: red }", errors: [ @@ -229,5 +249,159 @@ 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 { .foo { color: var(--undefined-var); } }", + errors: [ + { + messageId: "unknownVar", + data: { + var: "--undefined-var", + }, + line: 1, + column: 23, + endLine: 1, + endColumn: 38, + }, + ], + }, + { + code: "a { --my-color: 10px; color: var(--my-color); }", + errors: [ + { + messageId: "invalidPropertyValue", + data: { + property: "color", + value: "10px", + expected: "", + }, + 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: "", + }, + line: 1, + column: 30, + endLine: 1, + endColumn: 45, + }, + { + messageId: "invalidPropertyValue", + data: { + property: "background-color", + value: "10px", + expected: "", + }, + 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: "", + }, + line: 1, + column: 30, + endLine: 1, + endColumn: 45, + }, + { + messageId: "unknownVar", + data: { + var: "--unknown-var", + }, + line: 1, + column: 69, + endLine: 1, + endColumn: 82, + }, + ], + }, + { + code: "a { --width: 1px; border-top: var(--width) solid bar; }", + errors: [ + { + messageId: "invalidPropertyValue", + data: { + property: "border-top", + value: "bar", + expected: " || || ", + }, + line: 1, + column: 31, + endLine: 1, + endColumn: 53, + }, + ], + }, + { + code: "a { --width: baz; --style: foo; border-top: var(--width) var(--style) bar; }", + errors: [ + { + messageId: "invalidPropertyValue", + data: { + property: "border-top", + value: "baz", + expected: " || || ", + }, + line: 1, + column: 45, + endLine: 1, + endColumn: 57, + }, + ], + }, + { + code: "a { --width: 1px; border-top: var(--width) solid var(--width); }", + errors: [ + { + messageId: "invalidPropertyValue", + data: { + property: "border-top", + value: "1px", + expected: " || || ", + }, + line: 1, + column: 50, + endLine: 1, + endColumn: 62, + }, + ], + }, ], });