In as few characters as possible this page demonstrates how to wire the Pretty Diff application to third party HTML in a browser. Please not this guide is for directly using Pretty Diff in a browser and not through a Node.js application.
Attaching the application
First we need to inject the necessary code into the page. This can be done the traditional way with an HTML script tag or as an ECMAScript module import. Below are examples of both:
- HTML script tag:
<script src="prettydiff/js/browser.js" type="application/javascript"></script>
- A module import in your JavaScript code:
import "prettydiff/js/browser.js";
I have packaged everything into a single file. This contains the parser, all the Pretty Diff application, and the generated option list with default values.
Configuring and executing the application
Configuring the application is as simple as creating the options object and passing that object into the application.
let prettydiff = window.prettydiff;
prettydiff.options.source = "var a=1;";
prettydiff.options.wrap = 80;
myResult = prettydiff();
Please note that while that does work it is risky. I always recommend building options off the default options object for more predictable options. See the larger following example.
Demo
Here is an interactive demo with a demo wiring harness.
import "../js/browser.js";
(function () {
// first the dom interaction is defined with a target and handler
let button = document.getElementsByTagName("button")[0],
execute = function () {
// inside the application we gather the application
let prettydiff = window.prettydiff,
// this provides all options set to their default values for safety
options = prettydiff.options,
output = "";
// here is where we overwrite the default options with custom values
options.api = "dom";
options.language = "auto";
options.lexer = "script";
options.mode = "beautify";
options.source = document.getElementById("input").value;
// this where the application executes and the string output is assigned
output = prettydiff();
// output the generated string into the dom
document.getElementById("output").value = output;
};
// this uses a click event on a button
// for more excitement you can assign the handler to the input textarea's keyup event
button.onclick = execute;
}());