Adding a JavaScript-based diff

I’ve been on the hunt lately for some JavaScript based diffing routines.I’ve had a look at a few of them, and the one I’ve settled on is google-diff-match-patch which they use in the Grails wiki! (Thanks Peter Ledbrook for the pointer!)

My particular need was around diffing a fairly complex “tree” structure. These tree structures are actually imported from files that 3rd party releases from time to time and client import them directly into our product (it’s not always easy to see what’s changed between the versions they release – hence the need for a quick “visual diff” solution.

Here’s an example of the one of these control libraries (the Australian ISM) being diffed (notice the token changes I’ve hacked into the version on the right):

GMARC Diff of ISM Versions

What I really like about google-diff-match-patch is that the API is very simple, and comes in a single JS file with no dependencies. In fact, the download has the algo ported to Java, JavaScript, C++, C#, Objective C, Lua and Python. How awesome! So if you need to scale up to some custom backend magic in Java, the same API is there for you.

In my case, I wanted to diff the whole tree in html (since I can generated the tree itself from a nice re-usable Grails taglib). So in the end I took the approach:

  • Generate the “left” tree contents in a hidden textarea
  • Generate the “right” tree contents in a hidden textarea (these two textareas are needed so I have somewhere to hold the unchanged text of the two trees)
  • Display the unchanged left tree on the left (960gs FTW)
  • Display the results of the JavaScript diff function on the right

The library comes with a sample JavaScript “prettyHtml” diff which you can cut and paste and customise. Check out the demo that comes with the lib for a sample.

Loving the new diff feature! If you’re in the market for a diff capability for your app, this one is definitely worth having a look at (and it’s Apache2 so you can happily use it in your commercial app).

Thanks to Neil Fraser for an awesome lib!

3 thoughts on “Adding a JavaScript-based diff

Comments are closed.