All files / src createGenerator.js

96.84% Statements 92/95
70.37% Branches 38/54
100% Functions 41/41
96.43% Lines 81/84
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                                  2x           2x           2x 2x 2x 2x   2x           8x   2x     4x       2x       4x             8x 8x   2x 4x   4x 14x   12x           12x       12x       4x           8x 8x   2x 4x 4x 4x   4x                 8x 16x     8x       4x                     32x 20x     10x     2x   8x       10x 12x 6x 10x     6x 6x 6x 8x     6x 6x                                   10x                   32x 20x   10x 4x     2x   6x         10x 12x 6x 10x     6x 6x 6x 8x     6x 6x                             10x       40x 40x   14x 28x 12x         14x   12x 6x 4x 4x   4x 4x             2x                           12x   14x    
import {
  isPseudoClass,
  isPseudoElement,
  isMediaQuery,
  generateCSSClasses,
  generateCSSMediaQueryFromNode,
  getModuleName,
  stringifyCSSRule,
} from '@elodin/utils'
import { isUnitlessProperty, hyphenateProperty } from 'css-in-js-utils'
 
export default function createGenerator({
  adapter,
  devMode = false,
  rootNode = 'body',
  dynamicImport = false,
} = {}) {
  const config = {
    devMode,
    rootNode,
    dynamicImport,
  }
 
  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.'
    )
  }
 
  return 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 }
  }
}
 
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 classes = generateCSSClasses(module.body, variants)
 
    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 style = generateStyle(module.body)
    const classNameMap = generateClassNameMap(module.body, variants)
    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: variants.reduce((flatVariants, variant) => {
        flatVariants[variant.name] = variant.body.map(
          variation => variation.value
        )
 
        return flatVariants
      }, {}),
    })
 
    return files
  }, {})
}
 
function generateClassNameMap(
  nodes,
  variants,
  classes = {},
  variations = {},
  modifier = []
) {
  const nesting = nodes.filter(node => node.type !== 'Declaration')
  const variantOrder = variants.map(variant => variant.name)
 
  // 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]) => '__' + name + '-' + value)
      .join('')
  ] = variations
 
  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) {
            generateClassNameMap(
              nest.body,
              variants,
              classes,
              {
                ...variations,
                [variant.name]: variation.value,
              },
              [...modifier, [variant.name, variation.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]
}