File size: 9,968 Bytes
56fda74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
import {
  createEmotionMacro,
  transformers as vanillaTransformers
} from './emotion-macro'
import { createStyledMacro, styledTransformer } from './styled-macro'
import coreMacro, {
  transformers as coreTransformers,
  transformCsslessArrayExpression,
  transformCsslessObjectExpression
} from './core-macro'
import { getStyledOptions, createTransformerMacro } from './utils'

const getCssExport = (reexported, importSource, mapping) => {
  const cssExport = Object.keys(mapping).find(localExportName => {
    const [packageName, exportName] = mapping[localExportName].canonicalImport
    return packageName === '@emotion/react' && exportName === 'css'
  })

  if (!cssExport) {
    throw new Error(
      `You have specified that '${importSource}' re-exports '${reexported}' from '@emotion/react' but it doesn't also re-export 'css' from '@emotion/react', 'css' is necessary for certain optimisations, please re-export it from '${importSource}'`
    )
  }

  return cssExport
}

let webStyledMacro = createStyledMacro({
  importSource: '@emotion/styled/base',
  originalImportSource: '@emotion/styled',
  isWeb: true
})
let nativeStyledMacro = createStyledMacro({
  importSource: '@emotion/native',
  originalImportSource: '@emotion/native',
  isWeb: false
})
let primitivesStyledMacro = createStyledMacro({
  importSource: '@emotion/primitives',
  originalImportSource: '@emotion/primitives',
  isWeb: false
})
let vanillaEmotionMacro = createEmotionMacro('@emotion/css')

let transformersSource = {
  '@emotion/css': vanillaTransformers,
  '@emotion/react': coreTransformers,
  '@emotion/styled': {
    default: [
      styledTransformer,
      { styledBaseImport: ['@emotion/styled/base', 'default'], isWeb: true }
    ]
  },
  '@emotion/primitives': {
    default: [styledTransformer, { isWeb: false }]
  },
  '@emotion/native': {
    default: [styledTransformer, { isWeb: false }]
  }
}

export const macros = {
  core: coreMacro,
  nativeStyled: nativeStyledMacro,
  primitivesStyled: primitivesStyledMacro,
  webStyled: webStyledMacro,
  vanillaEmotion: vanillaEmotionMacro
}

/*
export type BabelPath = any

export type EmotionBabelPluginPass = any
*/

const AUTO_LABEL_VALUES = ['dev-only', 'never', 'always']

export default function (babel, options) {
  if (
    options.autoLabel !== undefined &&
    !AUTO_LABEL_VALUES.includes(options.autoLabel)
  ) {
    throw new Error(
      `The 'autoLabel' option must be undefined, or one of the following: ${AUTO_LABEL_VALUES.map(
        s => `"${s}"`
      ).join(', ')}`
    )
  }

  let t = babel.types
  return {
    name: '@emotion',
    // https://github.com/babel/babel/blob/0c97749e0fe8ad845b902e0b23a24b308b0bf05d/packages/babel-plugin-syntax-jsx/src/index.ts#L9-L18
    manipulateOptions(opts, parserOpts) {
      const { plugins } = parserOpts

      if (
        plugins.some(p => {
          const plugin = Array.isArray(p) ? p[0] : p
          return plugin === 'typescript' || plugin === 'jsx'
        })
      ) {
        return
      }

      plugins.push('jsx')
    },
    visitor: {
      ImportDeclaration(path, state) {
        const macro = state.pluginMacros[path.node.source.value]
        // most of this is from https://github.com/kentcdodds/babel-plugin-macros/blob/main/src/index.js
        if (macro === undefined) {
          return
        }
        if (t.isImportNamespaceSpecifier(path.node.specifiers[0])) {
          return
        }
        const imports = path.node.specifiers.map(s => ({
          localName: s.local.name,
          importedName:
            s.type === 'ImportDefaultSpecifier' ? 'default' : s.imported.name
        }))
        let shouldExit = false
        let hasReferences = false
        const referencePathsByImportName = imports.reduce(
          (byName, { importedName, localName }) => {
            let binding = path.scope.getBinding(localName)
            if (!binding) {
              shouldExit = true
              return byName
            }
            byName[importedName] = binding.referencePaths
            hasReferences =
              hasReferences || Boolean(byName[importedName].length)
            return byName
          },
          {}
        )
        if (!hasReferences || shouldExit) {
          return
        }
        /**
         * Other plugins that run before babel-plugin-macros might use path.replace, where a path is
         * put into its own replacement. Apparently babel does not update the scope after such
         * an operation. As a remedy, the whole scope is traversed again with an empty "Identifier"
         * visitor - this makes the problem go away.
         *
         * See: https://github.com/kentcdodds/import-all.macro/issues/7
         */
        state.file.scope.path.traverse({
          Identifier() {}
        })

        macro({
          path,
          references: referencePathsByImportName,
          state,
          babel,
          isEmotionCall: true,
          isBabelMacrosCall: true
        })
      },
      Program(path, state) {
        let macros = {}
        let jsxReactImports /*: Array<{
          importSource: string,
          export: string,
          cssExport: string
        }> */ = [
          { importSource: '@emotion/react', export: 'jsx', cssExport: 'css' }
        ]
        state.jsxReactImport = jsxReactImports[0]
        Object.keys(state.opts.importMap || {}).forEach(importSource => {
          let value = state.opts.importMap[importSource]
          let transformers = {}
          Object.keys(value).forEach(localExportName => {
            let { canonicalImport, ...options } = value[localExportName]
            let [packageName, exportName] = canonicalImport
            if (packageName === '@emotion/react' && exportName === 'jsx') {
              jsxReactImports.push({
                importSource,
                export: localExportName,
                cssExport: getCssExport('jsx', importSource, value)
              })
              return
            }
            let packageTransformers = transformersSource[packageName]

            if (packageTransformers === undefined) {
              throw new Error(
                `There is no transformer for the export '${exportName}' in '${packageName}'`
              )
            }

            let extraOptions

            if (packageName === '@emotion/react' && exportName === 'Global') {
              // this option is not supposed to be set in importMap
              extraOptions = {
                cssExport: getCssExport('Global', importSource, value)
              }
            } else if (
              packageName === '@emotion/styled' &&
              exportName === 'default'
            ) {
              // this is supposed to override defaultOptions value
              // and let correct value to be set if coming in options
              extraOptions = {
                styledBaseImport: undefined
              }
            }

            let [exportTransformer, defaultOptions] = Array.isArray(
              packageTransformers[exportName]
            )
              ? packageTransformers[exportName]
              : [packageTransformers[exportName]]

            transformers[localExportName] = [
              exportTransformer,
              {
                ...defaultOptions,
                ...extraOptions,
                ...options
              }
            ]
          })
          macros[importSource] = createTransformerMacro(transformers, {
            importSource
          })
        })
        state.pluginMacros = {
          '@emotion/styled': webStyledMacro,
          '@emotion/react': coreMacro,
          '@emotion/primitives': primitivesStyledMacro,
          '@emotion/native': nativeStyledMacro,
          '@emotion/css': vanillaEmotionMacro,
          ...macros
        }

        for (const node of path.node.body) {
          if (t.isImportDeclaration(node)) {
            let jsxReactImport = jsxReactImports.find(
              thing =>
                node.source.value === thing.importSource &&
                node.specifiers.some(
                  x =>
                    t.isImportSpecifier(x) && x.imported.name === thing.export
                )
            )
            if (jsxReactImport) {
              state.jsxReactImport = jsxReactImport
              break
            }
          }
        }

        if (state.opts.cssPropOptimization === false) {
          state.transformCssProp = false
        } else {
          state.transformCssProp = true
        }

        if (state.opts.sourceMap === false) {
          state.emotionSourceMap = false
        } else {
          state.emotionSourceMap = true
        }
      },
      JSXAttribute(path, state) {
        if (path.node.name.name !== 'css' || !state.transformCssProp) {
          return
        }

        if (t.isJSXExpressionContainer(path.node.value)) {
          if (t.isArrayExpression(path.node.value.expression)) {
            transformCsslessArrayExpression({
              state,
              babel,
              path
            })
          } else if (t.isObjectExpression(path.node.value.expression)) {
            transformCsslessObjectExpression({
              state,
              babel,
              path,
              cssImport: state.jsxReactImport
            })
          }
        }
      },
      CallExpression: {
        exit(path /*: BabelPath */, state /*: EmotionBabelPluginPass */) {
          try {
            if (
              path.node.callee &&
              path.node.callee.property &&
              path.node.callee.property.name === 'withComponent'
            ) {
              switch (path.node.arguments.length) {
                case 1:
                case 2: {
                  path.node.arguments[1] = getStyledOptions(t, path, state)
                }
              }
            }
          } catch (e) {
            throw path.buildCodeFrameError(e)
          }
        }
      }
    }
  }
}