All files / src createGenerator.js

97.2% Statements 104/107
71.93% Branches 41/57
100% Functions 41/41
96.91% Lines 94/97
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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301                            1x       6x       3x         3x   3x             3x 3x 3x   3x   3x   3x 3x   3x         12x   3x     6x       3x       6x             12x 12x   3x 6x 6x 12x 6x 12x       12x     6x   6x 21x   18x           18x       18x       6x           12x 12x   3x 6x 6x 12x 6x 12x       12x     6x 6x 6x   6x                     6x                       48x 15x   15x     3x     12x                   15x 18x 9x   9x 9x 9x   9x 9x                                     15x                   48x 30x   15x 6x     3x   9x         15x 18x 9x 15x     9x 9x 9x 12x     9x 9x                             15x       60x 60x   21x 42x 18x         21x   18x 9x 6x 6x   6x 6x             3x                           18x   21x    
import {
  isPseudoClass,
  isPseudoElement,
  isMediaQuery,
  generateCSSClasses,
  generateCSSMediaQueryFromNode,
  getModuleName,
  getVariantsFromAST,
  stringifyCSSRule,
} from '@elodin/utils'
import { isUnitlessProperty, hyphenateProperty } from 'css-in-js-utils'
 
import { baseReset, rootReset } from './getReset'
 
const defaultConfig = {
  devMode: false,
  rootNode: 'body',
  dynamicImport: false,
  generateResetClassName: type => '_elo_' + type,
}
 
export default function createGenerator(customConfig = {}) {
  const config = {
    ...defaultConfig,
    ...customConfig,
  }
 
  const { adapter, generateResetClassName, rootNode } = config
 
  Iif (!adapter) {
    throw new Error(
      'An adapter needs to passed in order to generate code. See @elodin/generator-css-in-js/lib/adapters for more information.'
    )
  }
 
  function generate(ast, fileName) {
    const css = generateCSS(ast, config)
    const js = generateJS(ast, config, adapter)
    const root = generateRoot(ast, config)
 
    return { [fileName + '.js']: root, ...css, ...js }
  }
  generate.filePattern = ['*.elo.js', '*.elo.css']
 
  generate.baseReset = baseReset(generateResetClassName)
  generate.rootReset = rootReset(rootNode)
 
  return generate
}
 
function generateRoot(ast) {
  // TODO: include fragments
  const styles = ast.body.filter(node => node.type === 'Style')
 
  const imports = styles
    .map(
      module =>
        'import { ' + module.name + " } from './" + module.name + ".elo.js'"
    )
    .join('\n')
 
  return (
    imports +
    '\n\n' +
    'export {\n  ' +
    styles.map(module => module.name).join(',\n  ') +
    '\n}'
  )
}
 
function generateCSS(ast, { devMode }) {
  // TODO: include fragments
  const styles = ast.body.filter(node => node.type === 'Style')
  const variants = ast.body.filter(node => node.type === 'Variant')
 
  return styles.reduce((files, module) => {
    const usedVariants = getVariantsFromAST(module)
    const variantMap = variants.reduce((flatVariants, variant) => {
      if (usedVariants[variant.name]) {
        flatVariants[variant.name] = variant.body.map(
          variation => variation.value
        )
      }
 
      return flatVariants
    }, {})
 
    const classes = generateCSSClasses(module.body, variantMap, devMode)
 
    files[module.name + '.elo.css'] = classes
      .filter(selector => selector.declarations.length > 0)
      .map(selector => {
        const css = stringifyCSSRule(
          selector.declarations,
          getModuleName(module, devMode) + selector.modifier + selector.pseudo,
          selector.media ? '  ' : ''
        )
 
        Iif (selector.media) {
          return '@media ' + selector.media + ' {\n' + css + '\n}'
        }
 
        return css
      })
      .join('\n\n')
 
    return files
  }, {})
}
 
function generateJS(ast, { devMode, dynamicImport }, adapter) {
  // TODO: include fragments
  const styles = ast.body.filter(node => node.type === 'Style')
  const variants = ast.body.filter(node => node.type === 'Variant')
 
  return styles.reduce((files, module) => {
    const usedVariants = getVariantsFromAST(module)
    const variantMap = variants.reduce((flatVariants, variant) => {
      if (usedVariants[variant.name]) {
        flatVariants[variant.name] = variant.body.map(
          variation => variation.value
        )
      }
 
      return flatVariants
    }, {})
 
    const style = generateStyle(module.body)
    const classNameMap = generateClassNameMap(module.body, variantMap, devMode)
    const variantStyleMap = generateVariantStyleMap(module.body, variants)
 
    files[module.name + '.elo.js'] = adapter({
      style,
      variantStyleMap,
      moduleName: module.name,
      dynamicImport,
      classNameMap,
      resetClassName: '_elo_' + module.format,
      className: getModuleName(module, devMode),
      variants: variantMap,
    })
 
    return files
  }, {})
}
 
function generateClassNameMap(
  nodes,
  variantMap,
  devMode,
  classes = {},
  variations = {},
  modifier = []
) {
  const nesting = nodes.filter(node => node.type !== 'Declaration')
  const variantOrder = Object.keys(variantMap)
  // ensure the variant modifier order is always deterministic
  classes[
    modifier
      .sort((a, b) =>
        variantOrder.indexOf(a[0]) > variantOrder.indexOf(b[0]) ? 1 : -1
      )
      .map(([name, value]) =>
        devMode
          ? '__' + name + '-' + value
          : '_' +
            variantOrder.indexOf(name) +
            '-' +
            variantMap[name].indexOf(value)
      )
      .join('')
  ] = variations
 
  nesting.forEach(nest => {
    if (nest.property.type === 'Identifier') {
      const variant = variantMap[nest.property.value]
 
      Eif (variant) {
        Eif (nest.value.type === 'Identifier') {
          const variation = variant.indexOf(nest.value.value) !== -1
 
          Eif (variation) {
            generateClassNameMap(
              nest.body,
              variantMap,
              devMode,
              classes,
              {
                ...variations,
                [nest.property.value]: nest.value.value,
              },
              [...modifier, [nest.property.value, nest.value.value]]
            )
          }
        }
      } else {
        // TODO: throw
      }
    }
  })
 
  return classes
}
 
function generateVariantStyleMap(
  nodes,
  variants,
  styles = {},
  style = [],
  modifier = []
) {
  const nesting = nodes.filter(node => node.type !== 'Declaration')
  const variantOrder = variants.map(variant => variant.name)
 
  if (style.length > 0) {
    styles[
      modifier
        .sort((a, b) =>
          variantOrder.indexOf(a[0]) > variantOrder.indexOf(b[0]) ? 1 : -1
        )
        .map(([name, value]) => '__' + name + '-' + value)
        .join('')
    ] = style
  }
 
  nesting.forEach(nest => {
    if (nest.property.type === 'Identifier') {
      const variant = variants.find(
        variant => variant.name === nest.property.value
      )
 
      Eif (variant) {
        Eif (nest.value.type === 'Identifier') {
          const variation = variant.body.find(
            variant => variant.value === nest.value.value
          )
 
          Eif (variation) {
            generateVariantStyleMap(
              nest.body,
              variants,
              styles,
              generateStyle(nest.body),
              [...modifier, [variant.name, variation.value]]
            )
          }
        }
      } else {
        // TODO: throw
      }
    }
  })
 
  return styles
}
 
function generateStyle(nodes) {
  const base = nodes.filter(node => node.type === 'Declaration')
  const nestings = nodes.filter(node => node.type !== 'Declaration')
 
  const declarations = base
    .filter(decl => decl.dynamic)
    .map(declaration => ({
      property: declaration.property,
      value: declaration.value.value,
    }))
 
  const nests = nestings
    .map(nest => {
      if (nest.property.type === 'Variable' && nest.property.environment) {
        if (nest.boolean) {
          const pseudoClass = isPseudoClass(nest.property.value)
          const pseudoElement = isPseudoElement(nest.property.value)
 
          Eif (pseudoClass || pseudoElement) {
            return {
              property: (pseudoElement ? '::' : ':') + nest.property.value,
              value: generateStyle(nest.body),
            }
          }
        }
 
        Iif (isMediaQuery(nest.property.value)) {
          return {
            property:
              '@media ' +
              generateCSSMediaQueryFromNode(
                nest.value.value,
                nest.property.value,
                nest.operator
              ),
            value: generateStyle(nest.body),
          }
        }
      }
    })
    .filter(nesting => nesting && nesting.value.length > 0)
 
  return [...declarations, ...nests]
}