|
| 1 | +/* |
| 2 | + * Copyright 2025 Palantir Technologies, Inc. All rights reserved. |
| 3 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | + * you may not use this file except in compliance with the License. |
| 5 | + * You may obtain a copy of the License at |
| 6 | + * |
| 7 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | + * |
| 9 | + * Unless required by applicable law or agreed to in writing, software |
| 10 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | + * See the License for the specific language governing permissions and |
| 13 | + * limitations under the License. |
| 14 | + */ |
| 15 | + |
| 16 | +import type { Declaration, Root } from "postcss"; |
| 17 | +import valueParser from "postcss-value-parser"; |
| 18 | +import stylelint, { type PostcssResult, type RuleContext } from "stylelint"; |
| 19 | + |
| 20 | +import { BpVariablePrefixMap, CssSyntax, getCssSyntax, isCssSyntaxToStringMap } from "../utils/cssSyntax"; |
| 21 | + |
| 22 | +const ruleName = "@blueprintjs/prefer-spacing-variable"; |
| 23 | + |
| 24 | +const GRID_SIZE_VARIABLE = "pt-grid-size"; |
| 25 | +const SPACING_VARIABLE = "pt-spacing"; |
| 26 | + |
| 27 | +const messages = stylelint.utils.ruleMessages(ruleName, { |
| 28 | + expected: (unfixed: string, fixed: string) => |
| 29 | + `Use \`${fixed}\` instead of \`${unfixed}\` (deprecated). See: https://github.com/palantir/blueprint/wiki/Spacing-System-Migration:-10px-to-4px`, |
| 30 | +}); |
| 31 | + |
| 32 | +interface Options { |
| 33 | + disableFix?: boolean; |
| 34 | + variablesImportPath?: Partial<Record<Exclude<CssSyntax, CssSyntax.OTHER>, string>>; |
| 35 | +} |
| 36 | + |
| 37 | +const ruleImpl = |
| 38 | + (enabled: boolean, options: Options | undefined, context: RuleContext) => (root: Root, result: PostcssResult) => { |
| 39 | + if (!enabled) { |
| 40 | + return; |
| 41 | + } |
| 42 | + |
| 43 | + const validOptions = stylelint.utils.validateOptions( |
| 44 | + result, |
| 45 | + ruleName, |
| 46 | + { |
| 47 | + actual: enabled, |
| 48 | + optional: false, |
| 49 | + possible: [true, false], |
| 50 | + }, |
| 51 | + { |
| 52 | + actual: options, |
| 53 | + optional: true, |
| 54 | + possible: { |
| 55 | + disableFix: [true, false], |
| 56 | + variablesImportPath: [isCssSyntaxToStringMap], |
| 57 | + }, |
| 58 | + }, |
| 59 | + ); |
| 60 | + |
| 61 | + if (!validOptions) { |
| 62 | + return; |
| 63 | + } |
| 64 | + |
| 65 | + const disableFix = options?.disableFix ?? false; |
| 66 | + |
| 67 | + const cssSyntax = getCssSyntax(root.source?.input.file || ""); |
| 68 | + if (cssSyntax === CssSyntax.OTHER) { |
| 69 | + return; |
| 70 | + } |
| 71 | + |
| 72 | + const variablePrefix = BpVariablePrefixMap[cssSyntax]; |
| 73 | + const gridSizeVariable = `${variablePrefix}${GRID_SIZE_VARIABLE}`; |
| 74 | + const spacingVariable = `${variablePrefix}${SPACING_VARIABLE}`; |
| 75 | + |
| 76 | + root.walkDecls(decl => { |
| 77 | + // Skip declarations that don't contain grid-size variables |
| 78 | + if (!decl.value.includes(gridSizeVariable)) { |
| 79 | + return; |
| 80 | + } |
| 81 | + |
| 82 | + if (context.fix && !disableFix) { |
| 83 | + // Convert the entire value using string replacement |
| 84 | + const newValue = convertGridSizeToSpacing(decl.value, gridSizeVariable, spacingVariable); |
| 85 | + decl.value = newValue; |
| 86 | + } else { |
| 87 | + // Report warnings for each variable usage |
| 88 | + const parsedValue = valueParser(decl.value); |
| 89 | + parsedValue.walk(node => { |
| 90 | + if (node.type !== "word") { |
| 91 | + return; |
| 92 | + } |
| 93 | + |
| 94 | + const isGridSizeVariable = node.value.includes(gridSizeVariable); |
| 95 | + |
| 96 | + if (isGridSizeVariable) { |
| 97 | + const namespace = getVarNamespace(node.value); |
| 98 | + const isNamespaced = namespace !== undefined; |
| 99 | + |
| 100 | + const targetVar = isNamespaced ? `${namespace}.${spacingVariable}` : spacingVariable; |
| 101 | + |
| 102 | + stylelint.utils.report({ |
| 103 | + index: declarationValueIndex(decl) + node.sourceIndex, |
| 104 | + message: messages.expected(node.value, targetVar), |
| 105 | + node: decl, |
| 106 | + result, |
| 107 | + ruleName, |
| 108 | + }); |
| 109 | + } |
| 110 | + }); |
| 111 | + } |
| 112 | + }); |
| 113 | + }; |
| 114 | + |
| 115 | +function getVarNamespace(value: string): string | undefined { |
| 116 | + if (value.includes(".")) { |
| 117 | + return value.split(".")[0]; |
| 118 | + } |
| 119 | + return undefined; |
| 120 | +} |
| 121 | + |
| 122 | +/** |
| 123 | + * Converts grid-size variables to spacing variables, maintains original computed value. |
| 124 | + */ |
| 125 | +function convertGridSizeToSpacing(value: string, gridVar: string, spacingVar: string): string { |
| 126 | + let result = value; |
| 127 | + |
| 128 | + // Check if there's a namespaced variable (e.g., bp.$pt-grid-size) |
| 129 | + const namespacedMatch = value.match(new RegExp(`(\\w+)\\.\\$${GRID_SIZE_VARIABLE}`)); |
| 130 | + |
| 131 | + if (namespacedMatch) { |
| 132 | + // Process namespaced variable |
| 133 | + const namespace = namespacedMatch[1]; |
| 134 | + const namespacedGridVar = `${namespace}.${gridVar}`; |
| 135 | + const namespacedSpacingVar = `${namespace}.${spacingVar}`; |
| 136 | + |
| 137 | + result = processVariableConversions(result, namespacedGridVar, namespacedSpacingVar); |
| 138 | + } else { |
| 139 | + // Process non-namespaced variables |
| 140 | + result = processVariableConversions(result, gridVar, spacingVar); |
| 141 | + } |
| 142 | + |
| 143 | + return result; |
| 144 | +} |
| 145 | + |
| 146 | +/** |
| 147 | + * Process variable conversions for a specific variable pair |
| 148 | + */ |
| 149 | +function processVariableConversions(value: string, fromVar: string, toVar: string): string { |
| 150 | + let result = value; |
| 151 | + const escapedFrom = fromVar.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); |
| 152 | + |
| 153 | + // Handle right-side multiplication: $var * N -> $var * (N * 2.5) |
| 154 | + result = result.replace(new RegExp(`${escapedFrom}\\s*\\*\\s*(\\d*\\.?\\d+)`, "g"), (_match, multiplier) => { |
| 155 | + const newValue = parseFloat(multiplier) * 2.5; |
| 156 | + return `${toVar} * ${formatNumber(newValue)}`; |
| 157 | + }); |
| 158 | + |
| 159 | + // Handle left-side multiplication: N * $var -> (N * 2.5) * $var |
| 160 | + result = result.replace(new RegExp(`(\\d*\\.?\\d+)\\s*\\*\\s*${escapedFrom}`, "g"), (_match, multiplier) => { |
| 161 | + const newValue = parseFloat(multiplier) * 2.5; |
| 162 | + return `${formatNumber(newValue)} * ${toVar}`; |
| 163 | + }); |
| 164 | + |
| 165 | + // Handle division: $var / N -> $var / (N / 2.5) |
| 166 | + result = result.replace(new RegExp(`${escapedFrom}\\s*\\/\\s*(\\d*\\.?\\d+)`, "g"), (_match, divisor) => { |
| 167 | + const newValue = parseFloat(divisor) / 2.5; |
| 168 | + return `${toVar} / ${formatNumber(newValue)}`; |
| 169 | + }); |
| 170 | + |
| 171 | + // Handle simple variable replacement (no adjacent math operations) |
| 172 | + result = result.replace(new RegExp(`${escapedFrom}(?!\\s*[*/])`, "g"), `${toVar} * 2.5`); |
| 173 | + |
| 174 | + return result; |
| 175 | +} |
| 176 | + |
| 177 | +function formatNumber(num: number): string { |
| 178 | + return num % 1 === 0 ? num.toString() : num.toString(); |
| 179 | +} |
| 180 | + |
| 181 | +/** |
| 182 | + * Returns the index of the start of the declaration value. |
| 183 | + */ |
| 184 | +function declarationValueIndex(decl: Declaration): number { |
| 185 | + const beforeColon = decl.toString().indexOf(":"); |
| 186 | + const afterColon = decl.raw("between").length - decl.raw("between").indexOf(":"); |
| 187 | + return beforeColon + afterColon; |
| 188 | +} |
| 189 | + |
| 190 | +ruleImpl.ruleName = ruleName; |
| 191 | +ruleImpl.messages = messages; |
| 192 | + |
| 193 | +export default stylelint.createPlugin(ruleName, ruleImpl); |
0 commit comments