| 1 |
import { stringLiteral } from "../../builders/generated"; |
| 2 |
import type * as t from "../.."; |
| 3 |
import { inherits } from "../.."; |
| 4 |
|
| 5 |
export default function cleanJSXElementLiteralChild( |
| 6 |
child: t.JSXText, |
| 7 |
args: Array<t.Node>, |
| 8 |
) { |
| 9 |
const lines = child.value.split(/\r\n|\n|\r/); |
| 10 |
|
| 11 |
let lastNonEmptyLine = 0; |
| 12 |
|
| 13 |
for (let i = 0; i < lines.length; i++) { |
| 14 |
if (lines[i].match(/[^ \t]/)) { |
| 15 |
lastNonEmptyLine = i; |
| 16 |
} |
| 17 |
} |
| 18 |
|
| 19 |
let str = ""; |
| 20 |
|
| 21 |
for (let i = 0; i < lines.length; i++) { |
| 22 |
const line = lines[i]; |
| 23 |
|
| 24 |
const isFirstLine = i === 0; |
| 25 |
const isLastLine = i === lines.length - 1; |
| 26 |
const isLastNonEmptyLine = i === lastNonEmptyLine; |
| 27 |
|
| 28 |
// replace rendered whitespace tabs with spaces |
| 29 |
let trimmedLine = line.replace(/\t/g, " "); |
| 30 |
|
| 31 |
// trim whitespace touching a newline |
| 32 |
if (!isFirstLine) { |
| 33 |
trimmedLine = trimmedLine.replace(/^[ ]+/, ""); |
| 34 |
} |
| 35 |
|
| 36 |
// trim whitespace touching an endline |
| 37 |
if (!isLastLine) { |
| 38 |
trimmedLine = trimmedLine.replace(/[ ]+$/, ""); |
| 39 |
} |
| 40 |
|
| 41 |
if (trimmedLine) { |
| 42 |
if (!isLastNonEmptyLine) { |
| 43 |
trimmedLine += " "; |
| 44 |
} |
| 45 |
|
| 46 |
str += trimmedLine; |
| 47 |
} |
| 48 |
} |
| 49 |
|
| 50 |
if (str) args.push(inherits(stringLiteral(str), child)); |
| 51 |
} |