diff --git a/README.md b/README.md index 94049b4..a9e3faf 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Diff to Html by [rtfpessoa](https://github.com/rtfpessoa) -Diff to Html generates pretty HTML diffs from git word diff output. +Diff to Html generates pretty HTML diffs from git diff output. ## Features @@ -12,6 +12,8 @@ Diff to Html generates pretty HTML diffs from git word diff output. * GitHub like style +* Code syntax highlight + ## Online Example > Go to [Diff2HTML](http://rtfpessoa.github.io/diff2html/) @@ -24,6 +26,8 @@ Diff to Html generates pretty HTML diffs from git word diff output. * [Bower Package](http://bower.io/search/?q=diff2html) +* [Node CLI](https://www.npmjs.org/package/diff2html-cli) + * Manually download and import `dist/diff2html.min.js` into your page ## How to use @@ -50,11 +54,60 @@ Diff to Html generates pretty HTML diffs from git word diff output. > Check out the `index.html` for a complete example. +## Sintax Hightlight + +> Add the dependencies. +Choose one color scheme, and add the main highlight code. +If your favourite language is not included in the default package also add its javascript highlight file. +jQuery is optional, just using it to help managing the highlight. + +```html + + + + + + + +``` + +> Invoke the highlightjs plugin + +```js +document.addEventListener("DOMContentLoaded", function () { + // parse the diff to json + var diffJson = Diff2Html.getJsonFromDiff(lineDiffExample); + + // collect all the file extensions in the json + var allFileLanguages = diffJson.map(function (line) { + return line.language; + }); + + // remove duplicated languages + var distinctLanguages = allFileLanguages.filter(function (v, i) { + return allFileLanguages.indexOf(v) == i; + }); + + // pass the languages to the highlightjs plugin + hljs.configure({languages: distinctLanguages}); + + // generate and inject the diff HTML into the desired place + document.getElementById("line-by-line").innerHTML = Diff2Html.getPrettyHtmlFromJson(diffJson); + document.getElementById("side-by-side").innerHTML = Diff2Html.getPrettySideBySideHtmlFromJson(diffJson); + + // collect all the code lines and execute the highlight on them + var codeLines = document.getElementsByClassName("d2h-code-line-ctn"); + [].forEach.call(codeLines, function (line) { + hljs.highlightBlock(line); + }); +}); +``` + ## Contributions All the contributions are welcome. -To contribute just send a pull request with your feature,fix,... and it will be reviewed asap. +To contribute just send a pull request with your changes and I will review it asap. ## License diff --git a/bower.json b/bower.json index db4758f..bc920b6 100644 --- a/bower.json +++ b/bower.json @@ -1,7 +1,7 @@ { "name": "diff2html", "version": "0.2.5-1", - "homepage": "https://github.com/rtfpessoa/diff2html", + "homepage": "http://rtfpessoa.github.io/diff2html/", "description": "Fast Diff to colorized HTML", "keywords": [ "git", diff --git a/dist/diff2html.js b/dist/diff2html.js index 99fcc63..2d88923 100644 --- a/dist/diff2html.js +++ b/dist/diff2html.js @@ -1,8 +1,25 @@ // Diff2Html minifier version (automatically generated) -var global = this; +/* + * Hack to allow nodejs require("package/file") in the browser + * How? + * Since every require is used as an object: + * `require("./utils.js").Utils` // (notice the `.Utils`) + * + * We can say that when there is no require method + * we use the global object in which the `Utils` + * object was already injected. + */ + +var $globalHolder = (typeof module !== 'undefined' && module.exports) || + (typeof exports !== 'undefined' && exports) || + (typeof window !== 'undefined' && window) || + (typeof self !== 'undefined' && self) || + (typeof this !== 'undefined' && this) || + Function('return this')(); function require() { - return global; -}/* See LICENSE file for terms of use */ + return $globalHolder; +} +/* See LICENSE file for terms of use */ /* * Text diff implementation. @@ -652,7 +669,7 @@ function require() { * */ -(function (global, undefined) { +(function (ctx, undefined) { function Utils() { } @@ -673,11 +690,13 @@ function require() { return value ? value : ""; }; - if (typeof module !== 'undefined' && module.exports) { - module.exports.Utils = new Utils(); - } else if (typeof global.Utils === 'undefined') { - global.Utils = new Utils(); - } + // expose this module + ((typeof module !== 'undefined' && module.exports) || + (typeof exports !== 'undefined' && exports) || + (typeof window !== 'undefined' && window) || + (typeof self !== 'undefined' && self) || + (typeof $this !== 'undefined' && $this) || + Function('return this')())["Utils"] = new Utils(); })(this); /* @@ -687,7 +706,7 @@ function require() { * */ -(function (global, undefined) { +(function (ctx, undefined) { var utils = require("./utils.js").Utils; @@ -895,11 +914,13 @@ function require() { else return language; } - if (typeof module !== 'undefined' && module.exports) { - module.exports.DiffParser = new DiffParser(); - } else if (typeof global.DiffParser === 'undefined') { - global.DiffParser = new DiffParser(); - } + // expose this module + ((typeof module !== 'undefined' && module.exports) || + (typeof exports !== 'undefined' && exports) || + (typeof window !== 'undefined' && window) || + (typeof self !== 'undefined' && self) || + (typeof $this !== 'undefined' && $this) || + Function('return this')())["DiffParser"] = new DiffParser(); })(this); /* @@ -909,12 +930,10 @@ function require() { * */ -(function (global, undefined) { +(function (ctx, undefined) { // dirty hack for browser compatibility - var jsDiff = (typeof JsDiff !== "undefined" && JsDiff) || - require("diff") || - require("../lib/diff.js"); + var jsDiff = (typeof JsDiff !== "undefined" && JsDiff) || require("diff"); var utils = require("./utils.js").Utils; function PrinterUtils() { @@ -988,11 +1007,13 @@ function require() { return line.replace(/(((.|\n)*?)<\/del>)/g, ""); } - if (typeof module !== 'undefined' && module.exports) { - module.exports.PrinterUtils = new PrinterUtils(); - } else if (typeof global.PrinterUtils === 'undefined') { - global.PrinterUtils = new PrinterUtils(); - } + // expose this module + ((typeof module !== 'undefined' && module.exports) || + (typeof exports !== 'undefined' && exports) || + (typeof window !== 'undefined' && window) || + (typeof self !== 'undefined' && self) || + (typeof $this !== 'undefined' && $this) || + Function('return this')())["PrinterUtils"] = new PrinterUtils(); })(this); /* @@ -1002,7 +1023,7 @@ function require() { * */ -(function (global, undefined) { +(function (ctx, undefined) { var diffParser = require("./diff-parser.js").DiffParser; var printerUtils = require("./printer-utils.js").PrinterUtils; @@ -1183,11 +1204,13 @@ function require() { return fileHtml; } - if (typeof module !== 'undefined' && module.exports) { - module.exports.SideBySidePrinter = new SideBySidePrinter(); - } else if (typeof global.SideBySidePrinter === 'undefined') { - global.SideBySidePrinter = new SideBySidePrinter(); - } + // expose this module + ((typeof module !== 'undefined' && module.exports) || + (typeof exports !== 'undefined' && exports) || + (typeof window !== 'undefined' && window) || + (typeof self !== 'undefined' && self) || + (typeof $this !== 'undefined' && $this) || + Function('return this')())["SideBySidePrinter"] = new SideBySidePrinter(); })(this); /* @@ -1197,7 +1220,7 @@ function require() { * */ -(function (global, undefined) { +(function (ctx, undefined) { var diffParser = require("./diff-parser.js").DiffParser; var printerUtils = require("./printer-utils.js").PrinterUtils; @@ -1342,11 +1365,13 @@ function require() { "\n"; } - if (typeof module !== 'undefined' && module.exports) { - module.exports.LineByLinePrinter = new LineByLinePrinter(); - } else if (typeof global.LineByLinePrinter === 'undefined') { - global.LineByLinePrinter = new LineByLinePrinter(); - } + // expose this module + ((typeof module !== 'undefined' && module.exports) || + (typeof exports !== 'undefined' && exports) || + (typeof window !== 'undefined' && window) || + (typeof self !== 'undefined' && self) || + (typeof $this !== 'undefined' && $this) || + Function('return this')())["LineByLinePrinter"] = new LineByLinePrinter(); })(this); /* @@ -1356,7 +1381,7 @@ function require() { * */ -(function (global, undefined) { +(function (ctx, undefined) { var lineByLinePrinter = require("./line-by-line-printer.js").LineByLinePrinter; var sideBySidePrinter = require("./side-by-side-printer.js").SideBySidePrinter; @@ -1368,11 +1393,13 @@ function require() { HtmlPrinter.prototype.generateSideBySideJsonHtml = sideBySidePrinter.generateSideBySideJsonHtml; - if (typeof module !== 'undefined' && module.exports) { - module.exports.HtmlPrinter = new HtmlPrinter(); - } else if (typeof global.HtmlPrinter === 'undefined') { - global.HtmlPrinter = new HtmlPrinter(); - } + // expose this module + ((typeof module !== 'undefined' && module.exports) || + (typeof exports !== 'undefined' && exports) || + (typeof window !== 'undefined' && window) || + (typeof self !== 'undefined' && self) || + (typeof $this !== 'undefined' && $this) || + Function('return this')())["HtmlPrinter"] = new HtmlPrinter(); })(this); /* @@ -1380,11 +1407,9 @@ function require() { * Diff to HTML (diff2html.js) * Author: rtfpessoa * - * Diff commands: - * git diff */ -(function (global, undefined) { +(function (ctx, undefined) { var diffParser = require("./diff-parser.js").DiffParser; var htmlPrinter = require("./html-printer.js").HtmlPrinter; @@ -1393,13 +1418,12 @@ function require() { } /* - * config - * { - * "wordByWord" : true (default) - * OR - * "charByChar" : true - * } - * + * Line diff type configuration + var config = { + "wordByWord": true, // (default) + // OR + "charByChar": true + }; */ /* @@ -1444,10 +1468,12 @@ function require() { return htmlPrinter.generateSideBySideJsonHtml(diffJson, configOrEmpty); }; - if (typeof module !== 'undefined' && module.exports) { - module.exports.Diff2Html = new Diff2Html(); - } else if (typeof global.Diff2Html === 'undefined') { - global.Diff2Html = new Diff2Html(); - } + // expose this module + ((typeof module !== 'undefined' && module.exports) || + (typeof exports !== 'undefined' && exports) || + (typeof window !== 'undefined' && window) || + (typeof self !== 'undefined' && self) || + (typeof $this !== 'undefined' && $this) || + Function('return this')())["Diff2Html"] = new Diff2Html(); })(this); diff --git a/dist/diff2html.min.js b/dist/diff2html.min.js index f2ffdd3..61c296a 100644 --- a/dist/diff2html.min.js +++ b/dist/diff2html.min.js @@ -1 +1 @@ -function require(){return global}var global=this;!function(global,undefined){function map(arr,mapper,that){if(Array.prototype.map)return Array.prototype.map.call(arr,mapper,that);for(var other=new Array(arr.length),i=0,n=arr.length;n>i;i++)other[i]=mapper.call(that,arr[i],i,arr);return other}function clonePath(path){return{newPos:path.newPos,components:path.components.slice(0)}}function removeEmpty(array){for(var ret=[],i=0;i/g,">"),n=n.replace(/"/g,""")}function canonicalize(obj,stack,replacementStack){stack=stack||[],replacementStack=replacementStack||[];var i;for(i=0;icomponentPos;componentPos++){var component=components[componentPos];if(component.removed){if(component.value=oldString.slice(oldPos,oldPos+component.count).join(""),oldPos+=component.count,componentPos&&components[componentPos-1].added){var tmp=components[componentPos-1];components[componentPos-1]=components[componentPos],components[componentPos]=tmp}}else{if(!component.added&&useLongestToken){var value=newString.slice(newPos,newPos+component.count);value=map(value,function(value,i){var oldValue=oldString[oldPos+i];return oldValue.length>value.length?oldValue:value}),component.value=value.join("")}else component.value=newString.slice(newPos,newPos+component.count).join("");newPos+=component.count,component.added||(oldPos+=component.count)}}return components}function Diff(ignoreWhitespace){this.ignoreWhitespace=ignoreWhitespace}var objectPrototypeToString=Object.prototype.toString;Diff.prototype={diff:function(oldString,newString,callback){function done(value){return callback?(setTimeout(function(){callback(undefined,value)},0),!0):value}function execEditLength(){for(var diagonalPath=-1*editLength;editLength>=diagonalPath;diagonalPath+=2){var basePath,addPath=bestPath[diagonalPath-1],removePath=bestPath[diagonalPath+1],oldPos=(removePath?removePath.newPos:0)-diagonalPath;addPath&&(bestPath[diagonalPath-1]=undefined);var canAdd=addPath&&addPath.newPos+1=0&&oldLen>oldPos;if(canAdd||canRemove){if(!canAdd||canRemove&&addPath.newPos=newLen&&oldPos+1>=oldLen)return done(buildValues(basePath.components,newString,oldString,self.useLongestToken));bestPath[diagonalPath]=basePath}else bestPath[diagonalPath]=undefined}editLength++}var self=this;if(newString===oldString)return done([{value:newString}]);if(!newString)return done([{value:oldString,removed:!0}]);if(!oldString)return done([{value:newString,added:!0}]);newString=this.tokenize(newString),oldString=this.tokenize(oldString);var newLen=newString.length,oldLen=oldString.length,editLength=1,maxEditLength=newLen+oldLen,bestPath=[{newPos:-1,components:[]}],oldPos=this.extractCommon(bestPath[0],newString,oldString,0);if(bestPath[0].newPos+1>=newLen&&oldPos+1>=oldLen)return done([{value:newString.join("")}]);if(callback)!function exec(){setTimeout(function(){return editLength>maxEditLength?callback():void(execEditLength()||exec())},0)}();else for(;maxEditLength>=editLength;){var ret=execEditLength();if(ret)return ret}},pushComponent:function(components,added,removed){var last=components[components.length-1];last&&last.added===added&&last.removed===removed?components[components.length-1]={count:last.count+1,added:added,removed:removed}:components.push({count:1,added:added,removed:removed})},extractCommon:function(basePath,newString,oldString,diagonalPath){for(var newLen=newString.length,oldLen=oldString.length,newPos=basePath.newPos,oldPos=newPos-diagonalPath,commonCount=0;newLen>newPos+1&&oldLen>oldPos+1&&this.equals(newString[newPos+1],oldString[oldPos+1]);)newPos++,oldPos++,commonCount++;return commonCount&&basePath.components.push({count:commonCount}),basePath.newPos=newPos,oldPos},equals:function(left,right){var reWhitespace=/\S/;return left===right||this.ignoreWhitespace&&!reWhitespace.test(left)&&!reWhitespace.test(right)},tokenize:function(value){return value.split("")}};var CharDiff=new Diff,WordDiff=new Diff(!0),WordWithSpaceDiff=new Diff;WordDiff.tokenize=WordWithSpaceDiff.tokenize=function(value){return removeEmpty(value.split(/(\s+|\b)/))};var CssDiff=new Diff(!0);CssDiff.tokenize=function(value){return removeEmpty(value.split(/([{}:;,]|\s+)/))};var LineDiff=new Diff,TrimmedLineDiff=new Diff;TrimmedLineDiff.ignoreTrim=!0,LineDiff.tokenize=TrimmedLineDiff.tokenize=function(value){for(var retLines=[],lines=value.split(/^/m),i=0;i=0;i--){for(var hunk=hunks[i],j=0;j"):change.removed&&ret.push(""),ret.push(escapeHTML(change.value)),change.added?ret.push(""):change.removed&&ret.push("")}return ret.join("")},convertChangesToDMP:function(changes){for(var change,operation,ret=[],i=0;i/g,">").replace(/\t/g," ")},Utils.prototype.startsWith=function(str,start){return 0===str.indexOf(start)},Utils.prototype.valueOrEmpty=function(value){return value?value:""},"undefined"!=typeof module&&module.exports?module.exports.Utils=new Utils:"undefined"==typeof global.Utils&&(global.Utils=new Utils)}(this),function(global,undefined){function DiffParser(){}function getExtension(filename,language){var nameSplit=filename.split(".");return nameSplit.length>1?nameSplit[nameSplit.length-1]:language}var utils=require("./utils.js").Utils,LINE_TYPE={INSERTS:"d2h-ins",DELETES:"d2h-del",CONTEXT:"d2h-cntx",INFO:"d2h-info"};DiffParser.prototype.LINE_TYPE=LINE_TYPE,DiffParser.prototype.generateDiffJson=function(diffInput){var files=[],currentFile=null,currentBlock=null,oldLine=null,newLine=null,saveBlock=function(){currentBlock&&(currentFile.blocks.push(currentBlock),currentBlock=null)},saveFile=function(){currentFile&¤tFile.newName&&(files.push(currentFile),currentFile=null)},startFile=function(){saveBlock(),saveFile(),currentFile={},currentFile.blocks=[],currentFile.deletedLines=0,currentFile.addedLines=0},startBlock=function(line){saveBlock();var values;(values=/^@@ -(\d+),\d+ \+(\d+),\d+ @@.*/.exec(line))?currentFile.isCombined=!1:(values=/^@@@ -(\d+),\d+ -\d+,\d+ \+(\d+),\d+ @@@.*/.exec(line))?currentFile.isCombined=!0:(values=[0,0],currentFile.isCombined=!1),oldLine=values[1],newLine=values[2],currentBlock={},currentBlock.lines=[],currentBlock.oldStartLine=oldLine,currentBlock.newStartLine=newLine,currentBlock.header=line},createLine=function(line){var currentLine={};currentLine.content=line,utils.startsWith(line,"+")||utils.startsWith(line," +")?(currentFile.addedLines++,currentLine.type=LINE_TYPE.INSERTS,currentLine.oldNumber=null,currentLine.newNumber=newLine++,currentBlock.lines.push(currentLine)):utils.startsWith(line,"-")||utils.startsWith(line," -")?(currentFile.deletedLines++,currentLine.type=LINE_TYPE.DELETES,currentLine.oldNumber=oldLine++,currentLine.newNumber=null,currentBlock.lines.push(currentLine)):(currentLine.type=LINE_TYPE.CONTEXT,currentLine.oldNumber=oldLine++,currentLine.newNumber=newLine++,currentBlock.lines.push(currentLine))},diffLines=diffInput.split("\n");return diffLines.forEach(function(line){if(line&&!utils.startsWith(line,"*")){var oldMode=/^old mode (\d{6})/,newMode=/^new mode (\d{6})/,deletedFileMode=/^deleted file mode (\d{6})/,newFileMode=/^new file mode (\d{6})/,copyFrom=/^copy from (.+)/,copyTo=/^copy to (.+)/,renameFrom=/^rename from (.+)/,renameTo=/^rename to (.+)/,similarityIndex=/^similarity index (\d+)%/,dissimilarityIndex=/^dissimilarity index (\d+)%/,index=/^index ([0-9a-z]+)..([0-9a-z]+) (\d{6})?/,combinedIndex=/^index ([0-9a-z]+),([0-9a-z]+)..([0-9a-z]+)/,combinedMode=/^mode (\d{6}),(\d{6})..(\d{6})/,combinedNewFile=/^new file mode (\d{6})/,combinedDeletedFile=/^deleted file mode (\d{6}),(\d{6})/,values=[];utils.startsWith(line,"diff")?startFile():currentFile&&!currentFile.oldName&&(values=/^--- a\/(\S+).*$/.exec(line))?(currentFile.oldName=values[1],currentFile.language=getExtension(currentFile.oldName,currentFile.language)):currentFile&&!currentFile.newName&&(values=/^\+\+\+ [b]?\/(\S+).*$/.exec(line))?(currentFile.newName=values[1],currentFile.language=getExtension(currentFile.newName,currentFile.language)):currentFile&&utils.startsWith(line,"@@")?startBlock(line):(values=oldMode.exec(line))?currentFile.oldMode=values[1]:(values=newMode.exec(line))?currentFile.newMode=values[1]:(values=deletedFileMode.exec(line))?currentFile.deletedFileMode=values[1]:(values=newFileMode.exec(line))?currentFile.newFileMode=values[1]:(values=copyFrom.exec(line))?(currentFile.oldName=values[1],currentFile.isCopy=!0):(values=copyTo.exec(line))?(currentFile.newName=values[1],currentFile.isCopy=!0):(values=renameFrom.exec(line))?(currentFile.oldName=values[1],currentFile.isRename=!0):(values=renameTo.exec(line))?(currentFile.newName=values[1],currentFile.isRename=!0):(values=similarityIndex.exec(line))?currentFile.unchangedPercentage=values[1]:(values=dissimilarityIndex.exec(line))?currentFile.changedPercentage=values[1]:(values=index.exec(line))?(currentFile.checksumBefore=values[1],currentFile.checksumAfter=values[2],values[2]&&(currentFile.mode=values[3])):(values=combinedIndex.exec(line))?(currentFile.checksumBefore=[values[2],values[3]],currentFile.checksumAfter=values[1]):(values=combinedMode.exec(line))?(currentFile.oldMode=[values[2],values[3]],currentFile.newMode=values[1]):(values=combinedNewFile.exec(line))?currentFile.newFileMode=values[1]:(values=combinedDeletedFile.exec(line))?currentFile.deletedFileMode=values[1]:currentBlock&&createLine(line)}}),saveBlock(),saveFile(),files},"undefined"!=typeof module&&module.exports?module.exports.DiffParser=new DiffParser:"undefined"==typeof global.DiffParser&&(global.DiffParser=new DiffParser)}(this),function(global,undefined){function PrinterUtils(){}function isDeletedName(name){return"dev/null"===name}function removeIns(line){return line.replace(/(((.|\n)*?)<\/ins>)/g,"")}function removeDel(line){return line.replace(/(((.|\n)*?)<\/del>)/g,"")}var jsDiff="undefined"!=typeof JsDiff&&JsDiff||require("diff")||require("../lib/diff.js"),utils=require("./utils.js").Utils;PrinterUtils.prototype.getDiffName=function(file){var oldFilename=file.oldName,newFilename=file.newName;return oldFilename&&newFilename&&oldFilename!==newFilename&&!isDeletedName(newFilename)?oldFilename+" -> "+newFilename:newFilename&&!isDeletedName(newFilename)?newFilename:oldFilename?oldFilename:"Unknown filename"},PrinterUtils.prototype.diffHighlight=function(diffLine1,diffLine2,config){var lineStart1,lineStart2,prefixSize=1;config.isCombined&&(prefixSize=2),lineStart1=diffLine1.substr(0,prefixSize),lineStart2=diffLine2.substr(0,prefixSize),diffLine1=diffLine1.substr(prefixSize),diffLine2=diffLine2.substr(prefixSize);var diff;diff=config.charByChar?jsDiff.diffChars(diffLine1,diffLine2):jsDiff.diffWordsWithSpace(diffLine1,diffLine2);var highlightedLine="";return diff.forEach(function(part){var elemType=part.added?"ins":part.removed?"del":null,escapedValue=utils.escape(part.value);highlightedLine+=null!==elemType?"<"+elemType+">"+escapedValue+"":escapedValue}),{first:{prefix:lineStart1,line:removeIns(highlightedLine)},second:{prefix:lineStart2,line:removeDel(highlightedLine)}}},"undefined"!=typeof module&&module.exports?module.exports.PrinterUtils=new PrinterUtils:"undefined"==typeof global.PrinterUtils&&(global.PrinterUtils=new PrinterUtils)}(this),function(global,undefined){function SideBySidePrinter(){}function generateSideBySideFileHtml(file,config){var fileHtml={};return fileHtml.left="",fileHtml.right="",file.blocks.forEach(function(block){fileHtml.left+='\n \n
'+utils.escape(block.header)+"
\n\n",fileHtml.right+='\n \n
\n\n';for(var oldLines=[],newLines=[],tmpHtml="",i=0;inewLines.length)newLines.push(line);else{var oldLine,newLine,j=0;if(oldLines.length===newLines.length)for(j=0;j");var htmlContent="";return content&&(htmlContent=''+content+""),'\n '+number+'\n
'+htmlPrefix+htmlContent+"
\n \n"}function generateEmptyDiff(){var fileHtml={};return fileHtml.right="",fileHtml.left='\n
File without changes
\n\n',fileHtml}var diffParser=require("./diff-parser.js").DiffParser,printerUtils=require("./printer-utils.js").PrinterUtils,utils=require("./utils.js").Utils;SideBySidePrinter.prototype.generateSideBySideJsonHtml=function(diffFiles,config){return'
\n'+diffFiles.map(function(file){var diffs;return diffs=file.blocks.length?generateSideBySideFileHtml(file,config):generateEmptyDiff(),'
\n
\n
\n +'+file.addedLines+'\n -'+file.deletedLines+'\n
\n
'+printerUtils.getDiffName(file)+'
\n
\n
\n
\n
\n \n \n '+diffs.left+' \n
\n
\n
\n
\n
\n \n \n '+diffs.right+" \n
\n
\n
\n
\n
\n"}).join("\n")+"
\n"},"undefined"!=typeof module&&module.exports?module.exports.SideBySidePrinter=new SideBySidePrinter:"undefined"==typeof global.SideBySidePrinter&&(global.SideBySidePrinter=new SideBySidePrinter)}(this),function(global,undefined){function LineByLinePrinter(){}function generateFileHtml(file,config){return file.blocks.map(function(block){for(var lines='\n \n
'+utils.escape(block.header)+"
\n\n",oldLines=[],newLines=[],processedOldLines=[],processedNewLines=[],i=0;inewLines.length)newLines.push(line);else{var oldLine,newLine,j=0;if(oldLines.length===newLines.length){for(j=0;j");var htmlContent="";return content&&(htmlContent=''+content+""),'\n
'+utils.valueOrEmpty(oldNumber)+'
'+utils.valueOrEmpty(newNumber)+'
\n
'+htmlPrefix+htmlContent+"
\n\n"}function generateEmptyDiff(){return'\n
File without changes
\n\n'}var diffParser=require("./diff-parser.js").DiffParser,printerUtils=require("./printer-utils.js").PrinterUtils,utils=require("./utils.js").Utils;LineByLinePrinter.prototype.generateLineByLineJsonHtml=function(diffFiles,config){return'
\n'+diffFiles.map(function(file){var diffs;return diffs=file.blocks.length?generateFileHtml(file,config):generateEmptyDiff(),'
\n
\n
\n +'+file.addedLines+'\n -'+file.deletedLines+'\n
\n
'+printerUtils.getDiffName(file)+'
\n
\n
\n
\n \n \n '+diffs+" \n
\n
\n
\n
\n"}).join("\n")+"
\n"},"undefined"!=typeof module&&module.exports?module.exports.LineByLinePrinter=new LineByLinePrinter:"undefined"==typeof global.LineByLinePrinter&&(global.LineByLinePrinter=new LineByLinePrinter)}(this),function(global,undefined){function HtmlPrinter(){}var lineByLinePrinter=require("./line-by-line-printer.js").LineByLinePrinter,sideBySidePrinter=require("./side-by-side-printer.js").SideBySidePrinter;HtmlPrinter.prototype.generateLineByLineJsonHtml=lineByLinePrinter.generateLineByLineJsonHtml,HtmlPrinter.prototype.generateSideBySideJsonHtml=sideBySidePrinter.generateSideBySideJsonHtml,"undefined"!=typeof module&&module.exports?module.exports.HtmlPrinter=new HtmlPrinter:"undefined"==typeof global.HtmlPrinter&&(global.HtmlPrinter=new HtmlPrinter)}(this),function(global,undefined){function Diff2Html(){}var diffParser=require("./diff-parser.js").DiffParser,htmlPrinter=require("./html-printer.js").HtmlPrinter;Diff2Html.prototype.getPrettyHtmlFromDiff=function(diffInput,config){var diffJson=diffParser.generateDiffJson(diffInput),configOrEmpty=config||{};return htmlPrinter.generateLineByLineJsonHtml(diffJson,configOrEmpty)},Diff2Html.prototype.getJsonFromDiff=function(diffInput){return diffParser.generateDiffJson(diffInput)},Diff2Html.prototype.getPrettyHtmlFromJson=function(diffJson,config){var configOrEmpty=config||{};return htmlPrinter.generateLineByLineJsonHtml(diffJson,configOrEmpty)},Diff2Html.prototype.getPrettySideBySideHtmlFromDiff=function(diffInput,config){var diffJson=diffParser.generateDiffJson(diffInput),configOrEmpty=config||{};return htmlPrinter.generateSideBySideJsonHtml(diffJson,configOrEmpty)},Diff2Html.prototype.getPrettySideBySideHtmlFromJson=function(diffJson,config){var configOrEmpty=config||{};return htmlPrinter.generateSideBySideJsonHtml(diffJson,configOrEmpty)},"undefined"!=typeof module&&module.exports?module.exports.Diff2Html=new Diff2Html:"undefined"==typeof global.Diff2Html&&(global.Diff2Html=new Diff2Html)}(this); \ No newline at end of file +function require(){return $globalHolder}var $globalHolder="undefined"!=typeof module&&module.exports||"undefined"!=typeof exports&&exports||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||"undefined"!=typeof this&&this||Function("return this")();!function(global,undefined){function map(arr,mapper,that){if(Array.prototype.map)return Array.prototype.map.call(arr,mapper,that);for(var other=new Array(arr.length),i=0,n=arr.length;n>i;i++)other[i]=mapper.call(that,arr[i],i,arr);return other}function clonePath(path){return{newPos:path.newPos,components:path.components.slice(0)}}function removeEmpty(array){for(var ret=[],i=0;i/g,">"),n=n.replace(/"/g,""")}function canonicalize(obj,stack,replacementStack){stack=stack||[],replacementStack=replacementStack||[];var i;for(i=0;icomponentPos;componentPos++){var component=components[componentPos];if(component.removed){if(component.value=oldString.slice(oldPos,oldPos+component.count).join(""),oldPos+=component.count,componentPos&&components[componentPos-1].added){var tmp=components[componentPos-1];components[componentPos-1]=components[componentPos],components[componentPos]=tmp}}else{if(!component.added&&useLongestToken){var value=newString.slice(newPos,newPos+component.count);value=map(value,function(value,i){var oldValue=oldString[oldPos+i];return oldValue.length>value.length?oldValue:value}),component.value=value.join("")}else component.value=newString.slice(newPos,newPos+component.count).join("");newPos+=component.count,component.added||(oldPos+=component.count)}}return components}function Diff(ignoreWhitespace){this.ignoreWhitespace=ignoreWhitespace}var objectPrototypeToString=Object.prototype.toString;Diff.prototype={diff:function(oldString,newString,callback){function done(value){return callback?(setTimeout(function(){callback(undefined,value)},0),!0):value}function execEditLength(){for(var diagonalPath=-1*editLength;editLength>=diagonalPath;diagonalPath+=2){var basePath,addPath=bestPath[diagonalPath-1],removePath=bestPath[diagonalPath+1],oldPos=(removePath?removePath.newPos:0)-diagonalPath;addPath&&(bestPath[diagonalPath-1]=undefined);var canAdd=addPath&&addPath.newPos+1=0&&oldLen>oldPos;if(canAdd||canRemove){if(!canAdd||canRemove&&addPath.newPos=newLen&&oldPos+1>=oldLen)return done(buildValues(basePath.components,newString,oldString,self.useLongestToken));bestPath[diagonalPath]=basePath}else bestPath[diagonalPath]=undefined}editLength++}var self=this;if(newString===oldString)return done([{value:newString}]);if(!newString)return done([{value:oldString,removed:!0}]);if(!oldString)return done([{value:newString,added:!0}]);newString=this.tokenize(newString),oldString=this.tokenize(oldString);var newLen=newString.length,oldLen=oldString.length,editLength=1,maxEditLength=newLen+oldLen,bestPath=[{newPos:-1,components:[]}],oldPos=this.extractCommon(bestPath[0],newString,oldString,0);if(bestPath[0].newPos+1>=newLen&&oldPos+1>=oldLen)return done([{value:newString.join("")}]);if(callback)!function exec(){setTimeout(function(){return editLength>maxEditLength?callback():void(execEditLength()||exec())},0)}();else for(;maxEditLength>=editLength;){var ret=execEditLength();if(ret)return ret}},pushComponent:function(components,added,removed){var last=components[components.length-1];last&&last.added===added&&last.removed===removed?components[components.length-1]={count:last.count+1,added:added,removed:removed}:components.push({count:1,added:added,removed:removed})},extractCommon:function(basePath,newString,oldString,diagonalPath){for(var newLen=newString.length,oldLen=oldString.length,newPos=basePath.newPos,oldPos=newPos-diagonalPath,commonCount=0;newLen>newPos+1&&oldLen>oldPos+1&&this.equals(newString[newPos+1],oldString[oldPos+1]);)newPos++,oldPos++,commonCount++;return commonCount&&basePath.components.push({count:commonCount}),basePath.newPos=newPos,oldPos},equals:function(left,right){var reWhitespace=/\S/;return left===right||this.ignoreWhitespace&&!reWhitespace.test(left)&&!reWhitespace.test(right)},tokenize:function(value){return value.split("")}};var CharDiff=new Diff,WordDiff=new Diff(!0),WordWithSpaceDiff=new Diff;WordDiff.tokenize=WordWithSpaceDiff.tokenize=function(value){return removeEmpty(value.split(/(\s+|\b)/))};var CssDiff=new Diff(!0);CssDiff.tokenize=function(value){return removeEmpty(value.split(/([{}:;,]|\s+)/))};var LineDiff=new Diff,TrimmedLineDiff=new Diff;TrimmedLineDiff.ignoreTrim=!0,LineDiff.tokenize=TrimmedLineDiff.tokenize=function(value){for(var retLines=[],lines=value.split(/^/m),i=0;i=0;i--){for(var hunk=hunks[i],j=0;j"):change.removed&&ret.push(""),ret.push(escapeHTML(change.value)),change.added?ret.push("
"):change.removed&&ret.push("
")}return ret.join("")},convertChangesToDMP:function(changes){for(var change,operation,ret=[],i=0;i/g,">").replace(/\t/g," ")},Utils.prototype.startsWith=function(str,start){return 0===str.indexOf(start)},Utils.prototype.valueOrEmpty=function(value){return value?value:""},("undefined"!=typeof module&&module.exports||"undefined"!=typeof exports&&exports||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||"undefined"!=typeof $this&&$this||Function("return this")()).Utils=new Utils}(this),function(ctx,undefined){function DiffParser(){}function getExtension(filename,language){var nameSplit=filename.split(".");return nameSplit.length>1?nameSplit[nameSplit.length-1]:language}var utils=require("./utils.js").Utils,LINE_TYPE={INSERTS:"d2h-ins",DELETES:"d2h-del",CONTEXT:"d2h-cntx",INFO:"d2h-info"};DiffParser.prototype.LINE_TYPE=LINE_TYPE,DiffParser.prototype.generateDiffJson=function(diffInput){var files=[],currentFile=null,currentBlock=null,oldLine=null,newLine=null,saveBlock=function(){currentBlock&&(currentFile.blocks.push(currentBlock),currentBlock=null)},saveFile=function(){currentFile&¤tFile.newName&&(files.push(currentFile),currentFile=null)},startFile=function(){saveBlock(),saveFile(),currentFile={},currentFile.blocks=[],currentFile.deletedLines=0,currentFile.addedLines=0},startBlock=function(line){saveBlock();var values;(values=/^@@ -(\d+),\d+ \+(\d+),\d+ @@.*/.exec(line))?currentFile.isCombined=!1:(values=/^@@@ -(\d+),\d+ -\d+,\d+ \+(\d+),\d+ @@@.*/.exec(line))?currentFile.isCombined=!0:(values=[0,0],currentFile.isCombined=!1),oldLine=values[1],newLine=values[2],currentBlock={},currentBlock.lines=[],currentBlock.oldStartLine=oldLine,currentBlock.newStartLine=newLine,currentBlock.header=line},createLine=function(line){var currentLine={};currentLine.content=line,utils.startsWith(line,"+")||utils.startsWith(line," +")?(currentFile.addedLines++,currentLine.type=LINE_TYPE.INSERTS,currentLine.oldNumber=null,currentLine.newNumber=newLine++,currentBlock.lines.push(currentLine)):utils.startsWith(line,"-")||utils.startsWith(line," -")?(currentFile.deletedLines++,currentLine.type=LINE_TYPE.DELETES,currentLine.oldNumber=oldLine++,currentLine.newNumber=null,currentBlock.lines.push(currentLine)):(currentLine.type=LINE_TYPE.CONTEXT,currentLine.oldNumber=oldLine++,currentLine.newNumber=newLine++,currentBlock.lines.push(currentLine))},diffLines=diffInput.split("\n");return diffLines.forEach(function(line){if(line&&!utils.startsWith(line,"*")){var oldMode=/^old mode (\d{6})/,newMode=/^new mode (\d{6})/,deletedFileMode=/^deleted file mode (\d{6})/,newFileMode=/^new file mode (\d{6})/,copyFrom=/^copy from (.+)/,copyTo=/^copy to (.+)/,renameFrom=/^rename from (.+)/,renameTo=/^rename to (.+)/,similarityIndex=/^similarity index (\d+)%/,dissimilarityIndex=/^dissimilarity index (\d+)%/,index=/^index ([0-9a-z]+)..([0-9a-z]+) (\d{6})?/,combinedIndex=/^index ([0-9a-z]+),([0-9a-z]+)..([0-9a-z]+)/,combinedMode=/^mode (\d{6}),(\d{6})..(\d{6})/,combinedNewFile=/^new file mode (\d{6})/,combinedDeletedFile=/^deleted file mode (\d{6}),(\d{6})/,values=[];utils.startsWith(line,"diff")?startFile():currentFile&&!currentFile.oldName&&(values=/^--- a\/(\S+).*$/.exec(line))?(currentFile.oldName=values[1],currentFile.language=getExtension(currentFile.oldName,currentFile.language)):currentFile&&!currentFile.newName&&(values=/^\+\+\+ [b]?\/(\S+).*$/.exec(line))?(currentFile.newName=values[1],currentFile.language=getExtension(currentFile.newName,currentFile.language)):currentFile&&utils.startsWith(line,"@@")?startBlock(line):(values=oldMode.exec(line))?currentFile.oldMode=values[1]:(values=newMode.exec(line))?currentFile.newMode=values[1]:(values=deletedFileMode.exec(line))?currentFile.deletedFileMode=values[1]:(values=newFileMode.exec(line))?currentFile.newFileMode=values[1]:(values=copyFrom.exec(line))?(currentFile.oldName=values[1],currentFile.isCopy=!0):(values=copyTo.exec(line))?(currentFile.newName=values[1],currentFile.isCopy=!0):(values=renameFrom.exec(line))?(currentFile.oldName=values[1],currentFile.isRename=!0):(values=renameTo.exec(line))?(currentFile.newName=values[1],currentFile.isRename=!0):(values=similarityIndex.exec(line))?currentFile.unchangedPercentage=values[1]:(values=dissimilarityIndex.exec(line))?currentFile.changedPercentage=values[1]:(values=index.exec(line))?(currentFile.checksumBefore=values[1],currentFile.checksumAfter=values[2],values[2]&&(currentFile.mode=values[3])):(values=combinedIndex.exec(line))?(currentFile.checksumBefore=[values[2],values[3]],currentFile.checksumAfter=values[1]):(values=combinedMode.exec(line))?(currentFile.oldMode=[values[2],values[3]],currentFile.newMode=values[1]):(values=combinedNewFile.exec(line))?currentFile.newFileMode=values[1]:(values=combinedDeletedFile.exec(line))?currentFile.deletedFileMode=values[1]:currentBlock&&createLine(line)}}),saveBlock(),saveFile(),files},("undefined"!=typeof module&&module.exports||"undefined"!=typeof exports&&exports||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||"undefined"!=typeof $this&&$this||Function("return this")()).DiffParser=new DiffParser}(this),function(ctx,undefined){function PrinterUtils(){}function isDeletedName(name){return"dev/null"===name}function removeIns(line){return line.replace(/(((.|\n)*?)<\/ins>)/g,"")}function removeDel(line){return line.replace(/(((.|\n)*?)<\/del>)/g,"")}var jsDiff="undefined"!=typeof JsDiff&&JsDiff||require("diff"),utils=require("./utils.js").Utils;PrinterUtils.prototype.getDiffName=function(file){var oldFilename=file.oldName,newFilename=file.newName;return oldFilename&&newFilename&&oldFilename!==newFilename&&!isDeletedName(newFilename)?oldFilename+" -> "+newFilename:newFilename&&!isDeletedName(newFilename)?newFilename:oldFilename?oldFilename:"Unknown filename"},PrinterUtils.prototype.diffHighlight=function(diffLine1,diffLine2,config){var lineStart1,lineStart2,prefixSize=1;config.isCombined&&(prefixSize=2),lineStart1=diffLine1.substr(0,prefixSize),lineStart2=diffLine2.substr(0,prefixSize),diffLine1=diffLine1.substr(prefixSize),diffLine2=diffLine2.substr(prefixSize);var diff;diff=config.charByChar?jsDiff.diffChars(diffLine1,diffLine2):jsDiff.diffWordsWithSpace(diffLine1,diffLine2);var highlightedLine="";return diff.forEach(function(part){var elemType=part.added?"ins":part.removed?"del":null,escapedValue=utils.escape(part.value);highlightedLine+=null!==elemType?"<"+elemType+">"+escapedValue+"":escapedValue}),{first:{prefix:lineStart1,line:removeIns(highlightedLine)},second:{prefix:lineStart2,line:removeDel(highlightedLine)}}},("undefined"!=typeof module&&module.exports||"undefined"!=typeof exports&&exports||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||"undefined"!=typeof $this&&$this||Function("return this")()).PrinterUtils=new PrinterUtils}(this),function(ctx,undefined){function SideBySidePrinter(){}function generateSideBySideFileHtml(file,config){var fileHtml={};return fileHtml.left="",fileHtml.right="",file.blocks.forEach(function(block){fileHtml.left+='\n \n
'+utils.escape(block.header)+"
\n\n",fileHtml.right+='\n \n
\n\n';for(var oldLines=[],newLines=[],tmpHtml="",i=0;inewLines.length)newLines.push(line);else{var oldLine,newLine,j=0;if(oldLines.length===newLines.length)for(j=0;j");var htmlContent="";return content&&(htmlContent=''+content+""),'\n '+number+'\n
'+htmlPrefix+htmlContent+"
\n \n"}function generateEmptyDiff(){var fileHtml={};return fileHtml.right="",fileHtml.left='\n
File without changes
\n\n',fileHtml}var diffParser=require("./diff-parser.js").DiffParser,printerUtils=require("./printer-utils.js").PrinterUtils,utils=require("./utils.js").Utils;SideBySidePrinter.prototype.generateSideBySideJsonHtml=function(diffFiles,config){return'
\n'+diffFiles.map(function(file){var diffs;return diffs=file.blocks.length?generateSideBySideFileHtml(file,config):generateEmptyDiff(),'
\n
\n
\n +'+file.addedLines+'\n -'+file.deletedLines+'\n
\n
'+printerUtils.getDiffName(file)+'
\n
\n
\n
\n
\n \n \n '+diffs.left+' \n
\n
\n
\n
\n
\n \n \n '+diffs.right+" \n
\n
\n
\n
\n
\n"}).join("\n")+"
\n"},("undefined"!=typeof module&&module.exports||"undefined"!=typeof exports&&exports||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||"undefined"!=typeof $this&&$this||Function("return this")()).SideBySidePrinter=new SideBySidePrinter}(this),function(ctx,undefined){function LineByLinePrinter(){}function generateFileHtml(file,config){return file.blocks.map(function(block){for(var lines='\n \n
'+utils.escape(block.header)+"
\n\n",oldLines=[],newLines=[],processedOldLines=[],processedNewLines=[],i=0;inewLines.length)newLines.push(line);else{var oldLine,newLine,j=0;if(oldLines.length===newLines.length){for(j=0;j");var htmlContent="";return content&&(htmlContent=''+content+""),'\n
'+utils.valueOrEmpty(oldNumber)+'
'+utils.valueOrEmpty(newNumber)+'
\n
'+htmlPrefix+htmlContent+"
\n\n"}function generateEmptyDiff(){return'\n
File without changes
\n\n'}var diffParser=require("./diff-parser.js").DiffParser,printerUtils=require("./printer-utils.js").PrinterUtils,utils=require("./utils.js").Utils;LineByLinePrinter.prototype.generateLineByLineJsonHtml=function(diffFiles,config){return'
\n'+diffFiles.map(function(file){var diffs;return diffs=file.blocks.length?generateFileHtml(file,config):generateEmptyDiff(),'
\n
\n
\n +'+file.addedLines+'\n -'+file.deletedLines+'\n
\n
'+printerUtils.getDiffName(file)+'
\n
\n
\n
\n \n \n '+diffs+" \n
\n
\n
\n
\n"}).join("\n")+"
\n"},("undefined"!=typeof module&&module.exports||"undefined"!=typeof exports&&exports||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||"undefined"!=typeof $this&&$this||Function("return this")()).LineByLinePrinter=new LineByLinePrinter}(this),function(ctx,undefined){function HtmlPrinter(){}var lineByLinePrinter=require("./line-by-line-printer.js").LineByLinePrinter,sideBySidePrinter=require("./side-by-side-printer.js").SideBySidePrinter;HtmlPrinter.prototype.generateLineByLineJsonHtml=lineByLinePrinter.generateLineByLineJsonHtml,HtmlPrinter.prototype.generateSideBySideJsonHtml=sideBySidePrinter.generateSideBySideJsonHtml,("undefined"!=typeof module&&module.exports||"undefined"!=typeof exports&&exports||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||"undefined"!=typeof $this&&$this||Function("return this")()).HtmlPrinter=new HtmlPrinter}(this),function(ctx,undefined){function Diff2Html(){}var diffParser=require("./diff-parser.js").DiffParser,htmlPrinter=require("./html-printer.js").HtmlPrinter;Diff2Html.prototype.getPrettyHtmlFromDiff=function(diffInput,config){var diffJson=diffParser.generateDiffJson(diffInput),configOrEmpty=config||{};return htmlPrinter.generateLineByLineJsonHtml(diffJson,configOrEmpty)},Diff2Html.prototype.getJsonFromDiff=function(diffInput){return diffParser.generateDiffJson(diffInput)},Diff2Html.prototype.getPrettyHtmlFromJson=function(diffJson,config){var configOrEmpty=config||{};return htmlPrinter.generateLineByLineJsonHtml(diffJson,configOrEmpty)},Diff2Html.prototype.getPrettySideBySideHtmlFromDiff=function(diffInput,config){var diffJson=diffParser.generateDiffJson(diffInput),configOrEmpty=config||{};return htmlPrinter.generateSideBySideJsonHtml(diffJson,configOrEmpty)},Diff2Html.prototype.getPrettySideBySideHtmlFromJson=function(diffJson,config){var configOrEmpty=config||{};return htmlPrinter.generateSideBySideJsonHtml(diffJson,configOrEmpty)},("undefined"!=typeof module&&module.exports||"undefined"!=typeof exports&&exports||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||"undefined"!=typeof $this&&$this||Function("return this")()).Diff2Html=new Diff2Html}(this); \ No newline at end of file diff --git a/lib/fakeRequire.js b/lib/fakeRequire.js index bb2a71f..a9ee153 100644 --- a/lib/fakeRequire.js +++ b/lib/fakeRequire.js @@ -1,4 +1,20 @@ -var global = this; +/* + * Hack to allow nodejs require("package/file") in the browser + * How? + * Since every require is used as an object: + * `require("./utils.js").Utils` // (notice the `.Utils`) + * + * We can say that when there is no require method + * we use the global object in which the `Utils` + * object was already injected. + */ + +var $globalHolder = (typeof module !== 'undefined' && module.exports) || + (typeof exports !== 'undefined' && exports) || + (typeof window !== 'undefined' && window) || + (typeof self !== 'undefined' && self) || + (typeof this !== 'undefined' && this) || + Function('return this')(); function require() { - return global; -} \ No newline at end of file + return $globalHolder; +} diff --git a/package.json b/package.json index 0ee2966..3cb1424 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "diff2html", - "version": "0.2.5-1", - "homepage": "https://www.github.com/rtfpessoa/diff2html", + "version": "0.2.6", + "homepage": "http://rtfpessoa.github.io/diff2html/", "description": "Fast Diff to colorized HTML", "keywords": [ "git", diff --git a/sample/index.html b/sample/index.html index a3a2042..0116fa0 100644 --- a/sample/index.html +++ b/sample/index.html @@ -29,7 +29,6 @@ - @@ -218,23 +217,30 @@ '+\n' + '+console.log(parser.parsePatchDiffResult(text, patchLineList));\n'; - $(document).ready(function () { - var diff2Html = Diff2Html; - var diffJson = diff2Html.getJsonFromDiff(lineDiffExample); + document.addEventListener("DOMContentLoaded", function () { + // parse the diff to json + var diffJson = Diff2Html.getJsonFromDiff(lineDiffExample); + // collect all the file extensions in the json var allFileLanguages = diffJson.map(function (line) { return line.language; }); + + // remove duplicated languages var distinctLanguages = allFileLanguages.filter(function (v, i) { return allFileLanguages.indexOf(v) == i; }); + + // pass the languages to the highlightjs plugin hljs.configure({languages: distinctLanguages}); - $("#line-by-line").html(diff2Html.getPrettyHtmlFromJson(diffJson)); - $("#side-by-side").html(diff2Html.getPrettySideBySideHtmlFromJson(diffJson)); + // generate and inject the diff HTML into the desired place + document.getElementById("line-by-line").innerHTML = Diff2Html.getPrettyHtmlFromJson(diffJson); + document.getElementById("side-by-side").innerHTML = Diff2Html.getPrettySideBySideHtmlFromJson(diffJson); - var code = $(".d2h-code-line-ctn"); - code.map(function (i, line) { + // collect all the code lines and execute the highlight on them + var codeLines = document.getElementsByClassName("d2h-code-line-ctn"); + [].forEach.call(codeLines, function (line) { hljs.highlightBlock(line); }); }); diff --git a/src/diff-parser.js b/src/diff-parser.js index dcf1d12..1bd9a07 100644 --- a/src/diff-parser.js +++ b/src/diff-parser.js @@ -5,7 +5,7 @@ * */ -(function (global, undefined) { +(function (ctx, undefined) { var utils = require("./utils.js").Utils; @@ -213,10 +213,12 @@ else return language; } - if (typeof module !== 'undefined' && module.exports) { - module.exports.DiffParser = new DiffParser(); - } else if (typeof global.DiffParser === 'undefined') { - global.DiffParser = new DiffParser(); - } + // expose this module + ((typeof module !== 'undefined' && module.exports) || + (typeof exports !== 'undefined' && exports) || + (typeof window !== 'undefined' && window) || + (typeof self !== 'undefined' && self) || + (typeof $this !== 'undefined' && $this) || + Function('return this')())["DiffParser"] = new DiffParser(); })(this); diff --git a/src/diff2html.js b/src/diff2html.js index 5d769d3..63c733d 100644 --- a/src/diff2html.js +++ b/src/diff2html.js @@ -3,11 +3,9 @@ * Diff to HTML (diff2html.js) * Author: rtfpessoa * - * Diff commands: - * git diff */ -(function (global, undefined) { +(function (ctx, undefined) { var diffParser = require("./diff-parser.js").DiffParser; var htmlPrinter = require("./html-printer.js").HtmlPrinter; @@ -16,13 +14,12 @@ } /* - * config - * { - * "wordByWord" : true (default) - * OR - * "charByChar" : true - * } - * + * Line diff type configuration + var config = { + "wordByWord": true, // (default) + // OR + "charByChar": true + }; */ /* @@ -67,10 +64,12 @@ return htmlPrinter.generateSideBySideJsonHtml(diffJson, configOrEmpty); }; - if (typeof module !== 'undefined' && module.exports) { - module.exports.Diff2Html = new Diff2Html(); - } else if (typeof global.Diff2Html === 'undefined') { - global.Diff2Html = new Diff2Html(); - } + // expose this module + ((typeof module !== 'undefined' && module.exports) || + (typeof exports !== 'undefined' && exports) || + (typeof window !== 'undefined' && window) || + (typeof self !== 'undefined' && self) || + (typeof $this !== 'undefined' && $this) || + Function('return this')())["Diff2Html"] = new Diff2Html(); })(this); diff --git a/src/html-printer.js b/src/html-printer.js index 8237cbf..0f9a99c 100644 --- a/src/html-printer.js +++ b/src/html-printer.js @@ -5,7 +5,7 @@ * */ -(function (global, undefined) { +(function (ctx, undefined) { var lineByLinePrinter = require("./line-by-line-printer.js").LineByLinePrinter; var sideBySidePrinter = require("./side-by-side-printer.js").SideBySidePrinter; @@ -17,10 +17,12 @@ HtmlPrinter.prototype.generateSideBySideJsonHtml = sideBySidePrinter.generateSideBySideJsonHtml; - if (typeof module !== 'undefined' && module.exports) { - module.exports.HtmlPrinter = new HtmlPrinter(); - } else if (typeof global.HtmlPrinter === 'undefined') { - global.HtmlPrinter = new HtmlPrinter(); - } + // expose this module + ((typeof module !== 'undefined' && module.exports) || + (typeof exports !== 'undefined' && exports) || + (typeof window !== 'undefined' && window) || + (typeof self !== 'undefined' && self) || + (typeof $this !== 'undefined' && $this) || + Function('return this')())["HtmlPrinter"] = new HtmlPrinter(); })(this); diff --git a/src/line-by-line-printer.js b/src/line-by-line-printer.js index 383ec93..78fdf8b 100644 --- a/src/line-by-line-printer.js +++ b/src/line-by-line-printer.js @@ -5,7 +5,7 @@ * */ -(function (global, undefined) { +(function (ctx, undefined) { var diffParser = require("./diff-parser.js").DiffParser; var printerUtils = require("./printer-utils.js").PrinterUtils; @@ -150,10 +150,12 @@ "\n"; } - if (typeof module !== 'undefined' && module.exports) { - module.exports.LineByLinePrinter = new LineByLinePrinter(); - } else if (typeof global.LineByLinePrinter === 'undefined') { - global.LineByLinePrinter = new LineByLinePrinter(); - } + // expose this module + ((typeof module !== 'undefined' && module.exports) || + (typeof exports !== 'undefined' && exports) || + (typeof window !== 'undefined' && window) || + (typeof self !== 'undefined' && self) || + (typeof $this !== 'undefined' && $this) || + Function('return this')())["LineByLinePrinter"] = new LineByLinePrinter(); })(this); diff --git a/src/printer-utils.js b/src/printer-utils.js index 2b59d85..b8122bf 100644 --- a/src/printer-utils.js +++ b/src/printer-utils.js @@ -5,12 +5,10 @@ * */ -(function (global, undefined) { +(function (ctx, undefined) { // dirty hack for browser compatibility - var jsDiff = (typeof JsDiff !== "undefined" && JsDiff) || - require("diff") || - require("../lib/diff.js"); + var jsDiff = (typeof JsDiff !== "undefined" && JsDiff) || require("diff"); var utils = require("./utils.js").Utils; function PrinterUtils() { @@ -84,10 +82,12 @@ return line.replace(/(((.|\n)*?)<\/del>)/g, ""); } - if (typeof module !== 'undefined' && module.exports) { - module.exports.PrinterUtils = new PrinterUtils(); - } else if (typeof global.PrinterUtils === 'undefined') { - global.PrinterUtils = new PrinterUtils(); - } + // expose this module + ((typeof module !== 'undefined' && module.exports) || + (typeof exports !== 'undefined' && exports) || + (typeof window !== 'undefined' && window) || + (typeof self !== 'undefined' && self) || + (typeof $this !== 'undefined' && $this) || + Function('return this')())["PrinterUtils"] = new PrinterUtils(); })(this); diff --git a/src/side-by-side-printer.js b/src/side-by-side-printer.js index dfb2a55..84d0f9e 100644 --- a/src/side-by-side-printer.js +++ b/src/side-by-side-printer.js @@ -5,7 +5,7 @@ * */ -(function (global, undefined) { +(function (ctx, undefined) { var diffParser = require("./diff-parser.js").DiffParser; var printerUtils = require("./printer-utils.js").PrinterUtils; @@ -186,10 +186,12 @@ return fileHtml; } - if (typeof module !== 'undefined' && module.exports) { - module.exports.SideBySidePrinter = new SideBySidePrinter(); - } else if (typeof global.SideBySidePrinter === 'undefined') { - global.SideBySidePrinter = new SideBySidePrinter(); - } + // expose this module + ((typeof module !== 'undefined' && module.exports) || + (typeof exports !== 'undefined' && exports) || + (typeof window !== 'undefined' && window) || + (typeof self !== 'undefined' && self) || + (typeof $this !== 'undefined' && $this) || + Function('return this')())["SideBySidePrinter"] = new SideBySidePrinter(); })(this); diff --git a/src/utils.js b/src/utils.js index d7cdb04..43eff7f 100644 --- a/src/utils.js +++ b/src/utils.js @@ -5,7 +5,7 @@ * */ -(function (global, undefined) { +(function (ctx, undefined) { function Utils() { } @@ -26,10 +26,12 @@ return value ? value : ""; }; - if (typeof module !== 'undefined' && module.exports) { - module.exports.Utils = new Utils(); - } else if (typeof global.Utils === 'undefined') { - global.Utils = new Utils(); - } + // expose this module + ((typeof module !== 'undefined' && module.exports) || + (typeof exports !== 'undefined' && exports) || + (typeof window !== 'undefined' && window) || + (typeof self !== 'undefined' && self) || + (typeof $this !== 'undefined' && $this) || + Function('return this')())["Utils"] = new Utils(); })(this);