@@ -69,7 +69,7 @@ const getVisitor = ({ $program, usedCompilers }) => ({
6969
7070 // 2. reassign this unique identifier or local dynamic layer to a constant LOCAL_NAME
7171 // in the scope of current function
72- $function . get ( 'body' ) . unshiftContainer ( 'body' , buildConst ( {
72+ insertLocalCss ( $function , $this , buildConst ( {
7373 variable : t . identifier ( LOCAL_NAME ) ,
7474 value : localValue
7575 } ) )
@@ -105,6 +105,36 @@ function insertAfterImports ($program, expressionStatement) {
105105 }
106106}
107107
108+ function insertLocalCss ( $function , $template , statement ) {
109+ const $body = $function . get ( 'body' )
110+ if ( ! $body . isBlockStatement ( ) ) {
111+ $body . replaceWith ( t . blockStatement ( [
112+ t . returnStatement ( $body . node )
113+ ] ) )
114+ }
115+
116+ const $statement = $template . getStatementParent ( )
117+ const $functionBody = $function . get ( 'body' )
118+
119+ if ( $statement ?. parentPath === $functionBody ) {
120+ // Local style templates usually live after the JSX return. Execute the
121+ // generated layer before that return, but after user setup code/hooks.
122+ const $target = findPreviousReturn ( $statement ) || $statement
123+ $target . insertBefore ( statement )
124+ return
125+ }
126+
127+ $functionBody . unshiftContainer ( 'body' , statement )
128+ }
129+
130+ function findPreviousReturn ( $statement ) {
131+ let $current = $statement . getPrevSibling ( )
132+ while ( $current ?. node ) {
133+ if ( $current . isReturnStatement ( ) ) return $current
134+ $current = $current . getPrevSibling ( )
135+ }
136+ }
137+
108138function shouldProcess ( $template , usedCompilers ) {
109139 if ( ! $template . get ( 'tag' ) . isIdentifier ( ) ) return
110140 if ( ! usedCompilers . has ( $template . node . tag . name ) ) return
0 commit comments