diff --git a/docs/url.html b/docs/demo.html similarity index 95% rename from docs/url.html rename to docs/demo.html index 106c089..4c84ce9 100644 --- a/docs/url.html +++ b/docs/demo.html @@ -79,7 +79,7 @@
  • - Demo + Demo
  • @@ -174,10 +174,8 @@ Can I send a custom url for a friend, colleague or co-worker?

    Just add a url parameter called diff to current url using as value your Commit, Pull Request, Merge Request, Diff or Patch url.

    -

    ex: https://diff2html.xyz/url?diff=https://github.com/rtfpessoa/diff2html/pull/106 +

    ex: https://diff2html.xyz/demo.html?diff=https://github.com/rtfpessoa/diff2html/pull/106

    -

    You can also use an hashtag (# or #! or #!/) in the end of the url. - This will be overridden if you click any href id and for that reason not advised.

  • Why can't I paste a diff? @@ -250,7 +248,7 @@ - + diff --git a/docs/url.js b/docs/demo.js similarity index 97% rename from docs/url.js rename to docs/demo.js index 86972c6..3c554d9 100644 --- a/docs/url.js +++ b/docs/demo.js @@ -453,6 +453,8 @@ $(document).ready(function() { // Improves browser compatibility require('whatwg-fetch'); + var searchParam = 'diff'; + var $container = $('.container'); var $url = $('#url'); var $outputFormat = $('#diff-url-options-output-format'); @@ -461,24 +463,10 @@ $(document).ready(function() { var $wordThreshold = $('#diff-url-options-match-words-threshold'); var $matchingMaxComparisons = $('#diff-url-options-matching-max-comparisons'); - var hash = window.location.hash - .replace(/^(#!?\/?)/, ''); - - var search = window.location.search; - - if (hash) { - $url.val(hash); - smartDraw(hash); - } else if (search) { - try { - var url = search - .split('?')[1] - .split('diff=')[1] - .split('&')[0]; - $url.val(url); - smartDraw(url); - } catch (_ignore) { - } + if (window.location.search) { + var url = getUrlFromSearch(window.location.search); + $url.val(url); + smartDraw(url); } bind(); @@ -492,6 +480,18 @@ $(document).ready(function() { smartDraw(); }); + function getUrlFromSearch(search) { + try { + return search + .split('?')[1] + .split(searchParam + '=')[1] + .split('&')[0]; + } catch (_ignore) { + } + + return null; + } + function bind() { $('#url-btn').click(function(e) { e.preventDefault(); @@ -617,12 +617,11 @@ $(document).ready(function() { } function updateUrl(url) { - if (window.history.pushState) { - window.history.pushState('', '/', 'url.html?diff=' + url); - } else { - window.location.hash = ''; - window.location.search = '?diff=' + url; - } + var currentUrl = getUrlFromSearch(window.location.search); + + if (currentUrl === url) return; + + window.location = 'demo.html?' + searchParam + '=' + url; } }); diff --git a/docs/url.min.js b/docs/demo.min.js similarity index 64% rename from docs/url.min.js rename to docs/demo.min.js index eb534de..dcbe699 100644 --- a/docs/url.min.js +++ b/docs/demo.min.js @@ -1 +1 @@ -!function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;o-1?upcased:method}function Request(input,options){options=options||{};var body=options.body;if(Request.prototype.isPrototypeOf(input)){if(input.bodyUsed)throw new TypeError("Already read");this.url=input.url,this.credentials=input.credentials,options.headers||(this.headers=new Headers(input.headers)),this.method=input.method,this.mode=input.mode,body||(body=input._bodyInit,input.bodyUsed=!0)}else this.url=input;if(this.credentials=options.credentials||this.credentials||"omit",(options.headers||!this.headers)&&(this.headers=new Headers(options.headers)),this.method=normalizeMethod(options.method||this.method||"GET"),this.mode=options.mode||this.mode||null,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&body)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(body)}function decode(body){var form=new FormData;return body.trim().split("&").forEach(function(bytes){if(bytes){var split=bytes.split("="),name=split.shift().replace(/\+/g," "),value=split.join("=").replace(/\+/g," ");form.append(decodeURIComponent(name),decodeURIComponent(value))}}),form}function headers(xhr){var head=new Headers,pairs=(xhr.getAllResponseHeaders()||"").trim().split("\n");return pairs.forEach(function(header){var split=header.trim().split(":"),key=split.shift().trim(),value=split.join(":").trim();head.append(key,value)}),head}function Response(bodyInit,options){options||(options={}),this.type="default",this.status=options.status,this.ok=this.status>=200&&this.status<300,this.statusText=options.statusText,this.headers=options.headers instanceof Headers?options.headers:new Headers(options.headers),this.url=options.url||"",this._initBody(bodyInit)}if(!self.fetch){var support={searchParams:"URLSearchParams"in self,iterable:"Symbol"in self&&"iterator"in Symbol,blob:"FileReader"in self&&"Blob"in self&&function(){try{return new Blob,!0}catch(e){return!1}}(),formData:"FormData"in self,arrayBuffer:"ArrayBuffer"in self};Headers.prototype.append=function(name,value){name=normalizeName(name),value=normalizeValue(value);var list=this.map[name];list||(list=[],this.map[name]=list),list.push(value)},Headers.prototype["delete"]=function(name){delete this.map[normalizeName(name)]},Headers.prototype.get=function(name){var values=this.map[normalizeName(name)];return values?values[0]:null},Headers.prototype.getAll=function(name){return this.map[normalizeName(name)]||[]},Headers.prototype.has=function(name){return this.map.hasOwnProperty(normalizeName(name))},Headers.prototype.set=function(name,value){this.map[normalizeName(name)]=[normalizeValue(value)]},Headers.prototype.forEach=function(callback,thisArg){Object.getOwnPropertyNames(this.map).forEach(function(name){this.map[name].forEach(function(value){callback.call(thisArg,value,name,this)},this)},this)},Headers.prototype.keys=function(){var items=[];return this.forEach(function(value,name){items.push(name)}),iteratorFor(items)},Headers.prototype.values=function(){var items=[];return this.forEach(function(value){items.push(value)}),iteratorFor(items)},Headers.prototype.entries=function(){var items=[];return this.forEach(function(value,name){items.push([name,value])}),iteratorFor(items)},support.iterable&&(Headers.prototype[Symbol.iterator]=Headers.prototype.entries);var methods=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];Request.prototype.clone=function(){return new Request(this)},Body.call(Request.prototype),Body.call(Response.prototype),Response.prototype.clone=function(){return new Response(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new Headers(this.headers),url:this.url})},Response.error=function(){var response=new Response(null,{status:0,statusText:""});return response.type="error",response};var redirectStatuses=[301,302,303,307,308];Response.redirect=function(url,status){if(-1===redirectStatuses.indexOf(status))throw new RangeError("Invalid status code");return new Response(null,{status:status,headers:{location:url}})},self.Headers=Headers,self.Request=Request,self.Response=Response,self.fetch=function(input,init){return new Promise(function(resolve,reject){function responseURL(){return"responseURL"in xhr?xhr.responseURL:/^X-Request-URL:/m.test(xhr.getAllResponseHeaders())?xhr.getResponseHeader("X-Request-URL"):void 0}var request;request=Request.prototype.isPrototypeOf(input)&&!init?input:new Request(input,init);var xhr=new XMLHttpRequest;xhr.onload=function(){var options={status:xhr.status,statusText:xhr.statusText,headers:headers(xhr),url:responseURL()},body="response"in xhr?xhr.response:xhr.responseText;resolve(new Response(body,options))},xhr.onerror=function(){reject(new TypeError("Network request failed"))},xhr.ontimeout=function(){reject(new TypeError("Network request failed"))},xhr.open(request.method,request.url,!0),"include"===request.credentials&&(xhr.withCredentials=!0),"responseType"in xhr&&support.blob&&(xhr.responseType="blob"),request.headers.forEach(function(value,name){xhr.setRequestHeader(name,value)}),xhr.send("undefined"==typeof request._bodyInit?null:request._bodyInit)})},self.fetch.polyfill=!0}}("undefined"!=typeof self?self:this)},{}],2:[function(require){$(document).ready(function(){function bind(){$("#url-btn").click(function(e){e.preventDefault();var url=$url.val();smartDraw(url)}),$url.on("paste",function(e){var url=e.originalEvent.clipboardData.getData("Text");smartDraw(url)})}function prepareUrl(url){function gitLabUrlGen(userName,projectName,type,value){return"https://crossorigin.me/https://gitlab.com/"+userName+"/"+projectName+"/"+type+"/"+value+".diff"}function gitHubUrlGen(userName,projectName,type,value){return headers.append("Accept","application/vnd.github.v3.diff"),"https://api.github.com/repos/"+userName+"/"+projectName+"/"+type+"/"+value}function bitbucketUrlGen(userName,projectName,type,value){var baseUrl="https://bitbucket.org/api/2.0/repositories/";return"pullrequests"===type?baseUrl+userName+"/"+projectName+"/pullrequests/"+value+"/diff":baseUrl+userName+"/"+projectName+"/diff/"+value}var fetchUrl,values,headers=new Headers,githubCommitUrl=/^https?:\/\/(?:www\.)?github\.com\/(.*?)\/(.*?)\/commit\/(.*?)(?:\.diff)?(?:\.patch)?(?:\/.*)?$/,githubPrUrl=/^https?:\/\/(?:www\.)?github\.com\/(.*?)\/(.*?)\/pull\/(.*?)(?:\.diff)?(?:\.patch)?(?:\/.*)?$/,gitlabCommitUrl=/^https?:\/\/(?:www\.)?gitlab\.com\/(.*?)\/(.*?)\/commit\/(.*?)(?:\.diff)?(?:\.patch)?(?:\/.*)?$/,gitlabPrUrl=/^https?:\/\/(?:www\.)?gitlab\.com\/(.*?)\/(.*?)\/merge_requests\/(.*?)(?:\.diff)?(?:\.patch)?(?:\/.*)?$/,bitbucketCommitUrl=/^https?:\/\/(?:www\.)?bitbucket\.org\/(.*?)\/(.*?)\/commits\/(.*?)(?:\/raw)?(?:\/.*)?$/,bitbucketPrUrl=/^https?:\/\/(?:www\.)?bitbucket\.org\/(.*?)\/(.*?)\/pull-requests\/(.*?)(?:\/.*)?$/;return(values=githubCommitUrl.exec(url))?fetchUrl=gitHubUrlGen(values[1],values[2],"commits",values[3]):(values=githubPrUrl.exec(url))?fetchUrl=gitHubUrlGen(values[1],values[2],"pulls",values[3]):(values=gitlabCommitUrl.exec(url))?fetchUrl=gitLabUrlGen(values[1],values[2],"commit",values[3]):(values=gitlabPrUrl.exec(url))?fetchUrl=gitLabUrlGen(values[1],values[2],"merge_requests",values[3]):(values=bitbucketCommitUrl.exec(url))?fetchUrl=bitbucketUrlGen(values[1],values[2],"commit",values[3]):(values=bitbucketPrUrl.exec(url))?fetchUrl=bitbucketUrlGen(values[1],values[2],"pullrequests",values[3]):(console.info("Could not parse url, using the provided url."),fetchUrl="https://crossorigin.me/"+url),{originalUrl:url,url:fetchUrl,headers:headers}}function smartDraw(urlOpt){var url=urlOpt||$url.val(),req=prepareUrl(url);draw(req)}function draw(req){if(!validateUrl(req.url))return void console.error("Invalid url provided!");validateUrl(req.originalUrl)&&updateUrl(req.originalUrl);var outputFormat=$outputFormat.val(),showFiles=$showFiles.is(":checked"),matching=$matching.val(),wordThreshold=$wordThreshold.val(),matchingMaxComparisons=$matchingMaxComparisons.val();fetch(req.url,{method:"GET",headers:req.headers,mode:"cors",cache:"default"}).then(function(res){return res.text()}).then(function(data){var container="#url-diff-container",diff2htmlUi=new Diff2HtmlUI({diff:data});$container.css("side-by-side"===outputFormat?{width:"100%"}:{width:""}),diff2htmlUi.draw(container,{outputFormat:outputFormat,showFiles:showFiles,matching:matching,matchWordsThreshold:wordThreshold,matchingMaxComparisons:matchingMaxComparisons,synchronisedScroll:!0}),diff2htmlUi.fileListCloseable(container,!1),diff2htmlUi.highlightCode(container)})}function validateUrl(url){return/^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})).?)(?::\d{2,5})?(?:[\/?#]\S*)?$/i.test(url)}function updateUrl(url){window.history.pushState?window.history.pushState("","/","url.html?diff="+url):(window.location.hash="",window.location.search="?diff="+url)}require("whatwg-fetch");var $container=$(".container"),$url=$("#url"),$outputFormat=$("#diff-url-options-output-format"),$showFiles=$("#diff-url-options-show-files"),$matching=$("#diff-url-options-matching"),$wordThreshold=$("#diff-url-options-match-words-threshold"),$matchingMaxComparisons=$("#diff-url-options-matching-max-comparisons"),hash=window.location.hash.replace(/^(#!?\/?)/,""),search=window.location.search;if(hash)$url.val(hash),smartDraw(hash);else if(search)try{var url=search.split("?")[1].split("diff=")[1].split("&")[0];$url.val(url),smartDraw(url)}catch(_ignore){}bind(),$outputFormat.add($showFiles).add($matching).add($wordThreshold).add($matchingMaxComparisons).change(function(){smartDraw()})})},{"whatwg-fetch":1}]},{},[2]); \ No newline at end of file +!function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;o-1?upcased:method}function Request(input,options){options=options||{};var body=options.body;if(Request.prototype.isPrototypeOf(input)){if(input.bodyUsed)throw new TypeError("Already read");this.url=input.url,this.credentials=input.credentials,options.headers||(this.headers=new Headers(input.headers)),this.method=input.method,this.mode=input.mode,body||(body=input._bodyInit,input.bodyUsed=!0)}else this.url=input;if(this.credentials=options.credentials||this.credentials||"omit",(options.headers||!this.headers)&&(this.headers=new Headers(options.headers)),this.method=normalizeMethod(options.method||this.method||"GET"),this.mode=options.mode||this.mode||null,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&body)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(body)}function decode(body){var form=new FormData;return body.trim().split("&").forEach(function(bytes){if(bytes){var split=bytes.split("="),name=split.shift().replace(/\+/g," "),value=split.join("=").replace(/\+/g," ");form.append(decodeURIComponent(name),decodeURIComponent(value))}}),form}function headers(xhr){var head=new Headers,pairs=(xhr.getAllResponseHeaders()||"").trim().split("\n");return pairs.forEach(function(header){var split=header.trim().split(":"),key=split.shift().trim(),value=split.join(":").trim();head.append(key,value)}),head}function Response(bodyInit,options){options||(options={}),this.type="default",this.status=options.status,this.ok=this.status>=200&&this.status<300,this.statusText=options.statusText,this.headers=options.headers instanceof Headers?options.headers:new Headers(options.headers),this.url=options.url||"",this._initBody(bodyInit)}if(!self.fetch){var support={searchParams:"URLSearchParams"in self,iterable:"Symbol"in self&&"iterator"in Symbol,blob:"FileReader"in self&&"Blob"in self&&function(){try{return new Blob,!0}catch(e){return!1}}(),formData:"FormData"in self,arrayBuffer:"ArrayBuffer"in self};Headers.prototype.append=function(name,value){name=normalizeName(name),value=normalizeValue(value);var list=this.map[name];list||(list=[],this.map[name]=list),list.push(value)},Headers.prototype["delete"]=function(name){delete this.map[normalizeName(name)]},Headers.prototype.get=function(name){var values=this.map[normalizeName(name)];return values?values[0]:null},Headers.prototype.getAll=function(name){return this.map[normalizeName(name)]||[]},Headers.prototype.has=function(name){return this.map.hasOwnProperty(normalizeName(name))},Headers.prototype.set=function(name,value){this.map[normalizeName(name)]=[normalizeValue(value)]},Headers.prototype.forEach=function(callback,thisArg){Object.getOwnPropertyNames(this.map).forEach(function(name){this.map[name].forEach(function(value){callback.call(thisArg,value,name,this)},this)},this)},Headers.prototype.keys=function(){var items=[];return this.forEach(function(value,name){items.push(name)}),iteratorFor(items)},Headers.prototype.values=function(){var items=[];return this.forEach(function(value){items.push(value)}),iteratorFor(items)},Headers.prototype.entries=function(){var items=[];return this.forEach(function(value,name){items.push([name,value])}),iteratorFor(items)},support.iterable&&(Headers.prototype[Symbol.iterator]=Headers.prototype.entries);var methods=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];Request.prototype.clone=function(){return new Request(this)},Body.call(Request.prototype),Body.call(Response.prototype),Response.prototype.clone=function(){return new Response(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new Headers(this.headers),url:this.url})},Response.error=function(){var response=new Response(null,{status:0,statusText:""});return response.type="error",response};var redirectStatuses=[301,302,303,307,308];Response.redirect=function(url,status){if(-1===redirectStatuses.indexOf(status))throw new RangeError("Invalid status code");return new Response(null,{status:status,headers:{location:url}})},self.Headers=Headers,self.Request=Request,self.Response=Response,self.fetch=function(input,init){return new Promise(function(resolve,reject){function responseURL(){return"responseURL"in xhr?xhr.responseURL:/^X-Request-URL:/m.test(xhr.getAllResponseHeaders())?xhr.getResponseHeader("X-Request-URL"):void 0}var request;request=Request.prototype.isPrototypeOf(input)&&!init?input:new Request(input,init);var xhr=new XMLHttpRequest;xhr.onload=function(){var options={status:xhr.status,statusText:xhr.statusText,headers:headers(xhr),url:responseURL()},body="response"in xhr?xhr.response:xhr.responseText;resolve(new Response(body,options))},xhr.onerror=function(){reject(new TypeError("Network request failed"))},xhr.ontimeout=function(){reject(new TypeError("Network request failed"))},xhr.open(request.method,request.url,!0),"include"===request.credentials&&(xhr.withCredentials=!0),"responseType"in xhr&&support.blob&&(xhr.responseType="blob"),request.headers.forEach(function(value,name){xhr.setRequestHeader(name,value)}),xhr.send("undefined"==typeof request._bodyInit?null:request._bodyInit)})},self.fetch.polyfill=!0}}("undefined"!=typeof self?self:this)},{}],2:[function(require){$(document).ready(function(){function getUrlFromSearch(search){try{return search.split("?")[1].split(searchParam+"=")[1].split("&")[0]}catch(_ignore){}return null}function bind(){$("#url-btn").click(function(e){e.preventDefault();var url=$url.val();smartDraw(url)}),$url.on("paste",function(e){var url=e.originalEvent.clipboardData.getData("Text");smartDraw(url)})}function prepareUrl(url){function gitLabUrlGen(userName,projectName,type,value){return"https://crossorigin.me/https://gitlab.com/"+userName+"/"+projectName+"/"+type+"/"+value+".diff"}function gitHubUrlGen(userName,projectName,type,value){return headers.append("Accept","application/vnd.github.v3.diff"),"https://api.github.com/repos/"+userName+"/"+projectName+"/"+type+"/"+value}function bitbucketUrlGen(userName,projectName,type,value){var baseUrl="https://bitbucket.org/api/2.0/repositories/";return"pullrequests"===type?baseUrl+userName+"/"+projectName+"/pullrequests/"+value+"/diff":baseUrl+userName+"/"+projectName+"/diff/"+value}var fetchUrl,values,headers=new Headers,githubCommitUrl=/^https?:\/\/(?:www\.)?github\.com\/(.*?)\/(.*?)\/commit\/(.*?)(?:\.diff)?(?:\.patch)?(?:\/.*)?$/,githubPrUrl=/^https?:\/\/(?:www\.)?github\.com\/(.*?)\/(.*?)\/pull\/(.*?)(?:\.diff)?(?:\.patch)?(?:\/.*)?$/,gitlabCommitUrl=/^https?:\/\/(?:www\.)?gitlab\.com\/(.*?)\/(.*?)\/commit\/(.*?)(?:\.diff)?(?:\.patch)?(?:\/.*)?$/,gitlabPrUrl=/^https?:\/\/(?:www\.)?gitlab\.com\/(.*?)\/(.*?)\/merge_requests\/(.*?)(?:\.diff)?(?:\.patch)?(?:\/.*)?$/,bitbucketCommitUrl=/^https?:\/\/(?:www\.)?bitbucket\.org\/(.*?)\/(.*?)\/commits\/(.*?)(?:\/raw)?(?:\/.*)?$/,bitbucketPrUrl=/^https?:\/\/(?:www\.)?bitbucket\.org\/(.*?)\/(.*?)\/pull-requests\/(.*?)(?:\/.*)?$/;return(values=githubCommitUrl.exec(url))?fetchUrl=gitHubUrlGen(values[1],values[2],"commits",values[3]):(values=githubPrUrl.exec(url))?fetchUrl=gitHubUrlGen(values[1],values[2],"pulls",values[3]):(values=gitlabCommitUrl.exec(url))?fetchUrl=gitLabUrlGen(values[1],values[2],"commit",values[3]):(values=gitlabPrUrl.exec(url))?fetchUrl=gitLabUrlGen(values[1],values[2],"merge_requests",values[3]):(values=bitbucketCommitUrl.exec(url))?fetchUrl=bitbucketUrlGen(values[1],values[2],"commit",values[3]):(values=bitbucketPrUrl.exec(url))?fetchUrl=bitbucketUrlGen(values[1],values[2],"pullrequests",values[3]):(console.info("Could not parse url, using the provided url."),fetchUrl="https://crossorigin.me/"+url),{originalUrl:url,url:fetchUrl,headers:headers}}function smartDraw(urlOpt){var url=urlOpt||$url.val(),req=prepareUrl(url);draw(req)}function draw(req){if(!validateUrl(req.url))return void console.error("Invalid url provided!");validateUrl(req.originalUrl)&&updateUrl(req.originalUrl);var outputFormat=$outputFormat.val(),showFiles=$showFiles.is(":checked"),matching=$matching.val(),wordThreshold=$wordThreshold.val(),matchingMaxComparisons=$matchingMaxComparisons.val();fetch(req.url,{method:"GET",headers:req.headers,mode:"cors",cache:"default"}).then(function(res){return res.text()}).then(function(data){var container="#url-diff-container",diff2htmlUi=new Diff2HtmlUI({diff:data});$container.css("side-by-side"===outputFormat?{width:"100%"}:{width:""}),diff2htmlUi.draw(container,{outputFormat:outputFormat,showFiles:showFiles,matching:matching,matchWordsThreshold:wordThreshold,matchingMaxComparisons:matchingMaxComparisons,synchronisedScroll:!0}),diff2htmlUi.fileListCloseable(container,!1),diff2htmlUi.highlightCode(container)})}function validateUrl(url){return/^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})).?)(?::\d{2,5})?(?:[\/?#]\S*)?$/i.test(url)}function updateUrl(url){var currentUrl=getUrlFromSearch(window.location.search);currentUrl!==url&&(window.location="demo.html?"+searchParam+"="+url)}require("whatwg-fetch");var searchParam="diff",$container=$(".container"),$url=$("#url"),$outputFormat=$("#diff-url-options-output-format"),$showFiles=$("#diff-url-options-show-files"),$matching=$("#diff-url-options-matching"),$wordThreshold=$("#diff-url-options-match-words-threshold"),$matchingMaxComparisons=$("#diff-url-options-matching-max-comparisons");if(window.location.search){var url=getUrlFromSearch(window.location.search);$url.val(url),smartDraw(url)}bind(),$outputFormat.add($showFiles).add($matching).add($wordThreshold).add($matchingMaxComparisons).change(function(){smartDraw()})})},{"whatwg-fetch":1}]},{},[2]); \ No newline at end of file diff --git a/docs/index.html b/docs/index.html index 9ed0381..efec149 100644 --- a/docs/index.html +++ b/docs/index.html @@ -72,7 +72,7 @@
  • - Demo + Demo
  • @@ -94,17 +94,17 @@

    Diff parser and pretty html generator

    Better diffs, unmatched reviews.

    -

    Demo

    +

    Demo

    - + - diff --git a/scripts/release-website.js b/scripts/release-website.js index d250843..5e51132 100644 --- a/scripts/release-website.js +++ b/scripts/release-website.js @@ -10,26 +10,47 @@ var websitePages = fs.readdirSync(root + '/pages'); var template = hogan.compile(readFile(root + '/template.mustache')); var options = { - 'url': { + 'all': { + 'demoUrl': 'demo.html?diff=https://github.com/rtfpessoa/diff2html/pull/106' + }, + 'demo': { 'extraClass': 'template-index-min' } }; websitePages.map(function(page) { - var pagePartial = readFile(pagesRoot + '/' + page + '/' + page + '.partial.html'); - var pageAssets = readFile(pagesRoot + '/' + page + '/' + page + '-assets.partial.html'); - var pageScripts = readFile(pagesRoot + '/' + page + '/' + page + '-scripts.partial.html'); + var pagePartialTemplate = hogan.compile(readFile(pagesRoot + '/' + page + '/' + page + '.partial.mustache')); + var pageAssetsTemplate = hogan.compile(readFile(pagesRoot + '/' + page + '/' + page + '-assets.partial.mustache')); + var pageScriptsTemplate = hogan.compile(readFile(pagesRoot + '/' + page + '/' + page + '-scripts.partial.mustache')); - var templateOptions = {assets: pageAssets, scripts: pageScripts, content: pagePartial}; + var templateOptions = {}; + + var key; + + // Allow the pages to share common options + var genericOptions = options['all'] || {}; + for (key in genericOptions) { + if (genericOptions.hasOwnProperty(key)) { + templateOptions[key] = genericOptions[key]; + } + } // Allow each page to have custom options var pageOptions = options[page] || {}; - for (var key in pageOptions) { + for (key in pageOptions) { if (pageOptions.hasOwnProperty(key)) { templateOptions[key] = pageOptions[key]; } } + var pagePartial = pagePartialTemplate.render(templateOptions); + var pageAssets = pageAssetsTemplate.render(templateOptions); + var pageScripts = pageScriptsTemplate.render(templateOptions); + + templateOptions.assets = pageAssets; + templateOptions.scripts = pageScripts; + templateOptions.content = pagePartial; + var pageHtml = template.render(templateOptions); writeFile('docs/' + page + '.html', pageHtml); }); diff --git a/scripts/release-website.sh b/scripts/release-website.sh index 2545cbd..e2f2ea2 100755 --- a/scripts/release-website.sh +++ b/scripts/release-website.sh @@ -8,12 +8,12 @@ set -e INPUT_DIR=website -INPUT_URL_JS=${INPUT_DIR}/templates/pages/url/url.js +INPUT_DEMO_JS=${INPUT_DIR}/templates/pages/demo/demo.js INPUT_CSS_FILE=${INPUT_DIR}/main.css OUTPUT_DIR=docs -OUTPUT_URL_JS=${OUTPUT_DIR}/url.js -OUTPUT_URL_MIN_JS=${OUTPUT_DIR}/url.min.js +OUTPUT_DEMO_JS=${OUTPUT_DIR}/demo.js +OUTPUT_DEMO_MIN_JS=${OUTPUT_DIR}/demo.min.js OUTPUT_CSS_FILE=${OUTPUT_DIR}/main.css OUTPUT_MIN_CSS_FILE=${OUTPUT_DIR}/main.min.css @@ -27,11 +27,11 @@ echo "Minifying ${OUTPUT_CSS_FILE} to ${OUTPUT_MIN_CSS_FILE}" postcss --use autoprefixer ${INPUT_CSS_FILE} -d ${OUTPUT_DIR} cleancss --advanced --compatibility=ie8 -o ${OUTPUT_MIN_CSS_FILE} ${OUTPUT_CSS_FILE} -echo "Generating website js aggregation file in ${OUTPUT_URL_JS}" -browserify -e ${INPUT_URL_JS} -o ${OUTPUT_URL_JS} +echo "Generating website js aggregation file in ${OUTPUT_DEMO_JS}" +browserify -e ${INPUT_DEMO_JS} -o ${OUTPUT_DEMO_JS} -echo "Minifying ${OUTPUT_URL_JS} to ${OUTPUT_URL_MIN_JS}" -uglifyjs ${OUTPUT_URL_JS} -c -o ${OUTPUT_URL_MIN_JS} +echo "Minifying ${OUTPUT_DEMO_JS} to ${OUTPUT_DEMO_MIN_JS}" +uglifyjs ${OUTPUT_DEMO_JS} -c -o ${OUTPUT_DEMO_MIN_JS} echo "Generating HTMLs from templates ..." node ./scripts/release-website.js diff --git a/website/templates/pages/url/url-assets.partial.html b/website/templates/pages/demo/demo-assets.partial.mustache similarity index 100% rename from website/templates/pages/url/url-assets.partial.html rename to website/templates/pages/demo/demo-assets.partial.mustache diff --git a/website/templates/pages/url/url-scripts.partial.html b/website/templates/pages/demo/demo-scripts.partial.mustache similarity index 86% rename from website/templates/pages/url/url-scripts.partial.html rename to website/templates/pages/demo/demo-scripts.partial.mustache index 99904f3..f09ae68 100644 --- a/website/templates/pages/url/url-scripts.partial.html +++ b/website/templates/pages/demo/demo-scripts.partial.mustache @@ -6,4 +6,4 @@ - + diff --git a/website/templates/pages/url/url.js b/website/templates/pages/demo/demo.js similarity index 92% rename from website/templates/pages/url/url.js rename to website/templates/pages/demo/demo.js index d023c18..4e97733 100644 --- a/website/templates/pages/url/url.js +++ b/website/templates/pages/demo/demo.js @@ -17,6 +17,8 @@ $(document).ready(function() { // Improves browser compatibility require('whatwg-fetch'); + var searchParam = 'diff'; + var $container = $('.container'); var $url = $('#url'); var $outputFormat = $('#diff-url-options-output-format'); @@ -25,24 +27,10 @@ $(document).ready(function() { var $wordThreshold = $('#diff-url-options-match-words-threshold'); var $matchingMaxComparisons = $('#diff-url-options-matching-max-comparisons'); - var hash = window.location.hash - .replace(/^(#!?\/?)/, ''); - - var search = window.location.search; - - if (hash) { - $url.val(hash); - smartDraw(hash); - } else if (search) { - try { - var url = search - .split('?')[1] - .split('diff=')[1] - .split('&')[0]; - $url.val(url); - smartDraw(url); - } catch (_ignore) { - } + if (window.location.search) { + var url = getUrlFromSearch(window.location.search); + $url.val(url); + smartDraw(url); } bind(); @@ -56,6 +44,18 @@ $(document).ready(function() { smartDraw(); }); + function getUrlFromSearch(search) { + try { + return search + .split('?')[1] + .split(searchParam + '=')[1] + .split('&')[0]; + } catch (_ignore) { + } + + return null; + } + function bind() { $('#url-btn').click(function(e) { e.preventDefault(); @@ -181,11 +181,10 @@ $(document).ready(function() { } function updateUrl(url) { - if (window.history.pushState) { - window.history.pushState('', '/', 'url.html?diff=' + url); - } else { - window.location.hash = ''; - window.location.search = '?diff=' + url; - } + var currentUrl = getUrlFromSearch(window.location.search); + + if (currentUrl === url) return; + + window.location = 'demo.html?' + searchParam + '=' + url; } }); diff --git a/website/templates/pages/url/url.partial.html b/website/templates/pages/demo/demo.partial.mustache similarity index 94% rename from website/templates/pages/url/url.partial.html rename to website/templates/pages/demo/demo.partial.mustache index f65c5b3..1797063 100644 --- a/website/templates/pages/url/url.partial.html +++ b/website/templates/pages/demo/demo.partial.mustache @@ -78,10 +78,8 @@ Can I send a custom url for a friend, colleague or co-worker?

    Just add a url parameter called diff to current url using as value your Commit, Pull Request, Merge Request, Diff or Patch url.

    -

    ex: https://diff2html.xyz/url?diff=https://github.com/rtfpessoa/diff2html/pull/106 +

    ex: https://diff2html.xyz/{{ demoUrl }}

    -

    You can also use an hashtag (# or #! or #!/) in the end of the url. - This will be overridden if you click any href id and for that reason not advised.

  • Why can't I paste a diff? diff --git a/website/templates/pages/index/index-scripts.partial.html b/website/templates/pages/index/index-scripts.partial.mustache similarity index 100% rename from website/templates/pages/index/index-scripts.partial.html rename to website/templates/pages/index/index-scripts.partial.mustache diff --git a/website/templates/pages/index/index.partial.html b/website/templates/pages/index/index.partial.mustache similarity index 98% rename from website/templates/pages/index/index.partial.html rename to website/templates/pages/index/index.partial.mustache index 399df5f..d029956 100644 --- a/website/templates/pages/index/index.partial.html +++ b/website/templates/pages/index/index.partial.mustache @@ -5,17 +5,17 @@

    Diff parser and pretty html generator

    Better diffs, unmatched reviews.

    -

    Demo

    +

    Demo

    - + - diff --git a/website/templates/template.mustache b/website/templates/template.mustache index 3bb95c5..4052c64 100644 --- a/website/templates/template.mustache +++ b/website/templates/template.mustache @@ -76,7 +76,7 @@
  • - Demo + Demo