// ============================================================================ // Stylescape | Code Block Formatter // ============================================================================ // Normalizes the indentation of demo-page code snippets. // // The Jinja→HTML pipeline bakes template-source indentation into // `.ss-c-preview__code` snippets (`{{ code_snippet | trim | escape }}` only // trims the outer edges), so rendered code blocks show jagged, arbitrary // leading whitespace. This utility re-formats them client-side: // // - Markup snippets (first char `<`) are re-indented from scratch with a // tiny depth-based pretty printer (4-space indent, text collapsed). // - Other snippets are dedented by their longest common indent. // // ============================================================================ /** Elements that never take a closing tag — they don't change depth. */ const VOID_ELEMENTS = new Set([ "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr", ]); const INDENT = " "; export class CodeBlockFormatter { /** * Format every code block matched by `selector`. * Defaults to the preview panel's `
` blocks.
     */
    public static formatAll(
        selector: string = ".ss-c-preview__code pre code",
    ): void {
        document.querySelectorAll(selector).forEach((block) => {
            const raw = block.textContent ?? "";
            const formatted = CodeBlockFormatter.format(raw);
            if (formatted !== raw) {
                block.textContent = formatted;
            }
        });
    }

    /** Format a single snippet. */
    public static format(source: string): string {
        const trimmed = source.replace(/^\s*\n/, "").trimEnd();
        if (!trimmed) return trimmed;

        // Snippets containing 
 or