index.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. 'use strict';
  2. const atRuleParamIndex = require('../../utils/atRuleParamIndex');
  3. const report = require('../../utils/report');
  4. const ruleMessages = require('../../utils/ruleMessages');
  5. const validateOptions = require('../../utils/validateOptions');
  6. const { isRegExp, isString } = require('../../utils/validateTypes');
  7. const ruleName = 'custom-media-pattern';
  8. const messages = ruleMessages(ruleName, {
  9. expected: (pattern) => `Expected custom media query name to match pattern "${pattern}"`,
  10. });
  11. const meta = {
  12. url: 'https://stylelint.io/user-guide/rules/list/custom-media-pattern',
  13. };
  14. /** @type {import('stylelint').Rule} */
  15. const rule = (primary) => {
  16. return (root, result) => {
  17. const validOptions = validateOptions(result, ruleName, {
  18. actual: primary,
  19. possible: [isRegExp, isString],
  20. });
  21. if (!validOptions) {
  22. return;
  23. }
  24. const regexpPattern = isString(primary) ? new RegExp(primary) : primary;
  25. root.walkAtRules((atRule) => {
  26. if (atRule.name.toLowerCase() !== 'custom-media') {
  27. return;
  28. }
  29. const match = atRule.params.match(/^--(\S+)\b/);
  30. if (match == null) throw new Error(`Unexpected at-rule params: "${atRule.params}"`);
  31. const customMediaName = match[1];
  32. if (regexpPattern.test(customMediaName)) {
  33. return;
  34. }
  35. report({
  36. message: messages.expected(primary),
  37. node: atRule,
  38. index: atRuleParamIndex(atRule),
  39. result,
  40. ruleName,
  41. });
  42. });
  43. };
  44. };
  45. rule.ruleName = ruleName;
  46. rule.messages = messages;
  47. rule.meta = meta;
  48. module.exports = rule;