rtfpessoa / diff2html

Pretty diff to html javascript library (diff2html)
https://diff2html.xyz
MIT License
2.79k stars 272 forks source link

Documentation Improvement? #532

Open MarketingPip opened 1 month ago

MarketingPip commented 1 month ago

Hello!

It would be great to get some more examples as ES6 import.

I have tried playing with this library all day struggling to figure out what I am doing wrong lol.

The code below should produce a highlighted string. But for some reason - highlighting is not picking up. Plus I am sure there is a pretty way to do this.

ps; forced to use this for tests / browser tests from ESM.sh as CDN - tho the default / main script does not catch proper requirements when loaded as ES6 Module..

Relevant Code:

import   Diff2HtmlUI from "https://esm.sh/diff2html/lib/ui/js/diff2html-ui-slim.js";

import * as JsDiff from "https://esm.sh/diff"

function compare(val1, val2) {
  const diff = JsDiff.createPatch('', 
   val1,
  val2,
    'original', 'modified', { options: { context: 5} }
  );
 document.querySelector("#diff").innerHTML = updateDiff(diff);
}

function updateDiff(diff) {
    const configuration = {
        drawFileList: true,
        matching: 'lines',
        outputFormat: 'side-by-side',
        fileListToggle: false,
        fileListStartVisible: false,
        fileContentToggle: false,
        container: document.createElement('div'),
      diff2htmlUi:null,
       highlight: true 
    };

   configuration.diff2htmlUi = new Diff2HtmlUI.Diff2HtmlUI(configuration.container, diff, configuration);

    configuration.diff2htmlUi.draw();

    configuration.diff2htmlUi.highlightCode();

  configuration.diff2htmlUi.highlightCode = configuration.container

    const HTML = getContentByQuerySelector(configuration.container.outerHTML, ".d2h-files-diff");

    // Remove the container element from the DOM
    configuration.container.remove();

    // Clear all keys in the configuration object
    for (let key in configuration) {
        delete configuration[key];
    }
    return HTML
}

function getContentByQuerySelector(element, selector) {
    // Get the HTML content from the element
    var htmlContent = element

    // Create a new DOMParser
    var parser = new DOMParser();

    // Parse the HTML string into a Document
    var doc = parser.parseFromString(htmlContent, "text/html");

    // Use querySelector on the parsed document to get the content with the given selector
    var selectedContent = doc.querySelector(selector);

    // Return the innerHTML of the selected content
    return selectedContent ? selectedContent.innerHTML : null;
}

compare('function example() {\n    return "pizza";\n}' , `function hello(){
console.log("hellos")
}`)
rtfpessoa commented 1 day ago

I think you are missing the actual CSS, check one example here https://github.com/rtfpessoa/diff2html/blob/master/website/templates/pages/demo/demo.ts