All files / src/adapters react-fela.js

100% Statements 9/9
90% Branches 18/20
100% Functions 3/3
100% Lines 9/9
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  8x   8x 2x         6x                       2x 2x   2x         2x                           2x                                                                                      
function stringifyDeclaration(declaration) {
  const prop = '"' + declaration.property + '":'
 
  if (typeof declaration.value === 'object') {
    return (
      prop + '{' + declaration.value.map(stringifyDeclaration).join(',\n') + '}'
    )
  }
 
  return prop + 'props.' + declaration.value
}
 
export default function reactFelaAdapter({
  style,
  variantStyleMap,
  moduleName,
  classNameMap,
  resetClassName,
  className,
  dynamicImport,
}) {
  const hasVariations = Object.keys(classNameMap).length > 1
  const hasDynamicVariations = Object.keys(variantStyleMap).length > 0
 
  const imports = [
    hasVariations ? 'getClassNameFromVariantMap' : undefined,
    hasDynamicVariations ? 'getDynamicStyleFromVariantMap' : undefined,
  ].filter(Boolean)
 
  return (
    (!dynamicImport ? "import './" + moduleName + ".elo.css'\n" : '') +
    (imports.length > 0
      ? 'import { ' + imports.join(', ') + " } from '@elodin/runtime'\n"
      : '') +
    "import { createComponent } from 'react-fela'\n\n" +
    (hasVariations
      ? 'const variantMap = ' + JSON.stringify(classNameMap, null, 2) + '\n\n'
      : '') +
    (hasDynamicVariations
      ? 'const variantStyleMap = {\n' +
        Object.keys(variantStyleMap)
          .map(
            modifier =>
              "'" +
              modifier +
              "'" +
              ': props => ({\n  ' +
              variantStyleMap[modifier]
                .map(stringifyDeclaration)
                .join(',\n  ') +
              '\n})'
          )
          .join(',\n') +
        '\n}' +
        '\n\n'
      : '') +
    'function ' +
    moduleName +
    'Style' +
    '(props  = {})' +
    ' {\n  ' +
    (dynamicImport ? "import('./" + moduleName + ".elo.css')\n" : '') +
    'return {\n    ' +
    '_className: ' +
    (hasVariations
      ? "'" +
        resetClassName +
        " ' + " +
        "getClassNameFromVariantMap('" +
        className +
        "', variantMap, props)"
      : "'" + resetClassName + ' ' + className + "'") +
    ',\n    ' +
    style.map(stringifyDeclaration).join(',\n    ') +
    (hasDynamicVariations
      ? ',\n    ...getDynamicStyleFromVariantMap(variantStyleMap, props)'
      : '') +
    '\n  }\n}\n\n' +
    'export const ' +
    moduleName +
    ' = createComponent(' +
    moduleName +
    'Style' +
    ')'
  )
}