export const truncate = (str, maxChars, maxLines) => {
    var _a;
    if (!str || maxChars < 0)
        return "";
    const parser = new DOMParser();
    const doc = parser.parseFromString(str, "text/html");
    let charCount = 0;
    let lineCount = 0;
    const walker = doc.createTreeWalker(doc.body, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT);
    const removeAfter = (node) => {
        let current = node;
        while (current && current !== doc.body) {
            const parent = current.parentNode;
            if (!parent)
                break;
            while (current.nextSibling) {
                parent.removeChild(current.nextSibling);
            }
            current = parent;
        }
    };
    while (walker.nextNode()) {
        const node = walker.currentNode;
        if (node.nodeType === Node.TEXT_NODE) {
            const text = node.textContent || "";
            if (charCount + text.length > maxChars) {
                node.textContent = text.slice(0, maxChars - charCount) + "...";
                removeAfter(node);
                break;
            }
            charCount += text.length;
        }
        else {
            const tagName = node.nodeName.toLowerCase();
            if (tagName === "br" || /^h[1-6]$/.test(tagName) || tagName === "p" || tagName === "blockquote") {
                lineCount++;
                if (lineCount >= maxLines) {
                    const ellipsis = doc.createTextNode("...");
                    (_a = node.parentNode) === null || _a === void 0 ? void 0 : _a.insertBefore(ellipsis, node);
                    removeAfter(ellipsis);
                    break;
                }
            }
        }
    }
    return doc.body.innerHTML;
};
