alinea
Version:
[](https://npmjs.org/package/alinea) [](https://packagephobia.com/result?p=alinea)
77 lines (75 loc) • 1.85 kB
JavaScript
import "../../chunks/chunk-U5RRZUYZ.js";
// src/core/util/CodeGen.ts
function code(input, ...inserts) {
if (!input)
return new Code([], []);
if (typeof input === "string")
return new Code([input], []);
if (input instanceof Code)
return input;
return new Code(input, inserts);
}
var Code = class {
constructor(strings, inserts) {
this.strings = strings;
this.inserts = inserts;
}
valueOf() {
return this.toString();
}
push(...strings) {
const inner = [this.toString(), ...strings.map((_) => _.toString())].join(
"\n"
);
this.strings = [inner];
this.inserts = [];
}
toString() {
let full = "";
for (const [index, string] of this.strings.entries()) {
full += string;
if (index in this.inserts) {
const insert = String(this.inserts[index]);
if (!insert.includes("\n")) {
full += insert;
continue;
}
let lineIndent = 0;
for (let i = full.length - 1; i >= 0; i--) {
const char = full[i];
if (char === " ")
lineIndent++;
else if (char === "\n")
break;
else
lineIndent = 0;
}
full += lineIndent > 0 ? indent(insert, lineIndent, true) : insert;
}
}
let baseIndent = 0;
for (const char of full) {
if (char === "\n")
baseIndent = 0;
else if (char === " ")
baseIndent++;
else
break;
}
return indent(full, -baseIndent);
}
};
function indent(input, amount, skipStart = false) {
const lines = input.split("\n");
return lines.map((line, index) => {
if (skipStart && index === 0)
return line;
if (amount >= 0)
return " ".repeat(amount) + line;
return line.slice(-amount);
}).join("\n").trim();
}
export {
Code,
code
};