2023-03-29 09:54:29 +02:00
|
|
|
/**
|
|
|
|
* Concatenate the string fragments and interpolated values
|
|
|
|
* to get a single string.
|
|
|
|
*/
|
2023-03-30 21:56:50 +02:00
|
|
|
function populateTemplate(strings: TemplateStringsArray, ...args: unknown[]) {
|
2023-03-30 22:17:06 +02:00
|
|
|
const chunks: string[] = [];
|
2023-03-29 09:54:29 +02:00
|
|
|
for (let i = 0; i < strings.length; i++) {
|
|
|
|
let lastStringLineLength = 0;
|
|
|
|
if (strings[i]) {
|
|
|
|
chunks.push(strings[i]);
|
|
|
|
// remember last indent of the string portion
|
2023-05-23 13:15:02 +03:00
|
|
|
lastStringLineLength = strings[i].split("\n").slice(-1)[0]?.length ?? 0;
|
2023-03-29 09:54:29 +02:00
|
|
|
}
|
|
|
|
if (args[i]) {
|
|
|
|
// if the interpolation value has newlines, indent the interpolation values
|
|
|
|
// using the last known string indent
|
2024-05-20 15:48:51 +02:00
|
|
|
const chunk = String(args[i]).replace(
|
|
|
|
/([\r?\n])/g,
|
|
|
|
"$1" + " ".repeat(lastStringLineLength)
|
|
|
|
);
|
2023-03-30 21:56:50 +02:00
|
|
|
chunks.push(chunk);
|
2023-03-29 09:54:29 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return chunks.join("");
|
|
|
|
}
|
|
|
|
|
2023-04-01 22:36:54 +02:00
|
|
|
/**
|
|
|
|
* Shift all lines left by the *smallest* indentation level,
|
|
|
|
* and remove initial newline and all trailing spaces.
|
|
|
|
*/
|
|
|
|
export default function trimIndent(strings: TemplateStringsArray, ...args: any[]) {
|
2023-03-29 09:54:29 +02:00
|
|
|
// Remove initial and final newlines
|
2023-04-01 22:36:54 +02:00
|
|
|
let string = populateTemplate(strings, ...args)
|
|
|
|
.replace(/^[\r\n]/, "")
|
|
|
|
.replace(/\r?\n *$/, "");
|
2023-04-01 22:44:13 +02:00
|
|
|
const dents =
|
|
|
|
string
|
|
|
|
.match(/^([ \t])+/gm)
|
|
|
|
?.filter(s => /^\s+$/.test(s))
|
|
|
|
?.map(s => s.length) ?? [];
|
2023-03-29 09:54:29 +02:00
|
|
|
// No dents? no change required
|
|
|
|
if (!dents || dents.length == 0) return string;
|
|
|
|
const minDent = Math.min(...dents);
|
|
|
|
// The min indentation is 0, no change needed
|
|
|
|
if (!minDent) return string;
|
2023-03-30 21:56:50 +02:00
|
|
|
const re = new RegExp(`^${" ".repeat(minDent)}`, "gm");
|
|
|
|
const dedented = string.replace(re, "");
|
2023-03-29 09:54:29 +02:00
|
|
|
return dedented;
|
|
|
|
}
|