All files / src/utils styled.js

100% Statements 22/22
100% Branches 18/18
100% Functions 6/6
100% Lines 20/20
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 55 56 57 58 59 60 61 62 63 64 653x         1784x               3x   100x                       3x   132x               3x 1774x                 3x 1784x   142x 568x 30x 30x     142x     3x 3x 3x 3x 3x  
const isTaggedTemplateLiteral = require('./tagged-template-literal').isTaggedTemplateLiteral
 
/**
 * Check if something is a styled-components import declaration
 */
const isStyledImport = (node) => node.type === 'ImportDeclaration' && node.source.value === 'styled-components'
 
/**
 * Check if something is a styled shorthand call
 * e.g. styled.div``
 *
 * TODO Lint that the tagname exists
 */
const isStyledShorthand = (node, styledVariableName) => (
  // Check that it's an object
  node.tag && node.tag.object
  // Check that the object matches the imported name
  && node.tag.object.name === styledVariableName
  // Check that a property exists, otherwise it's just styled
  // without any call
  && node.tag.property
)
 
/**
 * Check if a node is a styld call
 * e.g. styled(Component)`` or styled('tagname')``
 */
const isStyledCall = (node, styledVariableName) => (
  // Check that it's a function call
  node.tag && node.tag.callee
  // And that the function name matches the imported name
  && node.tag.callee.name === styledVariableName
)
 
/**
 * Check if something is a styled component call
 */
const isStyled = (node, styledVariableName) => (
  isTaggedTemplateLiteral(node) &&
  (isStyledCall(node, styledVariableName) || isStyledShorthand(node, styledVariableName))
)
 
/**
 * Check if something is a call to one of our helper methods
 *
 * Returns either a string (the name of the helper) or false
 */
const isHelper = (node, importedNames) => {
  if (!isTaggedTemplateLiteral(node)) return false
  let helper
  Object.keys(importedNames).forEach(name => {
    if (importedNames[name] === node.tag.name) {
      helper = name
      return
    }
  })
  return helper || false
}
 
exports.isStyledImport = isStyledImport
exports.isStyledShorthand = isStyledShorthand
exports.isStyledCall = isStyledCall
exports.isStyled = isStyled
exports.isHelper = isHelper