index.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. 'use strict';
  2. const isStandardSyntaxRule = require('../../utils/isStandardSyntaxRule');
  3. const parseSelector = require('../../utils/parseSelector');
  4. const report = require('../../utils/report');
  5. const ruleMessages = require('../../utils/ruleMessages');
  6. const validateOptions = require('../../utils/validateOptions');
  7. const { isRegExp, isString } = require('../../utils/validateTypes');
  8. const ruleName = 'selector-id-pattern';
  9. const messages = ruleMessages(ruleName, {
  10. expected: (selectorValue, pattern) =>
  11. `Expected ID selector "#${selectorValue}" to match pattern "${pattern}"`,
  12. });
  13. const meta = {
  14. url: 'https://stylelint.io/user-guide/rules/list/selector-id-pattern',
  15. };
  16. /** @type {import('stylelint').Rule} */
  17. const rule = (primary) => {
  18. return (root, result) => {
  19. const validOptions = validateOptions(result, ruleName, {
  20. actual: primary,
  21. possible: [isRegExp, isString],
  22. });
  23. if (!validOptions) {
  24. return;
  25. }
  26. /** @type {RegExp} */
  27. const normalizedPattern = isString(primary) ? new RegExp(primary) : primary;
  28. root.walkRules((ruleNode) => {
  29. if (!isStandardSyntaxRule(ruleNode)) {
  30. return;
  31. }
  32. const selector = ruleNode.selector;
  33. parseSelector(selector, result, ruleNode, (fullSelector) => {
  34. fullSelector.walk((selectorNode) => {
  35. if (selectorNode.type !== 'id') {
  36. return;
  37. }
  38. const value = selectorNode.value;
  39. const sourceIndex = selectorNode.sourceIndex;
  40. if (normalizedPattern.test(value)) {
  41. return;
  42. }
  43. report({
  44. result,
  45. ruleName,
  46. message: messages.expected(value, primary),
  47. node: ruleNode,
  48. index: sourceIndex,
  49. });
  50. });
  51. });
  52. });
  53. };
  54. };
  55. rule.ruleName = ruleName;
  56. rule.messages = messages;
  57. rule.meta = meta;
  58. module.exports = rule;