@@ -65,9 +65,9 @@ const getTag = (t, path) => {
6565 */
6666const getChildren = ( t , paths ) =>
6767 paths
68- . map ( ( path , index ) => {
68+ . map ( path => {
6969 if ( path . isJSXText ( ) ) {
70- return transformJSXText ( t , path , index === 0 ? - 1 : index === paths . length - 1 ? 1 : 0 )
70+ return transformJSXText ( t , path )
7171 }
7272 if ( path . isJSXExpressionContainer ( ) ) {
7373 return transformJSXExpressionContainer ( t , path )
@@ -374,24 +374,56 @@ const transformJSXMemberExpression = (t, path) => {
374374 return t . memberExpression ( transformedObject , transformedProperty )
375375}
376376
377- /**
378- * Trim text from JSX expressions depending on position
379- * @param string string
380- * @param position -1 for left, 0 for middle and 1 for right
381- * @returns string
382- */
383- const trimText = ( string , position ) => ( position === 0 ? string : string . replace ( position === - 1 ? / ^ \s * / : / \s * $ / , '' ) )
384-
385377/**
386378 * Transform JSXText to StringLiteral
387379 * @param t
388380 * @param path JSXText
389- * @param position -1 for left, 0 for middle and 1 for right
390381 * @returns StringLiteral
391382 */
392- const transformJSXText = ( t , path , position ) => {
393- const string = trimText ( path . get ( 'value' ) . node , position )
394- return string ? t . stringLiteral ( string ) : null
383+ const transformJSXText = ( t , path ) => {
384+ const node = path . node
385+ const lines = node . value . split ( / \r \n | \n | \r / )
386+
387+ let lastNonEmptyLine = 0
388+
389+ for ( let i = 0 ; i < lines . length ; i ++ ) {
390+ if ( lines [ i ] . match ( / [ ^ \t ] / ) ) {
391+ lastNonEmptyLine = i
392+ }
393+ }
394+
395+ let str = ''
396+
397+ for ( let i = 0 ; i < lines . length ; i ++ ) {
398+ const line = lines [ i ]
399+
400+ const isFirstLine = i === 0
401+ const isLastLine = i === lines . length - 1
402+ const isLastNonEmptyLine = i === lastNonEmptyLine
403+
404+ // replace rendered whitespace tabs with spaces
405+ let trimmedLine = line . replace ( / \t / g, ' ' )
406+
407+ // trim whitespace touching a newline
408+ if ( ! isFirstLine ) {
409+ trimmedLine = trimmedLine . replace ( / ^ [ ] + / , '' )
410+ }
411+
412+ // trim whitespace touching an endline
413+ if ( ! isLastLine ) {
414+ trimmedLine = trimmedLine . replace ( / [ ] + $ / , '' )
415+ }
416+
417+ if ( trimmedLine ) {
418+ if ( ! isLastNonEmptyLine ) {
419+ trimmedLine += ' '
420+ }
421+
422+ str += trimmedLine
423+ }
424+ }
425+
426+ return str !== '' ? t . stringLiteral ( str ) : null
395427}
396428
397429/**
0 commit comments