Skip to content

[Feature request] function to generate colorized diff element #638

@mooomooo

Description

@mooomooo

It's easy enough to copy/paste directly from your demo, but I wonder how many people might find it useful to have that basic functionality to display the diff built in to the library directly? Sorry I don't know how node and packages and ts works, but I e.g. I added this to the Diff class in the compiled .js release:

    function showDiff(a, b, mode='diffChars') {
        const diffElement = document.createDocumentFragment();

        const diffCSS = document.createElement('style');
        diffCSS.type = 'text/css';

        const diffStyles = `
           del { text-decoration: none;
                 color: #b30000;
                 background: #fadad7;
           }
           ins { background: #eaf2c2;
                 color: #406619;
                 text-decoration: none;
           }
           .chunk-header {
                 color: #8a008b;
                 text-decoration: none;
           }`;
        if (diffCSS.styleSheet) diffCSS.styleSheet.cssText = diffStyles;
        else diffCSS.appendChild(document.createTextNode(diffStyles));

        diffElement.appendChild(diffCSS);

        const diff = this[mode](a, b);
        for (var i=0; i < diff.length; i++) {
            if (diff[i].added && diff[i + 1] && diff[i + 1].removed) {
                var swap = diff[i];
                diff[i] = diff[i + 1];
                diff[i + 1] = swap;
            }
            var node;
            if (diff[i].removed) {
                node = document.createElement('del');
                node.appendChild(document.createTextNode(diff[i].value));
            } else if (diff[i].added) {
                node = document.createElement('ins');
                node.appendChild(document.createTextNode(diff[i].value));
            } else if (diff[i].chunkHeader) {
                node = document.createElement('span');
                node.setAttribute('class', 'chunk-header');
                node.appendChild(document.createTextNode(diff[i].value));
            } else {
                node = document.createTextNode(diff[i].value);
            }
            diffElement.appendChild(node);
        }
        return diffElement;
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions