From 736a8c9870090a9cdf77199e0b05e525960e267e Mon Sep 17 00:00:00 2001 From: Lauren Hamel Date: Sun, 27 Jan 2019 16:13:27 -0500 Subject: [PATCH] Updates viewer to allow better Prism highlighting Updates the `panels-viewer.js`, and thus `patternlab-viewer.js`, to improve the way code snippets are highlighted by Prism. This is part of the fix I alluded to for pattern-lab/plugin-node-tab#5. --- dist/styleguide/js/patternlab-viewer.js | 181 ++++++++++++++------ dist/styleguide/js/patternlab-viewer.min.js | 2 +- src/js/panels-viewer.js | 181 ++++++++++++++------ 3 files changed, 255 insertions(+), 109 deletions(-) diff --git a/dist/styleguide/js/patternlab-viewer.js b/dist/styleguide/js/patternlab-viewer.js index a63b40b..cd9716b 100644 --- a/dist/styleguide/js/patternlab-viewer.js +++ b/dist/styleguide/js/patternlab-viewer.js @@ -875,17 +875,17 @@ Dispatcher.trigger('setupPanels'); var panelsViewer = { // set up some defaults - targetOrigin: (window.location.protocol === 'file:') ? '*' : window.location.protocol+'//'+window.location.host, - initCopy: false, - initMoveTo: 0, + targetOrigin: (window.location.protocol === 'file:') ? '*' : window.location.protocol + '//' + window.location.host, + initCopy: false, + initMoveTo: 0, /** - * Check to see if all of the panels have been collected before rendering - * @param {String} the collected panels - * @param {String} the data from the pattern - * @param {Boolean} if this is going to be passed back to the styleguide - */ - checkPanels: function(panels, patternData, iframePassback, switchText) { + * Check to see if all of the panels have been collected before rendering + * @param {String} the collected panels + * @param {String} the data from the pattern + * @param {Boolean} if this is going to be passed back to the styleguide + */ + checkPanels: function (panels, patternData, iframePassback, switchText) { // count how many panels have rendered content var panelContentCount = 0; @@ -903,11 +903,11 @@ var panelsViewer = { }, /** - * Gather the panels related to the modal - * @param {String} the data from the pattern - * @param {Boolean} if this is going to be passed back to the styleguide - */ - gatherPanels: function(patternData, iframePassback, switchText) { + * Gather the panels related to the modal + * @param {String} the data from the pattern + * @param {Boolean} if this is going to be passed back to the styleguide + */ + gatherPanels: function (patternData, iframePassback, switchText) { Dispatcher.addListener('checkPanels', panelsViewer.checkPanels); @@ -921,11 +921,13 @@ var panelsViewer = { for (var i = 0; i < panels.length; ++i) { panel = panels[i]; - + + panel.index = i; + // catch pattern panel since it doesn't have a name defined by default if (panel.name === undefined) { panel.name = patternData.patternEngineName || patternData.patternExtension; - panel.httpRequestReplace = panel.httpRequestReplace+'.'+patternData.patternExtension; + panel.httpRequestReplace = panel.httpRequestReplace + '.' + patternData.patternExtension; panel.language = patternData.patternExtension; } @@ -935,27 +937,35 @@ var panelsViewer = { // need a file and then render var fileBase = urlHandler.getFileName(patternData.patternPartial, false); - var e = new XMLHttpRequest(); - e.onload = (function(i, panels, patternData, iframeRequest) { - return function() { - prismedContent = Prism.highlight(this.responseText, Prism.languages['html']); - template = document.getElementById(panels[i].templateID); - templateCompiled = Hogan.compile(template.innerHTML); - templateRendered = templateCompiled.render({ 'language': 'html', 'code': prismedContent }); - panels[i].content = templateRendered; + + panelsViewer.requestPanel(panel, 'GET', fileBase + panel.httpRequestReplace + '?' + (new Date()).getTime(), true) + + .then(function (response) { + + prismedContent = Prism.highlight(response.content, Prism.languages[response.panel.language] || Prism.languages.html); + template = document.getElementById(response.panel.templateID); + templateCompiled = Hogan.compile(template.innerHTML); + templateRendered = templateCompiled.render({ + 'language': 'html', + 'code': prismedContent + }); + panels[response.panel.index].content = templateRendered; Dispatcher.trigger('checkPanels', [panels, patternData, iframePassback, switchText]); - }; - })(i, panels, patternData, iframePassback); - - e.open('GET', fileBase+panel.httpRequestReplace+'?'+(new Date()).getTime(), true); - e.send(); + + }) + + .catch(function (error) { + + console.log('An error occurred while trying to load panel' + error.panel.name + '.'); + + }); } else { // vanilla render of pattern data - template = document.getElementById(panel.templateID); - templateCompiled = Hogan.compile(template.innerHTML); - templateRendered = templateCompiled.render(patternData); + template = document.getElementById(panel.templateID); + templateCompiled = Hogan.compile(template.innerHTML); + templateRendered = templateCompiled.render(patternData); panels[i].content = templateRendered; Dispatcher.trigger('checkPanels', [panels, patternData, iframePassback, switchText]); @@ -968,19 +978,71 @@ var panelsViewer = { }, /** - * Render the panels that have been collected - * @param {String} the collected panels - * @param {String} the data from the pattern - * @param {Boolean} if this is going to be passed back to the styleguide - */ - renderPanels: function(panels, patternData, iframePassback, switchText) { + * Request a panel's content via an httpRequest + * @param {Object} the target panel + * @param {String} the request method + * @param {String} the request address + * @param {Boolean} if the request should be async (default) or sync + */ + requestPanel: function (panel, method, url, async) { + + async = async ||true; + + return new Promise(function (resolve, reject) { + + var xhr = new XMLHttpRequest(); + + xhr.onload = function () { + + if (this.status >= 200 && this.status < 300) resolve({ + content: xhr.response, + panel: panel + }); + + else { + + reject({ + status: xhr.status, + statusText: xhr.statusText, + panel: panel + }); + } + + }; + + xhr.onerror = function () { + + reject({ + status: this.status, + statusText: xhr.statusText, + panel: panel + }); + + }; + + xhr.open(method, url, async); + + xhr.send(); + + }); + + }, + + + /** + * Render the panels that have been collected + * @param {String} the collected panels + * @param {String} the data from the pattern + * @param {Boolean} if this is going to be passed back to the styleguide + */ + renderPanels: function (panels, patternData, iframePassback, switchText) { // set-up defaults var template, templateCompiled, templateRendered; var annotation, comment, count, div, els, item, markup, i; var patternPartial = patternData.patternPartial; patternData.panels = panels; - + // set a default pattern description for modal pop-up if (!iframePassback && (patternData.patternDesc.length === 0)) { patternData.patternDesc = "This pattern doesn't have a description."; @@ -990,7 +1052,7 @@ var panelsViewer = { patternData.patternNameCaps = patternData.patternName.toUpperCase(); // check for annotations in the given mark-up - markup = document.createElement('div'); + markup = document.createElement('div'); markup.innerHTML = patternData.patternMarkup; count = 1; @@ -1000,10 +1062,15 @@ var panelsViewer = { for (i = 0; i < comments.comments.length; ++i) { item = comments.comments[i]; - els = markup.querySelectorAll(item.el); + els = markup.querySelectorAll(item.el); if (els.length > 0) { - annotation = { 'displayNumber': count, 'el': item.el, 'title': item.title, 'comment': item.comment }; + annotation = { + 'displayNumber': count, + 'el': item.el, + 'title': item.title, + 'comment': item.comment + }; patternData.annotations.push(annotation); count++; } @@ -1012,7 +1079,10 @@ var panelsViewer = { // alert the pattern that annotations should be highlighted if (patternData.annotations.length > 0) { - var obj = JSON.stringify({ 'event': 'patternLab.annotationsHighlightShow', 'annotations': patternData.annotations }); + var obj = JSON.stringify({ + 'event': 'patternLab.annotationsHighlightShow', + 'annotations': patternData.annotations + }); document.getElementById('sg-viewport').contentWindow.postMessage(obj, panelsViewer.targetOrigin); } @@ -1046,25 +1116,25 @@ var panelsViewer = { // figure out if pattern state should be drawn patternData.patternStateExists = (patternData.patternState.length > 0); - + // figure if annotations should be drawn patternData.annotationExists = (patternData.annotations.length > 0); - + // figure if the entire desc block should be drawn patternData.descBlockExists = (patternData.patternDescExists || patternData.lineageExists || patternData.lineageRExists || patternData.patternStateExists || patternData.annotationExists); - + // set isPatternView based on if we have to pass it back to the styleguide level patternData.isPatternView = (iframePassback === false); // render all of the panels in the base panel template - template = document.getElementById('pl-panel-template-base'); + template = document.getElementById('pl-panel-template-base'); templateCompiled = Hogan.compile(template.innerHTML); templateRendered = templateCompiled.render(patternData); // make sure templateRendered is modified to be an HTML element - div = document.createElement('div'); - div.className = 'sg-modal-content-inner'; - div.innerHTML = templateRendered; + div = document.createElement('div'); + div.className = 'sg-modal-content-inner'; + div.innerHTML = templateRendered; templateRendered = div; // add click events @@ -1076,8 +1146,8 @@ var panelsViewer = { panel = panels[i]; // default IDs - panelTab = '#sg-'+patternPartial+'-'+panel.id+'-tab'; - panelBlock = '#sg-'+patternPartial+'-'+panel.id+'-panel'; + panelTab = '#sg-' + patternPartial + '-' + panel.id + '-tab'; + panelBlock = '#sg-' + patternPartial + '-' + panel.id + '-panel'; // show default options if ((templateRendered.querySelector(panelTab) !== null) && (panel.default)) { @@ -1088,9 +1158,12 @@ var panelsViewer = { } // find lineage links in the rendered content and add postmessage handlers in case it's in the modal - $('#sg-code-lineage-fill a, #sg-code-lineager-fill a', templateRendered).on('click', function(e){ + $('#sg-code-lineage-fill a, #sg-code-lineager-fill a', templateRendered).on('click', function (e) { e.preventDefault(); - var obj = JSON.stringify({ 'event': 'patternLab.updatePath', 'path': urlHandler.getFileName($(this).attr('data-patternpartial')) }); + var obj = JSON.stringify({ + 'event': 'patternLab.updatePath', + 'path': urlHandler.getFileName($(this).attr('data-patternpartial')) + }); document.getElementById('sg-viewport').contentWindow.postMessage(obj, panelsViewer.targetOrigin); }); diff --git a/dist/styleguide/js/patternlab-viewer.min.js b/dist/styleguide/js/patternlab-viewer.min.js index e39b67d..b3ce267 100644 --- a/dist/styleguide/js/patternlab-viewer.min.js +++ b/dist/styleguide/js/patternlab-viewer.min.js @@ -1 +1 @@ -function receiveIframeMessage(e){if("file:"==window.location.protocol||e.origin===window.location.protocol+"//"+window.location.host){var t,n={};try{n="string"!=typeof e.data?e.data:JSON.parse(e.data)}catch(a){}if(void 0!==n.event&&"patternLab.updatePath"==n.event)if(void 0!==patternData.patternPartial){var i=/(patterns|snapshots)\/(.*)$/;t=window.location.protocol+"//"+window.location.host+window.location.pathname.replace(i,"")+n.path+"?"+Date.now(),window.location.replace(t)}else t=window.location.protocol+"//"+window.location.host+window.location.pathname.replace("styleguide/html/styleguide.html","")+n.path+"?"+Date.now(),window.location.replace(t);else void 0!==n.event&&"patternLab.reload"==n.event&&window.location.reload()}}!function(e,t,n){function a(e){return e}function i(e){return decodeURIComponent(e.replace(o," "))}var o=/\+/g,r=e.cookie=function(o,l,s){if(l!==n){if(s=e.extend({},r.defaults,s),null===l&&(s.expires=-1),"number"==typeof s.expires){var d=s.expires,c=s.expires=new Date;c.setDate(c.getDate()+d)}return l=r.json?JSON.stringify(l):String(l),t.cookie=[encodeURIComponent(o),"=",r.raw?l:encodeURIComponent(l),s.expires?"; expires="+s.expires.toUTCString():"",s.path?"; path="+s.path:"",s.domain?"; domain="+s.domain:"",s.secure?"; secure":""].join("")}for(var p=r.raw?a:i,g=t.cookie.split("; "),u=0,f=g.length;u0?"|"+o[0]+"~"+o[1]:o[0]+"~"+o[1]}$.cookie(this.cookieName,n)}else this.addValue(e,t)},removeValue:function(e){for(var t="",n=$.cookie(this.cookieName).split("|"),a=0,i=0;i1)for(var t,n=0,a=e.substr(1).split("&");n1?unescape(t[1]):""}(window.location.search);return e},pushPattern:function(e,t){var n={pattern:e},a=urlHandler.getFileName(e),i=window.location.pathname;i="file"===window.location.protocol?i.replace("/public/index.html","public/"):i.replace(/\/index\.html/,"/");var o=window.location.protocol+"//"+window.location.host+i+a;if(t!=o){var r=JSON.stringify({event:"patternLab.updatePath",path:a});document.getElementById("sg-viewport").contentWindow.postMessage(r,urlHandler.targetOrigin)}else{var l="file:"==window.location.protocol?null:window.location.protocol+"//"+window.location.host+window.location.pathname.replace("index.html","")+"?p="+e;void 0!==history.pushState&&history.pushState(n,null,l),document.getElementById("title").innerHTML="Pattern Lab - "+e,null!==document.getElementById("sg-raw")&&document.getElementById("sg-raw").setAttribute("href",urlHandler.getFileName(e))}},popPattern:function(e){var t,n=e.state;if(null===n)return void(this.skipBack=!1);null!==n&&(t=n.pattern);var a="";a=this.getFileName(t),""===a&&(a="styleguide/html/styleguide.html");var i=JSON.stringify({event:"patternLab.updatePath",path:a});document.getElementById("sg-viewport").contentWindow.postMessage(i,urlHandler.targetOrigin),document.getElementById("title").innerHTML="Pattern Lab - "+t,null!==document.getElementById("sg-raw")&&document.getElementById("sg-raw").setAttribute("href",urlHandler.getFileName(t))}};window.onpopstate=function(e){urlHandler.skipBack=!0,urlHandler.popPattern(e)};var modalViewer={active:!1,switchText:!0,template:"info",patternData:{},targetOrigin:"file:"===window.location.protocol?"*":window.location.protocol+"//"+window.location.host,onReady:function(){Dispatcher.addListener("insertPanels",modalViewer.insert),$(window).on("resize",function(){"false"===DataSaver.findValue("modalActive")&&modalViewer.slide($("#sg-modal-container").outerHeight())}),$("#sg-t-patterninfo").click(function(e){e.preventDefault(),$("#sg-tools-toggle").removeClass("active"),$(this).parents("ul").removeClass("active"),modalViewer.toggle()}),$("#sg-modal-close-btn").on("click",function(e){e.preventDefault(),obj=JSON.stringify({event:"patternLab.annotationsHighlightHide"}),document.getElementById("sg-viewport").contentWindow.postMessage(obj,modalViewer.targetOrigin),modalViewer.close()}),"true"===DataSaver.findValue("modalActive")&&(modalViewer.active=!0,$("#sg-t-patterninfo").html("Hide Pattern Info")),modalViewer.hide();var e=urlHandler.getRequestVars();void 0===e.view||"code"!==e.view&&"c"!==e.view||modalViewer.queryPattern(),void 0===e.view||"annotations"!==e.view&&"a"!==e.view||modalViewer.queryPattern()},toggle:function(){modalViewer.active===!1?modalViewer.queryPattern():(obj=JSON.stringify({event:"patternLab.annotationsHighlightHide"}),document.getElementById("sg-viewport").contentWindow.postMessage(obj,modalViewer.targetOrigin),modalViewer.close())},open:function(){modalViewer.close(),DataSaver.updateValue("modalActive","true"),modalViewer.active=!0,$("#sg-t-"+modalViewer.template+" .sg-checkbox").addClass("active"),$("#sg-modal-container").addClass("active"),modalViewer.show()},close:function(){var e;DataSaver.updateValue("modalActive","false"),modalViewer.active=!1,$("#sg-modal-container").removeClass("active"),$(".sg-checkbox").removeClass("active"),modalViewer.hide(),$("#sg-t-patterninfo").html("Show Pattern Info"),e=JSON.stringify({event:"patternLab.patternModalClose"}),document.getElementById("sg-viewport").contentWindow.postMessage(e,modalViewer.targetOrigin)},hide:function(){modalViewer.slide($("#sg-modal-container").outerHeight()+30)},insert:function(e,t,n,a){if(n){var i=JSON.stringify({event:"patternLab.patternModalInsert",patternPartial:t,modalContent:e.outerHTML});document.getElementById("sg-viewport").contentWindow.postMessage(i,modalViewer.targetOrigin)}else $("#sg-modal-content").html(e),modalViewer.open();a===!0&&$("#sg-t-patterninfo").html("Hide Pattern Info")},refresh:function(e,t,n){t&&modalViewer.hide(),panelsViewer.gatherPanels(e,t,n)},slide:function(e){e=0===e?0:-e,$("#sg-modal-container").css("bottom",e)},slideToAnnotation:function(e){for(els=document.querySelectorAll("#sg-annotations > .sg-annotations-list > li"),i=0;i0&&(l={displayNumber:s,el:p.el,title:p.title,comment:p.comment},t.annotations.push(l),s++);if(t.annotations.length>0){var h=JSON.stringify({event:"patternLab.annotationsHighlightShow",annotations:t.annotations});document.getElementById("sg-viewport").contentWindow.postMessage(h,panelsViewer.targetOrigin)}if(t.lineage.length>0)for(u=0;u0)for(u=0;u0||void 0!==t.patternDescAdditions&&t.patternDescAdditions.length>0,t.lineageExists=0!==t.lineage.length,t.lineageRExists=0!==t.lineageR.length,t.patternStateExists=t.patternState.length>0,t.annotationExists=t.annotations.length>0,t.descBlockExists=t.patternDescExists||t.lineageExists||t.lineageRExists||t.patternStateExists||t.annotationExists,t.isPatternView=n===!1,i=document.getElementById("pl-panel-template-base"),o=Hogan.compile(i.innerHTML),r=o.render(t),d=document.createElement("div"),d.className="sg-modal-content-inner",d.innerHTML=r,r=d,r=panelsUtil.addClickEvents(r,f),u=0;uk?k:ex?P:x}var b=14,V=$("#sg-viewport"),I=$(".sg-size-px"),S=$(".sg-size-em"),D=void 0!==config.ishFontSize?parseInt(config.ishFontSize):parseInt($("body").css("font-size")),E=$(".sg-header").height(),M=!1,L=!1,C=!0,H=!1;$(e).resize(function(){v=document.body.clientWidth,w=$(document).height(),t(),C===!0&&c(v,!1)}),$(".sg-acc-handle").on("click",function(e){e.preventDefault();var n=$(this),a=n.next(".sg-acc-panel"),i=n.parent().parent().hasClass("sg-acc-panel");i||($(".sg-acc-handle").not(n).removeClass("active"),$(".sg-acc-panel").not(a).removeClass("active")),n.toggleClass("active"),a.toggleClass("active"),t()}),$(".sg-nav-toggle").on("click",function(e){e.preventDefault(),$(".sg-nav-container").toggleClass("active")}),$("#sg-t-toggle").on("click",function(e){e.preventDefault(),$(this).parents("ul").toggleClass("active")}),$("#sg-size-toggle").on("click",function(e){e.preventDefault(),$(this).parents("ul").toggleClass("active")}),$(".sg-size[data-size]").on("click",function(e){e.preventDefault(),r(),s(),C=!1;var t=$(this).attr("data-size");t.indexOf("px")>-1&&(D=1),t=t.replace(/[^\d.-]/g,""),c(Math.floor(t*D))}),$("#sg-size-s").on("click",function(e){e.preventDefault(),n()}),jwerty.key("ctrl+shift+s",function(e){return n(),!1}),$("#sg-size-m").on("click",function(e){e.preventDefault(),a()}),jwerty.key("ctrl+shift+m",function(e){return i(),!1}),$("#sg-size-l").on("click",function(e){e.preventDefault(),i()}),jwerty.key("ctrl+shift+l",function(e){return i(),!1}),$("#sg-size-full").on("click",function(e){e.preventDefault(),r(),s(),C=!0,c(v)}),$("#sg-size-random").on("click",function(e){e.preventDefault(),r(),s(),C=!1,c(u(y,v))}),$("#sg-size-disco").on("click",function(e){e.preventDefault(),s(),C=!1,L?r():l()}),jwerty.key("ctrl+shift+d",function(e){return L?r():l(),!1}),$("#sg-size-hay").on("click",function(e){e.preventDefault(),r(),H?s():d()}),jwerty.key("ctrl+shift+h",function(e){H?s():d()}),I.on("keydown",function(e){var t=Math.floor($(this).val());38===e.keyCode?(t++,c(t,!1)):40===e.keyCode?(t--,c(t,!1)):13===e.keyCode&&(e.preventDefault(),c(t),$(this).blur())}),I.on("keyup",function(){var e=Math.floor($(this).val());g(e,"px","updateEmInput")}),S.on("keydown",function(e){var t=parseFloat($(this).val());38===e.keyCode?(t++,c(Math.floor(t*D),!1)):40===e.keyCode?(t--,c(Math.floor(t*D),!1)):13===e.keyCode&&(e.preventDefault(),c(Math.floor(t*D)))}),S.on("keyup",function(){var e=parseFloat($(this).val());g(e,"em","updatePxInput")}),jwerty.key("ctrl+shift+0",function(e){return e.preventDefault(),c(320,!0),!1});var N=[];$("#sg-mq a").each(function(e){N.push($(this).html()),$(this).on("click",function(e,t){return function(e){e.preventDefault();var n=$(t).html(),a=n.indexOf("px")!==-1?"px":"em";n=n.replace(a,"");var i="px"===a?1*n:n*D;c(i,!0)}}(e,this)),jwerty.key("ctrl+shift+"+(e+1),function(e){return function(t){var n=$(e).html(),a=n.indexOf("px")!==-1?"px":"em";n=n.replace(a,"");var i="px"===a?1*n:n*D;return c(i,!0),!1}}(this))}),$("#sg-gen-container").on("transitionend webkitTransitionEnd",function(e){var t="file:"===window.location.protocol?"*":window.location.protocol+"//"+window.location.host,n=JSON.stringify({event:"patternLab.resize",resize:"true"});document.getElementById("sg-viewport").contentWindow.postMessage(n,t)}),$("#sg-gen-container").on("touchstart",function(e){}),$("#sg-rightpull").mousedown(function(e){var t=e.clientX,n=V.width();return C=!1,$("#sg-cover").css("display","block"),$("#sg-cover").mousemove(function(e){var a;a=n+2*(e.clientX-t),a>y&&(DataSaver.findValue("vpWidth")?DataSaver.updateValue("vpWidth",a):DataSaver.addValue("vpWidth",a),c(a,!1))}),!1}),$("body").mouseup(function(){$("#sg-cover").unbind("mousemove"),$("#sg-cover").css("display","none")});var F=$("#sg-viewport").width();$("#sg-gen-container").width(F);var O=screen.width;void 0!==window.orientation&&(O=0===window.orientation?screen.width:screen.height),$(window).width()==O&&"ontouchstart"in document.documentElement&&$(window).width()<=1024?$("#sg-rightpull-container").width(0):$("#sg-viewport").width(F-14),g($("#sg-viewport").width());var B=urlHandler.getRequestVars(),R=0,T=!0;void 0!==B.h||void 0!==B.hay?d():void 0!==B.d||void 0!==B.disco?l():void 0!==B.w||void 0!==B.width?(R=void 0!==B.w?B.w:B.width,R=R.indexOf("em")!==-1?Math.floor(Math.floor(R.replace("em",""))*D):Math.floor(R.replace("px","")),DataSaver.updateValue("vpWidth",R),f(R)):T&&(R=DataSaver.findValue("vpWidth"))&&f(R);var q=window.location.protocol+"//"+window.location.host+window.location.pathname.replace("index.html",""),z=void 0!==config.defaultPattern&&"string"==typeof config.defaultPattern&&config.defaultPattern.trim().length>0?config.defaultPattern:"all",A=q+"styleguide/html/styleguide.html?"+Date.now();if(void 0===B.p&&void 0===B.pattern||(z=void 0!==B.p?B.p:B.pattern),"all"!==z&&(patternPath=urlHandler.getFileName(z),A=""!==patternPath?q+patternPath+"?"+Date.now():A,document.getElementById("title").innerHTML="Pattern Lab - "+z,history.replaceState({pattern:z},null,null)),null!==document.getElementById("sg-raw")&&document.getElementById("sg-raw").setAttribute("href",urlHandler.getFileName(z)),urlHandler.skipBack=!0,document.getElementById("sg-viewport").contentWindow.location.replace(A),$("a[data-patternpartial]").on("click",function(e){e.preventDefault();var t=JSON.stringify({event:"patternLab.updatePath",path:urlHandler.getFileName($(this).attr("data-patternpartial"))});document.getElementById("sg-viewport").contentWindow.postMessage(t,urlHandler.targetOrigin),h()}),$("#sg-vp-wrap").click(function(){h()}),void 0!==window.orientation){var W=window.orientation;window.addEventListener("orientationchange",function(){window.orientation!=W&&($("#sg-gen-container").width($(window).width()),$("#sg-viewport").width($(window).width()),g($(window).width()),W=window.orientation)},!1)}window.addEventListener("message",m,!1)}(this);var pluginLoader={init:function(){for(var s,t,l,c,n,i=0;i0?"|"+o[0]+"~"+o[1]:o[0]+"~"+o[1]}$.cookie(this.cookieName,n)}else this.addValue(e,t)},removeValue:function(e){for(var t="",n=$.cookie(this.cookieName).split("|"),a=0,i=0;i1)for(var t,n=0,a=e.substr(1).split("&");n1?unescape(t[1]):""}(window.location.search);return e},pushPattern:function(e,t){var n={pattern:e},a=urlHandler.getFileName(e),i=window.location.pathname;i="file"===window.location.protocol?i.replace("/public/index.html","public/"):i.replace(/\/index\.html/,"/");var o=window.location.protocol+"//"+window.location.host+i+a;if(t!=o){var r=JSON.stringify({event:"patternLab.updatePath",path:a});document.getElementById("sg-viewport").contentWindow.postMessage(r,urlHandler.targetOrigin)}else{var l="file:"==window.location.protocol?null:window.location.protocol+"//"+window.location.host+window.location.pathname.replace("index.html","")+"?p="+e;void 0!==history.pushState&&history.pushState(n,null,l),document.getElementById("title").innerHTML="Pattern Lab - "+e,null!==document.getElementById("sg-raw")&&document.getElementById("sg-raw").setAttribute("href",urlHandler.getFileName(e))}},popPattern:function(e){var t,n=e.state;if(null===n)return void(this.skipBack=!1);null!==n&&(t=n.pattern);var a="";a=this.getFileName(t),""===a&&(a="styleguide/html/styleguide.html");var i=JSON.stringify({event:"patternLab.updatePath",path:a});document.getElementById("sg-viewport").contentWindow.postMessage(i,urlHandler.targetOrigin),document.getElementById("title").innerHTML="Pattern Lab - "+t,null!==document.getElementById("sg-raw")&&document.getElementById("sg-raw").setAttribute("href",urlHandler.getFileName(t))}};window.onpopstate=function(e){urlHandler.skipBack=!0,urlHandler.popPattern(e)};var modalViewer={active:!1,switchText:!0,template:"info",patternData:{},targetOrigin:"file:"===window.location.protocol?"*":window.location.protocol+"//"+window.location.host,onReady:function(){Dispatcher.addListener("insertPanels",modalViewer.insert),$(window).on("resize",function(){"false"===DataSaver.findValue("modalActive")&&modalViewer.slide($("#sg-modal-container").outerHeight())}),$("#sg-t-patterninfo").click(function(e){e.preventDefault(),$("#sg-tools-toggle").removeClass("active"),$(this).parents("ul").removeClass("active"),modalViewer.toggle()}),$("#sg-modal-close-btn").on("click",function(e){e.preventDefault(),obj=JSON.stringify({event:"patternLab.annotationsHighlightHide"}),document.getElementById("sg-viewport").contentWindow.postMessage(obj,modalViewer.targetOrigin),modalViewer.close()}),"true"===DataSaver.findValue("modalActive")&&(modalViewer.active=!0,$("#sg-t-patterninfo").html("Hide Pattern Info")),modalViewer.hide();var e=urlHandler.getRequestVars();void 0===e.view||"code"!==e.view&&"c"!==e.view||modalViewer.queryPattern(),void 0===e.view||"annotations"!==e.view&&"a"!==e.view||modalViewer.queryPattern()},toggle:function(){modalViewer.active===!1?modalViewer.queryPattern():(obj=JSON.stringify({event:"patternLab.annotationsHighlightHide"}),document.getElementById("sg-viewport").contentWindow.postMessage(obj,modalViewer.targetOrigin),modalViewer.close())},open:function(){modalViewer.close(),DataSaver.updateValue("modalActive","true"),modalViewer.active=!0,$("#sg-t-"+modalViewer.template+" .sg-checkbox").addClass("active"),$("#sg-modal-container").addClass("active"),modalViewer.show()},close:function(){var e;DataSaver.updateValue("modalActive","false"),modalViewer.active=!1,$("#sg-modal-container").removeClass("active"),$(".sg-checkbox").removeClass("active"),modalViewer.hide(),$("#sg-t-patterninfo").html("Show Pattern Info"),e=JSON.stringify({event:"patternLab.patternModalClose"}),document.getElementById("sg-viewport").contentWindow.postMessage(e,modalViewer.targetOrigin)},hide:function(){modalViewer.slide($("#sg-modal-container").outerHeight()+30)},insert:function(e,t,n,a){if(n){var i=JSON.stringify({event:"patternLab.patternModalInsert",patternPartial:t,modalContent:e.outerHTML});document.getElementById("sg-viewport").contentWindow.postMessage(i,modalViewer.targetOrigin)}else $("#sg-modal-content").html(e),modalViewer.open();a===!0&&$("#sg-t-patterninfo").html("Hide Pattern Info")},refresh:function(e,t,n){t&&modalViewer.hide(),panelsViewer.gatherPanels(e,t,n)},slide:function(e){e=0===e?0:-e,$("#sg-modal-container").css("bottom",e)},slideToAnnotation:function(e){for(els=document.querySelectorAll("#sg-annotations > .sg-annotations-list > li"),i=0;i=200&&this.status<300?i({content:r.response,panel:e}):o({status:r.status,statusText:r.statusText,panel:e})},r.onerror=function(){o({status:this.status,statusText:r.statusText,panel:e})},r.open(t,n,a),r.send()})},renderPanels:function(e,t,n,a){var i,o,r,l,s,d,c,p,g,u,f=t.patternPartial;for(t.panels=e,n||0!==t.patternDesc.length||(t.patternDesc="This pattern doesn't have a description."),t.patternNameCaps=t.patternName.toUpperCase(),g=document.createElement("div"),g.innerHTML=t.patternMarkup,s=1,t.annotations=[],delete t.patternMarkup,u=0;u0&&(l={displayNumber:s,el:p.el,title:p.title,comment:p.comment},t.annotations.push(l),s++);if(t.annotations.length>0){var h=JSON.stringify({event:"patternLab.annotationsHighlightShow",annotations:t.annotations});document.getElementById("sg-viewport").contentWindow.postMessage(h,panelsViewer.targetOrigin)}if(t.lineage.length>0)for(u=0;u0)for(u=0;u0||void 0!==t.patternDescAdditions&&t.patternDescAdditions.length>0,t.lineageExists=0!==t.lineage.length,t.lineageRExists=0!==t.lineageR.length,t.patternStateExists=t.patternState.length>0,t.annotationExists=t.annotations.length>0,t.descBlockExists=t.patternDescExists||t.lineageExists||t.lineageRExists||t.patternStateExists||t.annotationExists,t.isPatternView=n===!1,i=document.getElementById("pl-panel-template-base"),o=Hogan.compile(i.innerHTML),r=o.render(t),d=document.createElement("div"),d.className="sg-modal-content-inner",d.innerHTML=r,r=d,r=panelsUtil.addClickEvents(r,f),u=0;uk?k:ex?P:x}var b=14,V=$("#sg-viewport"),I=$(".sg-size-px"),S=$(".sg-size-em"),D=void 0!==config.ishFontSize?parseInt(config.ishFontSize):parseInt($("body").css("font-size")),E=$(".sg-header").height(),M=!1,L=!1,C=!0,H=!1;$(e).resize(function(){v=document.body.clientWidth,w=$(document).height(),t(),C===!0&&c(v,!1)}),$(".sg-acc-handle").on("click",function(e){e.preventDefault();var n=$(this),a=n.next(".sg-acc-panel"),i=n.parent().parent().hasClass("sg-acc-panel");i||($(".sg-acc-handle").not(n).removeClass("active"),$(".sg-acc-panel").not(a).removeClass("active")),n.toggleClass("active"),a.toggleClass("active"),t()}),$(".sg-nav-toggle").on("click",function(e){e.preventDefault(),$(".sg-nav-container").toggleClass("active")}),$("#sg-t-toggle").on("click",function(e){e.preventDefault(),$(this).parents("ul").toggleClass("active")}),$("#sg-size-toggle").on("click",function(e){e.preventDefault(),$(this).parents("ul").toggleClass("active")}),$(".sg-size[data-size]").on("click",function(e){e.preventDefault(),r(),s(),C=!1;var t=$(this).attr("data-size");t.indexOf("px")>-1&&(D=1),t=t.replace(/[^\d.-]/g,""),c(Math.floor(t*D))}),$("#sg-size-s").on("click",function(e){e.preventDefault(),n()}),jwerty.key("ctrl+shift+s",function(e){return n(),!1}),$("#sg-size-m").on("click",function(e){e.preventDefault(),a()}),jwerty.key("ctrl+shift+m",function(e){return i(),!1}),$("#sg-size-l").on("click",function(e){e.preventDefault(),i()}),jwerty.key("ctrl+shift+l",function(e){return i(),!1}),$("#sg-size-full").on("click",function(e){e.preventDefault(),r(),s(),C=!0,c(v)}),$("#sg-size-random").on("click",function(e){e.preventDefault(),r(),s(),C=!1,c(u(y,v))}),$("#sg-size-disco").on("click",function(e){e.preventDefault(),s(),C=!1,L?r():l()}),jwerty.key("ctrl+shift+d",function(e){return L?r():l(),!1}),$("#sg-size-hay").on("click",function(e){e.preventDefault(),r(),H?s():d()}),jwerty.key("ctrl+shift+h",function(e){H?s():d()}),I.on("keydown",function(e){var t=Math.floor($(this).val());38===e.keyCode?(t++,c(t,!1)):40===e.keyCode?(t--,c(t,!1)):13===e.keyCode&&(e.preventDefault(),c(t),$(this).blur())}),I.on("keyup",function(){var e=Math.floor($(this).val());g(e,"px","updateEmInput")}),S.on("keydown",function(e){var t=parseFloat($(this).val());38===e.keyCode?(t++,c(Math.floor(t*D),!1)):40===e.keyCode?(t--,c(Math.floor(t*D),!1)):13===e.keyCode&&(e.preventDefault(),c(Math.floor(t*D)))}),S.on("keyup",function(){var e=parseFloat($(this).val());g(e,"em","updatePxInput")}),jwerty.key("ctrl+shift+0",function(e){return e.preventDefault(),c(320,!0),!1});var N=[];$("#sg-mq a").each(function(e){N.push($(this).html()),$(this).on("click",function(e,t){return function(e){e.preventDefault();var n=$(t).html(),a=n.indexOf("px")!==-1?"px":"em";n=n.replace(a,"");var i="px"===a?1*n:n*D;c(i,!0)}}(e,this)),jwerty.key("ctrl+shift+"+(e+1),function(e){return function(t){var n=$(e).html(),a=n.indexOf("px")!==-1?"px":"em";n=n.replace(a,"");var i="px"===a?1*n:n*D;return c(i,!0),!1}}(this))}),$("#sg-gen-container").on("transitionend webkitTransitionEnd",function(e){var t="file:"===window.location.protocol?"*":window.location.protocol+"//"+window.location.host,n=JSON.stringify({event:"patternLab.resize",resize:"true"});document.getElementById("sg-viewport").contentWindow.postMessage(n,t)}),$("#sg-gen-container").on("touchstart",function(e){}),$("#sg-rightpull").mousedown(function(e){var t=e.clientX,n=V.width();return C=!1,$("#sg-cover").css("display","block"),$("#sg-cover").mousemove(function(e){var a;a=n+2*(e.clientX-t),a>y&&(DataSaver.findValue("vpWidth")?DataSaver.updateValue("vpWidth",a):DataSaver.addValue("vpWidth",a),c(a,!1))}),!1}),$("body").mouseup(function(){$("#sg-cover").unbind("mousemove"),$("#sg-cover").css("display","none")});var F=$("#sg-viewport").width();$("#sg-gen-container").width(F);var O=screen.width;void 0!==window.orientation&&(O=0===window.orientation?screen.width:screen.height),$(window).width()==O&&"ontouchstart"in document.documentElement&&$(window).width()<=1024?$("#sg-rightpull-container").width(0):$("#sg-viewport").width(F-14),g($("#sg-viewport").width());var B=urlHandler.getRequestVars(),R=0,T=!0;void 0!==B.h||void 0!==B.hay?d():void 0!==B.d||void 0!==B.disco?l():void 0!==B.w||void 0!==B.width?(R=void 0!==B.w?B.w:B.width,R=R.indexOf("em")!==-1?Math.floor(Math.floor(R.replace("em",""))*D):Math.floor(R.replace("px","")),DataSaver.updateValue("vpWidth",R),f(R)):T&&(R=DataSaver.findValue("vpWidth"))&&f(R);var q=window.location.protocol+"//"+window.location.host+window.location.pathname.replace("index.html",""),z=void 0!==config.defaultPattern&&"string"==typeof config.defaultPattern&&config.defaultPattern.trim().length>0?config.defaultPattern:"all",A=q+"styleguide/html/styleguide.html?"+Date.now();if(void 0===B.p&&void 0===B.pattern||(z=void 0!==B.p?B.p:B.pattern),"all"!==z&&(patternPath=urlHandler.getFileName(z),A=""!==patternPath?q+patternPath+"?"+Date.now():A,document.getElementById("title").innerHTML="Pattern Lab - "+z,history.replaceState({pattern:z},null,null)),null!==document.getElementById("sg-raw")&&document.getElementById("sg-raw").setAttribute("href",urlHandler.getFileName(z)),urlHandler.skipBack=!0,document.getElementById("sg-viewport").contentWindow.location.replace(A),$("a[data-patternpartial]").on("click",function(e){e.preventDefault();var t=JSON.stringify({event:"patternLab.updatePath",path:urlHandler.getFileName($(this).attr("data-patternpartial"))});document.getElementById("sg-viewport").contentWindow.postMessage(t,urlHandler.targetOrigin),h()}),$("#sg-vp-wrap").click(function(){h()}),void 0!==window.orientation){var W=window.orientation;window.addEventListener("orientationchange",function(){window.orientation!=W&&($("#sg-gen-container").width($(window).width()),$("#sg-viewport").width($(window).width()),g($(window).width()),W=window.orientation)},!1)}window.addEventListener("message",m,!1)}(this);var pluginLoader={init:function(){for(var s,t,l,c,n,i=0;i= 200 && this.status < 300) resolve({ + content: xhr.response, + panel: panel + }); + + else { + + reject({ + status: xhr.status, + statusText: xhr.statusText, + panel: panel + }); + } + + }; + + xhr.onerror = function () { + + reject({ + status: this.status, + statusText: xhr.statusText, + panel: panel + }); + + }; + + xhr.open(method, url, async); + + xhr.send(); + + }); + + }, + + + /** + * Render the panels that have been collected + * @param {String} the collected panels + * @param {String} the data from the pattern + * @param {Boolean} if this is going to be passed back to the styleguide + */ + renderPanels: function (panels, patternData, iframePassback, switchText) { // set-up defaults var template, templateCompiled, templateRendered; var annotation, comment, count, div, els, item, markup, i; var patternPartial = patternData.patternPartial; patternData.panels = panels; - + // set a default pattern description for modal pop-up if (!iframePassback && (patternData.patternDesc.length === 0)) { patternData.patternDesc = "This pattern doesn't have a description."; @@ -126,7 +188,7 @@ var panelsViewer = { patternData.patternNameCaps = patternData.patternName.toUpperCase(); // check for annotations in the given mark-up - markup = document.createElement('div'); + markup = document.createElement('div'); markup.innerHTML = patternData.patternMarkup; count = 1; @@ -136,10 +198,15 @@ var panelsViewer = { for (i = 0; i < comments.comments.length; ++i) { item = comments.comments[i]; - els = markup.querySelectorAll(item.el); + els = markup.querySelectorAll(item.el); if (els.length > 0) { - annotation = { 'displayNumber': count, 'el': item.el, 'title': item.title, 'comment': item.comment }; + annotation = { + 'displayNumber': count, + 'el': item.el, + 'title': item.title, + 'comment': item.comment + }; patternData.annotations.push(annotation); count++; } @@ -148,7 +215,10 @@ var panelsViewer = { // alert the pattern that annotations should be highlighted if (patternData.annotations.length > 0) { - var obj = JSON.stringify({ 'event': 'patternLab.annotationsHighlightShow', 'annotations': patternData.annotations }); + var obj = JSON.stringify({ + 'event': 'patternLab.annotationsHighlightShow', + 'annotations': patternData.annotations + }); document.getElementById('sg-viewport').contentWindow.postMessage(obj, panelsViewer.targetOrigin); } @@ -182,25 +252,25 @@ var panelsViewer = { // figure out if pattern state should be drawn patternData.patternStateExists = (patternData.patternState.length > 0); - + // figure if annotations should be drawn patternData.annotationExists = (patternData.annotations.length > 0); - + // figure if the entire desc block should be drawn patternData.descBlockExists = (patternData.patternDescExists || patternData.lineageExists || patternData.lineageRExists || patternData.patternStateExists || patternData.annotationExists); - + // set isPatternView based on if we have to pass it back to the styleguide level patternData.isPatternView = (iframePassback === false); // render all of the panels in the base panel template - template = document.getElementById('pl-panel-template-base'); + template = document.getElementById('pl-panel-template-base'); templateCompiled = Hogan.compile(template.innerHTML); templateRendered = templateCompiled.render(patternData); // make sure templateRendered is modified to be an HTML element - div = document.createElement('div'); - div.className = 'sg-modal-content-inner'; - div.innerHTML = templateRendered; + div = document.createElement('div'); + div.className = 'sg-modal-content-inner'; + div.innerHTML = templateRendered; templateRendered = div; // add click events @@ -212,8 +282,8 @@ var panelsViewer = { panel = panels[i]; // default IDs - panelTab = '#sg-'+patternPartial+'-'+panel.id+'-tab'; - panelBlock = '#sg-'+patternPartial+'-'+panel.id+'-panel'; + panelTab = '#sg-' + patternPartial + '-' + panel.id + '-tab'; + panelBlock = '#sg-' + patternPartial + '-' + panel.id + '-panel'; // show default options if ((templateRendered.querySelector(panelTab) !== null) && (panel.default)) { @@ -224,9 +294,12 @@ var panelsViewer = { } // find lineage links in the rendered content and add postmessage handlers in case it's in the modal - $('#sg-code-lineage-fill a, #sg-code-lineager-fill a', templateRendered).on('click', function(e){ + $('#sg-code-lineage-fill a, #sg-code-lineager-fill a', templateRendered).on('click', function (e) { e.preventDefault(); - var obj = JSON.stringify({ 'event': 'patternLab.updatePath', 'path': urlHandler.getFileName($(this).attr('data-patternpartial')) }); + var obj = JSON.stringify({ + 'event': 'patternLab.updatePath', + 'path': urlHandler.getFileName($(this).attr('data-patternpartial')) + }); document.getElementById('sg-viewport').contentWindow.postMessage(obj, panelsViewer.targetOrigin); });