keycloak_theme/src/bin/tools/trimIndent.ts

56 lines
2.1 KiB
TypeScript
Raw Normal View History

/**
* 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[] = [];
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
lastStringLineLength = strings[i].split("\n").at(-1)?.length ?? 0;
}
if (args[i]) {
// if the interpolation value has newlines, indent the interpolation values
// using the last known string indent
2023-03-30 21:56:50 +02:00
const chunk = String(args[i]).replace(/([\r?\n])/g, "$1" + " ".repeat(lastStringLineLength));
chunks.push(chunk);
}
}
return chunks.join("");
}
function trimIndentPrivate(removeEmptyLeadingAndTrailingLines: boolean, strings: TemplateStringsArray, ...args: any[]) {
// Remove initial and final newlines
let string = populateTemplate(strings, ...args);
2023-03-30 21:56:50 +02:00
if (removeEmptyLeadingAndTrailingLines) {
string = string.replace(/^[\r\n]/, "").replace(/[^\S\r\n]*[\r\n]$/, "");
}
const dents = string.match(/^([ \t])+/gm)?.map(s => s.length) ?? [];
// 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, "");
return dedented;
}
/**
* Shift all lines left by the *smallest* indentation level,
* and remove initial newline and all trailing spaces.
*/
2023-03-30 21:56:50 +02:00
export default function trimIndent(strings: TemplateStringsArray, ...args: unknown[]) {
return trimIndentPrivate(true, strings, ...args);
}
/**
* Shift all lines left by the *smallest* indentation level,
* and _keep_ initial newline and all trailing spaces.
*/
2023-03-30 21:56:50 +02:00
trimIndent.keepLeadingAndTrailingNewlines = function (strings: TemplateStringsArray, ...args: unknown[]) {
return trimIndentPrivate(false, strings, ...args);
};