JavaScript: mostrare il codice sorgente dei blocchi di codice

JavaScript: mostrare il codice sorgente dei blocchi di codice

In JavaScript possiamo mostrare il codice sorgente dei blocchi di codice con semplicità.

La soluzione consiste nell'aggiungere un link prima di ogni blocco di codice che aprirà una popup con il sorgente originario.


'use strict';

const insertLinks = (className = 'show-source') => {
    const pre = document.querySelectorAll('pre');
    if(pre.length => 0) {
        pre.forEach(element => {
            const html = `<div><a href="#" class="${className}">Show source</a></div>`;
            element.insertAdjacentHTML('beforeBegin', html);
        });
    }
};

const showWindow = ( url = location.href, title = 'Source code', width = 400, height = 400 ) => {
    const left = ( screen.width / 2 ) - ( width / 2 );
    const top = ( screen.height / 2 ) - ( height / 2 );
    return window.open(url, title, `location=1,status=1,scrollbars=1, width=${width},height=${height},top=${top},left=${left}`);
};

const showSource = (className = 'show-source') => {
    document.addEventListener('click', e => {
       e.preventDefault();
       const element = e.target;
       if(element.classList.contains(className)) {
           const code = element.parentNode.nextElementSibling.querySelector('code').innerText;
           const newWindow = showWindow();
           const newDocument = newWindow.document;
           const html = `<pre>${code}</pre>`;

           newDocument.write(html);
           newDocument.close();
       }
    });
};

const init = () => {
    showSource();
    insertLinks();
};

document.addEventListener('DOMContentLoaded', () => {
    init();
});

Demo

JavaScript: show source code

Torna su