|
| 1 | +import stylelint from 'stylelint' |
| 2 | + |
| 3 | +const { |
| 4 | + createPlugin, |
| 5 | + utils: { |
| 6 | + report, |
| 7 | + ruleMessages, |
| 8 | + validateOptions |
| 9 | + } |
| 10 | +} = stylelint |
| 11 | +const ruleName = 'trigen/no-root-margin' |
| 12 | +const messages = ruleMessages(ruleName, { |
| 13 | + rejected: 'A block does not set its own outer margin: where it stands is its consumer\'s. Only `0` and `auto` reset or center it.' |
| 14 | +}) |
| 15 | +// The block's root alone, with its states or modifiers, not an element inside it |
| 16 | +const ROOT_SELECTOR_PATTERN = /^\.root(?![\w-])[^\s>+~]*$/ |
| 17 | +// A nested `&` with no combinator: the rule it stands in, in a state |
| 18 | +const NESTED_SAME_PATTERN = /^&[^\s>+~]*$/ |
| 19 | +const MARGIN_PATTERN = /^margin(-|$)/i |
| 20 | +const NEUTRAL_VALUES = new Set(['0', 'auto']) |
| 21 | + |
| 22 | +function isRootRule(rule) { |
| 23 | + return rule.selectors.some((selector) => { |
| 24 | + const trimmed = selector.trim() |
| 25 | + |
| 26 | + return ROOT_SELECTOR_PATTERN.test(trimmed) |
| 27 | + || (NESTED_SAME_PATTERN.test(trimmed) && rule.parent?.type === 'rule' && isRootRule(rule.parent)) |
| 28 | + }) |
| 29 | +} |
| 30 | + |
| 31 | +function ruleFunction(primary) { |
| 32 | + return (root, result) => { |
| 33 | + if (!validateOptions(result, ruleName, { |
| 34 | + actual: primary |
| 35 | + })) { |
| 36 | + return |
| 37 | + } |
| 38 | + |
| 39 | + root.walkRules((rule) => { |
| 40 | + if (!isRootRule(rule)) { |
| 41 | + return |
| 42 | + } |
| 43 | + |
| 44 | + rule.each((node) => { |
| 45 | + if ( |
| 46 | + node.type === 'decl' |
| 47 | + && MARGIN_PATTERN.test(node.prop) |
| 48 | + && !node.value.trim().split(/\s+/).every(value => NEUTRAL_VALUES.has(value.toLowerCase())) |
| 49 | + ) { |
| 50 | + report({ |
| 51 | + ruleName, |
| 52 | + result, |
| 53 | + node, |
| 54 | + message: messages.rejected |
| 55 | + }) |
| 56 | + } |
| 57 | + }) |
| 58 | + }) |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +ruleFunction.ruleName = ruleName |
| 63 | +ruleFunction.messages = messages |
| 64 | + |
| 65 | +export default createPlugin(ruleName, ruleFunction) |
0 commit comments