Javascript : insérer des sections

Petite moulinette javascript pour insérer des sections à chaque niveau de titraille d'un document web.

L'élément <section> a été ajouté en HTML5 pour décrire des… sections de documents, en lieu et place des éléments plus génériques <div>. Exemple d'un document simple :

<h1>Titre du document</h1>
<h2>Titre 1</h2>
<h3>Titre 1.1</h3>
<h3>Titre 1.2</h3>
<h2>Titre 2</h2>
<h3>Titre 1.1</h3>
<h3>Titre 1.2</h3>

qui peut se transformer en :

<h1>Titre du document</h1>
<section>
    <h2>Titre 1</h2>
    <section>
        <h3>Titre 1.1</h3>
    </section>
    <section>
        <h3>Titre 1.2</h3>
    </section>
</section>
<section>
    <h2>Titre 2</h2>
    <section>
        <h3>Titre 1.1</h3>
    </section>
    <section>
        <h3>Titre 1.2</h3>
    </section>
</section>

Il y a pas mal d'avantages à utiliser des sections mais elles allourdissent la rédaction du document, surtout si on utilise du markdown comme source. Voici un petit script pour les insérer dans un document web existant :

/**
 * @param {HTMLElement} parent 
 * @param {number} [startLevel=2] Start Heading level
 * @param {number} [endLevel=6] End heading level
 */
export const insertSections = (parent, startLevel = 2, endLevel = 6) => {
    if (startLevel < 1 || startLevel > 6 || endLevel < 1 || endLevel > 6 
            || startLevel > endLevel) {
        console.warn(`Wrong level values: ${startLevel} to ${endLevel}`);
        return;
    }
    const reHeading = /^h\d$/i;
    
    const queryArray = [];
    for (let i = startLevel; i <= endLevel; i++ ) {
        queryArray.push(`:scope h${i}`);
    }
    
    /**@type {HTMLElement}*/
    let previousSection = null;
    /**@type {number}*/
    let previousLevel = startLevel;
    
    parent.querySelectorAll(queryArray.join(',')).forEach(heading => {
        const section = globalThis.document.createElement('section');
        while (heading.nextElementSibling) {
            if (reHeading.test(heading.nextElementSibling.nodeName)) {
                break;
            }
            section.append(heading.nextElementSibling);
        }
        const current = Number(heading.nodeName.charAt(1));
        
        if (current === previousLevel) {
            if (previousSection) {
                previousSection.insertAdjacentElement('afterend', section);
            } else {
                heading.parentElement.insertBefore(section, heading);
            }
        } else if (current > previousLevel) {
            if (previousSection) {
                previousSection.append(section);
            } else {
                heading.parentElement.insertBefore(section, heading);
            }
        } else if (current < previousLevel) {
            let target = previousSection;
            // Remonter les parents
            for (let i = 0, n = previousLevel - current; i <= n; i++) {
                target = target.parentElement;
            }
            if (target === parent) {
                heading.parentElement.insertBefore(section, heading);
            } else {
                target.append(section);
            }
        }
        section.prepend(heading);
        previousLevel = current;
        previousSection = section;
    });
};