|
| 1 | +const stylelint = require('stylelint'); |
| 2 | +const path = require('path'); |
| 3 | +const isStandardSyntaxRule = require('stylelint/lib/utils/isStandardSyntaxRule'); |
| 4 | +const isStandardSyntaxSelector = require('stylelint/lib/utils/isStandardSyntaxSelector'); |
| 5 | + |
| 6 | +const ruleName = 'material/selector-nested-pattern-scoped'; |
| 7 | +const messages = stylelint.utils.ruleMessages(ruleName, { |
| 8 | + expected: selector => `Expected nested selector '${selector}' to match specified pattern`, |
| 9 | +}); |
| 10 | + |
| 11 | +/** |
| 12 | + * Re-implementation of the `selector-nested-pattern` Stylelint rule, allowing us |
| 13 | + * to scope it to a particular set of files via the custom `filePattern` option. The |
| 14 | + * primary use-case is to be able to apply the rule only to theme files. |
| 15 | + * |
| 16 | + * Reference: https://stylelint.io/user-guide/rules/selector-nested-pattern/ |
| 17 | + * Source: https://github.com/stylelint/stylelint/blob/master/lib/rules/selector-nested-pattern/ |
| 18 | + */ |
| 19 | +const plugin = stylelint.createPlugin(ruleName, (pattern, options) => { |
| 20 | + return (root, result) => { |
| 21 | + const selectorPattern = new RegExp(pattern); |
| 22 | + const filePattern = new RegExp(options.filePattern); |
| 23 | + const fileName = path.basename(root.source.input.file); |
| 24 | + |
| 25 | + if (!filePattern.test(fileName)) return; |
| 26 | + |
| 27 | + root.walkRules(rule => { |
| 28 | + if (rule.parent.type === 'rule' && |
| 29 | + isStandardSyntaxRule(rule) && |
| 30 | + isStandardSyntaxSelector(rule.selector) && |
| 31 | + !selectorPattern.test(rule.selector)) { |
| 32 | + |
| 33 | + stylelint.utils.report({ |
| 34 | + result, |
| 35 | + ruleName, |
| 36 | + message: messages.expected(rule.selector), |
| 37 | + node: rule |
| 38 | + }); |
| 39 | + } |
| 40 | + }); |
| 41 | + }; |
| 42 | +}); |
| 43 | + |
| 44 | +plugin.ruleName = ruleName; |
| 45 | +plugin.messages = messages; |
| 46 | +module.exports = plugin; |
0 commit comments