index.mjs 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. import valueParser from 'postcss-value-parser';
  2. import { assert, isRegExp, isString } from '../../utils/validateTypes.mjs';
  3. import { declarationValueIndex } from '../../utils/nodeFieldIndices.mjs';
  4. import getDeclarationValue from '../../utils/getDeclarationValue.mjs';
  5. import isStandardSyntaxValue from '../../utils/isStandardSyntaxValue.mjs';
  6. import { isValueWord } from '../../utils/typeGuards.mjs';
  7. import optionsMatches from '../../utils/optionsMatches.mjs';
  8. import report from '../../utils/report.mjs';
  9. import ruleMessages from '../../utils/ruleMessages.mjs';
  10. import setDeclarationValue from '../../utils/setDeclarationValue.mjs';
  11. import validateOptions from '../../utils/validateOptions.mjs';
  12. const ruleName = 'alpha-value-notation';
  13. const messages = ruleMessages(ruleName, {
  14. expected: (unfixed, fixed) => `Expected "${unfixed}" to be "${fixed}"`,
  15. });
  16. const meta = {
  17. url: 'https://stylelint.io/user-guide/rules/alpha-value-notation',
  18. fixable: true,
  19. };
  20. const ALPHA_PROPS =
  21. /^(?:opacity|shape-image-threshold|fill-opacity|flood-opacity|stop-opacity|stroke-opacity)$/i;
  22. const ALPHA_FUNCTION = /(?:color|hsla?|rgba?|hwb|lab|lch|oklab|oklch)\(/i;
  23. const ALPHA_FUNCTION_NAME = /^(?:color|hsla?|rgba?|hwb|lab|lch|oklab|oklch)$/i;
  24. const DIGIT = /\d/;
  25. /** @type {import('stylelint').CoreRules[ruleName]} */
  26. const rule = (primary, secondaryOptions) => {
  27. return (root, result) => {
  28. const validOptions = validateOptions(
  29. result,
  30. ruleName,
  31. {
  32. actual: primary,
  33. possible: ['number', 'percentage'],
  34. },
  35. {
  36. actual: secondaryOptions,
  37. possible: {
  38. exceptProperties: [isString, isRegExp],
  39. },
  40. optional: true,
  41. },
  42. );
  43. if (!validOptions) return;
  44. const optionFuncs = Object.freeze({
  45. number: {
  46. expFunc: isNumber,
  47. fixFunc: asNumber,
  48. },
  49. percentage: {
  50. expFunc: isPercentage,
  51. fixFunc: asPercentage,
  52. },
  53. });
  54. root.walkDecls((decl) => {
  55. const declarationValue = getDeclarationValue(decl);
  56. const isAlphaProp = ALPHA_PROPS.test(decl.prop);
  57. const isAlpha = isAlphaProp || ALPHA_FUNCTION.test(declarationValue);
  58. if (!isAlpha || !DIGIT.test(declarationValue)) return;
  59. const parsedValue = valueParser(declarationValue);
  60. parsedValue.walk((node) => {
  61. const inVal = isAlphaProp && DIGIT.test(node.value);
  62. const inFn = node.type === 'function' && ALPHA_FUNCTION_NAME.test(node.value);
  63. const alpha = inVal ? findAlphaInValue(node) : inFn ? findAlphaInFunction(node) : undefined;
  64. if (!alpha) return;
  65. const { value } = alpha;
  66. if (!isStandardSyntaxValue(value)) return;
  67. if (!isNumber(value) && !isPercentage(value)) return;
  68. /** @type {'number' | 'percentage'} */
  69. let expectation = primary;
  70. if (optionsMatches(secondaryOptions, 'exceptProperties', decl.prop)) {
  71. if (expectation === 'number') {
  72. expectation = 'percentage';
  73. } else if (expectation === 'percentage') {
  74. expectation = 'number';
  75. }
  76. }
  77. if (optionFuncs[expectation].expFunc(value)) return;
  78. const fixed = optionFuncs[expectation].fixFunc(value);
  79. const unfixed = value;
  80. const index = declarationValueIndex(decl) + alpha.sourceIndex;
  81. const endIndex = index + alpha.value.length;
  82. const fix = () => {
  83. alpha.value = fixed;
  84. setDeclarationValue(decl, parsedValue.toString());
  85. };
  86. report({
  87. message: messages.expected,
  88. messageArgs: [unfixed, fixed],
  89. node: decl,
  90. index,
  91. endIndex,
  92. result,
  93. ruleName,
  94. fix: {
  95. apply: fix,
  96. node: decl,
  97. },
  98. });
  99. });
  100. });
  101. };
  102. };
  103. /**
  104. * @param {string} value
  105. * @returns {string}
  106. */
  107. function asPercentage(value) {
  108. const number = Number(value);
  109. return `${Number((number * 100).toPrecision(3))}%`;
  110. }
  111. /**
  112. * @param {string} value
  113. * @returns {string}
  114. */
  115. function asNumber(value) {
  116. const dimension = valueParser.unit(value);
  117. assert(dimension);
  118. const number = Number(dimension.number);
  119. return Number((number / 100).toPrecision(3)).toString();
  120. }
  121. /**
  122. * @template {import('postcss-value-parser').Node} T
  123. * @param {T} node
  124. * @returns {T | undefined}
  125. */
  126. function findAlphaInValue(node) {
  127. return node.type === 'word' || node.type === 'function' ? node : undefined;
  128. }
  129. /**
  130. * @param {import('postcss-value-parser').FunctionNode} node
  131. * @returns {import('postcss-value-parser').Node | undefined}
  132. */
  133. function findAlphaInFunction(node) {
  134. const legacySyntax = node.nodes.some(({ type, value }) => type === 'div' && value === ',');
  135. if (legacySyntax) {
  136. const args = node.nodes.filter(({ type }) => type === 'word' || type === 'function');
  137. if (args.length === 4) return args[3];
  138. return undefined;
  139. }
  140. const slashNodeIndex = node.nodes.findIndex(({ type, value }) => type === 'div' && value === '/');
  141. if (slashNodeIndex !== -1) {
  142. const nodesAfterSlash = node.nodes.slice(slashNodeIndex + 1, node.nodes.length);
  143. return nodesAfterSlash.find(isValueWord);
  144. }
  145. return undefined;
  146. }
  147. /**
  148. * @param {string} value
  149. * @returns {boolean}
  150. */
  151. function isPercentage(value) {
  152. const dimension = valueParser.unit(value);
  153. return dimension && dimension.unit === '%';
  154. }
  155. /**
  156. * @param {string} value
  157. * @returns {boolean}
  158. */
  159. function isNumber(value) {
  160. const dimension = valueParser.unit(value);
  161. return dimension && dimension.unit === '';
  162. }
  163. rule.ruleName = ruleName;
  164. rule.messages = messages;
  165. rule.meta = meta;
  166. export default rule;