index.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. 'use strict';
  2. const valueParser = require('postcss-value-parser');
  3. const declarationValueIndex = require('../../utils/declarationValueIndex');
  4. const flattenArray = require('../../utils/flattenArray');
  5. const getUnitFromValueNode = require('../../utils/getUnitFromValueNode');
  6. const matchesStringOrRegExp = require('../../utils/matchesStringOrRegExp');
  7. const report = require('../../utils/report');
  8. const ruleMessages = require('../../utils/ruleMessages');
  9. const validateObjectWithArrayProps = require('../../utils/validateObjectWithArrayProps');
  10. const validateOptions = require('../../utils/validateOptions');
  11. const { isString } = require('../../utils/validateTypes');
  12. const vendor = require('../../utils/vendor');
  13. const ruleName = 'declaration-property-unit-disallowed-list';
  14. const messages = ruleMessages(ruleName, {
  15. rejected: (property, unit) => `Unexpected unit "${unit}" for property "${property}"`,
  16. });
  17. const meta = {
  18. url: 'https://stylelint.io/user-guide/rules/list/declaration-property-unit-disallowed-list',
  19. };
  20. /** @type {import('stylelint').Rule<Record<string, string | string[]>>} */
  21. const rule = (primary) => {
  22. return (root, result) => {
  23. const validOptions = validateOptions(result, ruleName, {
  24. actual: primary,
  25. possible: [validateObjectWithArrayProps(isString)],
  26. });
  27. if (!validOptions) {
  28. return;
  29. }
  30. root.walkDecls((decl) => {
  31. const prop = decl.prop;
  32. const value = decl.value;
  33. const unprefixedProp = vendor.unprefixed(prop);
  34. const propKey = Object.keys(primary).find((propIdentifier) =>
  35. matchesStringOrRegExp(unprefixedProp, propIdentifier),
  36. );
  37. if (!propKey) {
  38. return;
  39. }
  40. const propList = flattenArray(primary[propKey]);
  41. if (!propList) {
  42. return;
  43. }
  44. valueParser(value).walk((node) => {
  45. // Ignore wrong units within `url` function
  46. if (node.type === 'function' && node.value.toLowerCase() === 'url') {
  47. return false;
  48. }
  49. if (node.type === 'string') {
  50. return;
  51. }
  52. const unit = getUnitFromValueNode(node);
  53. if (!unit || (unit && !propList.includes(unit.toLowerCase()))) {
  54. return;
  55. }
  56. report({
  57. message: messages.rejected(prop, unit),
  58. node: decl,
  59. index: declarationValueIndex(decl) + node.sourceIndex,
  60. result,
  61. ruleName,
  62. });
  63. });
  64. });
  65. };
  66. };
  67. rule.ruleName = ruleName;
  68. rule.messages = messages;
  69. rule.meta = meta;
  70. module.exports = rule;