1- import generate from '@babel/generator' ;
2- import template from '@babel/template' ;
31import * as t from '@babel/types' ;
4- import { unique } from '@compiled/utils' ;
52
63import type { Metadata } from '../types' ;
74
@@ -12,6 +9,10 @@ import { hoistSheet } from './hoist-sheet';
129import { transformCssItems } from './transform-css-items' ;
1310import type { CSSOutput } from './types' ;
1411
12+ const WHITESPACE_TEXT_NODES = {
13+ leading : t . jsxText ( '\n ' ) ,
14+ trailing : t . jsxText ( '\n' ) ,
15+ } ;
1516/**
1617 * Will return a generated AST for a Compiled Component.
1718 * This is primarily used for CSS prop and ClassNames apis.
@@ -21,24 +22,37 @@ import type { CSSOutput } from './types';
2122 * @param meta {Metadata} Useful metadata that can be used during the transformation
2223 */
2324export const compiledTemplate = ( node : t . Expression , sheets : string [ ] , meta : Metadata ) : t . Node => {
24- const nonceAttribute = meta . state . opts . nonce ? `nonce={${ meta . state . opts . nonce } }` : '' ;
25-
25+ const nonce = meta . state . opts . nonce ;
26+ const nonceAttribute = nonce
27+ ? t . jsxAttribute ( t . jsxIdentifier ( 'nonce' ) , t . jsxExpressionContainer ( t . identifier ( nonce ) ) )
28+ : null ;
2629 const [ keyAttribute ] = getJSXAttribute ( node , 'key' ) ;
2730
28- return template (
29- `
30- <CC ${ keyAttribute ? generate ( keyAttribute ) . code : '' } >
31- <CS ${ nonceAttribute } >{%%cssNode%%}</CS>
32- {%%jsxNode%%}
33- </CC>
34- ` ,
35- {
36- plugins : [ 'jsx' ] ,
37- }
38- ) ( {
39- jsxNode : node ,
40- cssNode : t . arrayExpression ( unique ( sheets ) . map ( ( sheet : string ) => hoistSheet ( sheet , meta ) ) ) ,
41- } ) as t . Node ;
31+ return t . jsxElement (
32+ t . jsxOpeningElement (
33+ t . jsxIdentifier ( 'CC' ) ,
34+ keyAttribute ? [ t . jsxAttribute ( t . jsxIdentifier ( 'key' ) , keyAttribute . value ) ] : [ ] ,
35+ false
36+ ) ,
37+ t . jsxClosingElement ( t . jsxIdentifier ( 'CC' ) ) ,
38+ [
39+ WHITESPACE_TEXT_NODES . leading ,
40+ t . jsxElement (
41+ t . jsxOpeningElement ( t . jsxIdentifier ( 'CS' ) , nonceAttribute ? [ nonceAttribute ] : [ ] , false ) ,
42+ t . jsxClosingElement ( t . jsxIdentifier ( 'CS' ) ) ,
43+ [
44+ t . jsxExpressionContainer (
45+ t . arrayExpression (
46+ Array . from ( new Set ( sheets ) ) . map ( ( sheet : string ) => hoistSheet ( sheet , meta ) )
47+ )
48+ ) ,
49+ ]
50+ ) ,
51+ WHITESPACE_TEXT_NODES . leading ,
52+ t . jsxExpressionContainer ( node ) ,
53+ WHITESPACE_TEXT_NODES . trailing ,
54+ ]
55+ ) ;
4256} ;
4357
4458/**
0 commit comments