All files / plugins no-scale-colors.js

88% Statements 22/25
60% Branches 6/10
85.71% Functions 6/7
91.67% Lines 22/24

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 553x 3x   3x 3x   4x         3x   3x 4x       4x   4x     4x   4x 4x 3x 3x     3x     3x 3x 3x 2x                             3x 3x  
const stylelint = require('stylelint')
const matchAll = require('string.prototype.matchall')
 
const ruleName = 'primer/no-scale-colors'
const messages = stylelint.utils.ruleMessages(ruleName, {
  rejected: varName =>
    `${varName} is a non-functional scale color and cannot be used without being wrapped in the color-mode-var mixin`
})
 
// Match CSS variable references (e.g var(--color-text-primary))
// eslint-disable-next-line no-useless-escape
const variableReferenceRegex = /var\(([^\),]+)(,.*)?\)/g
 
module.exports = stylelint.createPlugin(ruleName, (enabled, options = {}) => {
  Iif (!enabled) {
    return noop
  }
 
  const {verbose = false} = options
  // eslint-disable-next-line no-console
  const log = verbose ? (...args) => console.warn(...args) : noop
 
  // Keep track of declarations we've already seen
  const seen = new WeakMap()
 
  return (root, result) => {
    root.walkRules(rule => {
      rule.walkDecls(decl => {
        Iif (seen.has(decl)) {
          return
        } else {
          seen.set(decl, true)
        }
 
        for (const [, variableName] of matchAll(decl.value, variableReferenceRegex)) {
          log(`Found variable reference ${variableName}`)
          if (variableName.match(/^--color-(scale|auto)-/)) {
            stylelint.utils.report({
              message: messages.rejected(variableName),
              node: decl,
              result,
              ruleName
            })
          }
        }
      })
    })
  }
})
 
function noop() {}
 
module.exports.ruleName = ruleName
module.exports.messages = messages