UNPKG

@salesforce-ux/eslint-plugin-slds

Version:

ESLint plugin provides custom linting rules specifically built for Salesforce Lightning Design System 2 (SLDS 2 beta)

400 lines (389 loc) 13.3 kB
var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/rules/v9/no-hardcoded-values/handlers/fontHandler.ts var fontHandler_exports = {}; __export(fontHandler_exports, { handleFontDeclaration: () => handleFontDeclaration }); module.exports = __toCommonJS(fontHandler_exports); // src/utils/value-utils.ts var ALLOWED_UNITS = ["px", "em", "rem", "%", "ch"]; function parseUnitValue(value) { if (!value) return null; const unitsPattern = ALLOWED_UNITS.join("|"); const regex = new RegExp(`^(-?\\d*\\.?\\d+)(${unitsPattern})?$`); const match = value.match(regex); if (!match) return null; const number = parseFloat(match[1]); const unit = match[2] ? match[2] : null; if (isNaN(number)) return null; return { number, unit }; } function toAlternateUnitValue(numberVal, unitType) { if (unitType === "px") { let floatValue = parseFloat(`${numberVal / 16}`); if (!isNaN(floatValue)) { return { unit: "rem", number: parseFloat(floatValue.toFixed(4)) }; } } else if (unitType === "rem") { const intValue = parseInt(`${numberVal * 16}`); if (!isNaN(intValue)) { return { unit: "px", number: intValue }; } } return null; } // src/utils/styling-hook-utils.ts function isValueMatch(valueToMatch, sldsValue) { if (!valueToMatch || !sldsValue) { return false; } return valueToMatch.unit == sldsValue.unit && valueToMatch.number === sldsValue.number; } function getStylingHooksForDensityValue(parsedValue, supportedStylinghooks, cssProperty) { if (!parsedValue) return []; const alternateValue = toAlternateUnitValue(parsedValue.number, parsedValue.unit); const matchedHooks = []; for (const [sldsValue, hooks] of Object.entries(supportedStylinghooks)) { const parsedSldsValue = parseUnitValue(sldsValue); if (isValueMatch(parsedValue, parsedSldsValue) || alternateValue && isValueMatch(alternateValue, parsedSldsValue)) { hooks.filter((hook) => hook.properties.includes(cssProperty)).forEach((hook) => matchedHooks.push(hook.name)); } } return matchedHooks; } // src/utils/property-matcher.ts var DIRECTION_VALUES = "(?:top|right|bottom|left|inline|block|inline-start|inline-end|start|end|block-start|block-end)"; var CORNER_VALUES = "(?:top-left|top-right|bottom-right|bottom-left|start-start|start-end|end-start|end-end)"; var INSET_VALUES = "(?:inline|block|inline-start|inline-end|block-start|block-end)"; var BORDER_COLOR_REGEX = new RegExp(`^border(?:-${DIRECTION_VALUES})?-color$`); var BORDER_WIDTH_REGEX = new RegExp(`^border(?:-${DIRECTION_VALUES})?-width$`); var MARGIN_REGEX = new RegExp(`^margin(?:-${DIRECTION_VALUES})?$`); var PADDING_REGEX = new RegExp(`^padding(?:-${DIRECTION_VALUES})?$`); var BORDER_RADIUS_REGEX = new RegExp(`^border(?:-${CORNER_VALUES})?-radius$`); var INSET_REGEX = new RegExp(`^inset(?:-${INSET_VALUES})?$`); function isBorderColorProperty(cssProperty) { return BORDER_COLOR_REGEX.test(cssProperty); } function isBorderWidthProperty(cssProperty) { return BORDER_WIDTH_REGEX.test(cssProperty); } function isMarginProperty(cssProperty) { return MARGIN_REGEX.test(cssProperty); } function isPaddingProperty(cssProperty) { return PADDING_REGEX.test(cssProperty); } function isBorderRadius(cssProperty) { return BORDER_RADIUS_REGEX.test(cssProperty); } function isDimensionProperty(cssProperty) { return ["width", "height", "min-width", "max-width", "min-height", "max-height"].includes(cssProperty); } function isInsetProperty(cssProperty) { return INSET_REGEX.test(cssProperty); } function resolvePropertyToMatch(cssProperty) { const propertyToMatch = cssProperty.toLowerCase(); if (propertyToMatch === "outline" || propertyToMatch === "outline-width" || isBorderWidthProperty(propertyToMatch)) { return "border-width"; } else if (isMarginProperty(propertyToMatch)) { return "margin"; } else if (isPaddingProperty(propertyToMatch)) { return "padding"; } else if (isBorderRadius(propertyToMatch)) { return "border-radius"; } else if (isDimensionProperty(propertyToMatch)) { return "width"; } else if (isInsetProperty(propertyToMatch)) { return "top"; } else if (cssProperty === "background" || cssProperty === "background-color") { return "background-color"; } else if (cssProperty === "outline" || cssProperty === "outline-color" || isBorderColorProperty(cssProperty)) { return "border-color"; } return propertyToMatch; } // src/utils/hardcoded-shared-utils.ts var import_css_tree2 = require("@eslint/css-tree"); // src/utils/color-lib-utils.ts var import_chroma_js = __toESM(require("chroma-js")); var import_css_tree = require("@eslint/css-tree"); // src/utils/css-functions.ts var CSS_FUNCTIONS = [ "attr", "calc", "color-mix", "conic-gradient", "counter", "cubic-bezier", "linear-gradient", "max", "min", "radial-gradient", "repeating-conic-gradient", "repeating-linear-gradient", "repeating-radial-gradient", "var" ]; var CSS_MATH_FUNCTIONS = ["calc", "min", "max"]; var cssFunctionsRegex = new RegExp(`(?:${CSS_FUNCTIONS.join("|")})`); var cssFunctionsExactRegex = new RegExp(`^(?:${CSS_FUNCTIONS.join("|")})$`); var cssMathFunctionsRegex = new RegExp(`^(?:${CSS_MATH_FUNCTIONS.join("|")})$`); // src/utils/hardcoded-shared-utils.ts var FONT_WEIGHTS = [ "normal", "bold", "bolder", "lighter", "100", "200", "300", "400", "500", "600", "700", "800", "900" ]; function isKnownFontWeight(value) { const stringValue = value.toString(); return FONT_WEIGHTS.includes(stringValue.toLowerCase()); } function handleShorthandAutoFix(declarationNode, context, valueText, replacements) { const sortedReplacements = replacements.sort((a, b) => a.start - b.start); const hasAnyHooks = sortedReplacements.some((r) => r.hasHook); const canAutoFix = hasAnyHooks; sortedReplacements.forEach(({ start, end, replacement, displayValue, hasHook }) => { const originalValue = valueText.substring(start, end); const valueStartColumn = declarationNode.value.loc.start.column; const valueColumn = valueStartColumn + start; const { loc: { start: locStart, end: locEnd } } = declarationNode.value; const reportNode = { ...declarationNode.value, loc: { ...declarationNode.value.loc, start: { ...locStart, column: valueColumn }, end: { ...locEnd, column: valueColumn + originalValue.length } } }; if (hasHook) { const fix = canAutoFix ? (fixer) => { let newValue = valueText; for (let i = sortedReplacements.length - 1; i >= 0; i--) { const { start: rStart, end: rEnd, replacement: rReplacement } = sortedReplacements[i]; newValue = newValue.substring(0, rStart) + rReplacement + newValue.substring(rEnd); } return fixer.replaceText(declarationNode.value, newValue); } : void 0; context.context.report({ node: reportNode, messageId: "hardcodedValue", data: { oldValue: originalValue, newValue: displayValue }, fix }); } else { context.context.report({ node: reportNode, messageId: "noReplacement", data: { oldValue: originalValue } }); } }); } function forEachValue(valueText, extractValue, shouldSkipNode, callback) { if (!valueText || typeof valueText !== "string") { return; } try { const ast = (0, import_css_tree2.parse)(valueText, { context: "value", positions: true }); (0, import_css_tree2.walk)(ast, { enter(node) { if (shouldSkipNode(node)) { return this.skip; } const value = extractValue(node); if (value !== null) { const positionInfo = { start: node.loc?.start, end: node.loc?.end }; callback(value, positionInfo); } } }); } catch (error) { return; } } function extractFontValue(node) { if (!node) return null; switch (node.type) { case "Dimension": const numValue = Number(node.value); if (numValue <= 0) return null; const unit = node.unit.toLowerCase(); if (!ALLOWED_UNITS.includes(unit)) return null; return { number: numValue, unit }; case "Number": const numberValue = Number(node.value); if (numberValue <= 0) { return null; } if (!isKnownFontWeight(numberValue)) { return null; } return { number: numberValue, unit: null }; case "Identifier": const namedValue = node.name.toLowerCase(); if (!isKnownFontWeight(namedValue)) { return null; } if (namedValue === "normal") { return { number: 400, unit: null }; } return { number: namedValue, unit: null }; case "Percentage": const percentValue = Number(node.value); if (percentValue === 0) return null; return { number: percentValue, unit: "%" }; case "Value": return node.children?.[0] ? extractFontValue(node.children[0]) : null; } return null; } function shouldSkipFontNode(node) { return node.type === "Function"; } function forEachFontValue(valueText, callback) { forEachValue(valueText, extractFontValue, shouldSkipFontNode, callback); } // src/utils/css-utils.ts function formatSuggestionHooks(hooks) { if (hooks.length === 1) { return `${hooks[0]}`; } return "\n" + hooks.map((hook, index) => `${index + 1}. ${hook}`).join("\n"); } // src/rules/v9/no-hardcoded-values/handlers/fontHandler.ts var handleFontDeclaration = (node, context) => { const cssProperty = node.property.toLowerCase(); const valueText = context.sourceCode.getText(node.value); const replacements = []; forEachFontValue(valueText, (fontValue, positionInfo) => { if (fontValue && isValidFontValue(fontValue, cssProperty)) { const replacement = createFontReplacement(fontValue, cssProperty, context, positionInfo); if (replacement) { replacements.push(replacement); } } }); handleShorthandAutoFix(node, context, valueText, replacements); }; function isValidFontValue(fontValue, cssProperty) { if (cssProperty === "font-size") { return !!fontValue.unit; } else if (cssProperty === "font-weight") { return !fontValue.unit && isKnownFontWeight(fontValue.number); } else if (cssProperty === "font") { if (!fontValue.unit && isKnownFontWeight(fontValue.number)) { return true; } else if (fontValue.unit) { return true; } else { return false; } } return false; } function createFontReplacement(fontValue, cssProperty, context, positionInfo) { if (!positionInfo?.start) { return null; } const rawValue = fontValue.unit ? `${fontValue.number}${fontValue.unit}` : fontValue.number.toString(); const propToMatch = !fontValue.unit && isKnownFontWeight(fontValue.number) ? resolvePropertyToMatch("font-weight") : resolvePropertyToMatch("font-size"); const closestHooks = getStylingHooksForDensityValue(fontValue, context.valueToStylinghook, propToMatch); const start = positionInfo.start.offset; const end = positionInfo.end.offset; if (closestHooks.length === 1) { return { start, end, replacement: `var(${closestHooks[0]}, ${rawValue})`, displayValue: closestHooks[0], hasHook: true }; } else if (closestHooks.length > 1) { return { start, end, replacement: rawValue, displayValue: formatSuggestionHooks(closestHooks), hasHook: true }; } else { return { start, end, replacement: rawValue, displayValue: rawValue, hasHook: false }; } } // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { handleFontDeclaration }); //# sourceMappingURL=fontHandler.js.map