@alotool/shortcode
Version:
Replace wordpress-style shortcode strings with anything
1 lines • 2.78 kB
JavaScript
var pluginName,Shortcode=function(e,t){e&&(this.el=e,this.tags=t,this.matches=[],this.regex="\\[{name}(\\s[\\s\\S]*?)?\\](?:((?!\\s*?(?:\\[{name}|\\[\\/(?!{name})))[\\s\\S]*?)(\\[/{name}\\]))?",this.el.jquery&&(this.el=this.el[0]),this.matchTags(),this.convertMatchesToNodes(),this.replaceNodes())};Shortcode.prototype.matchTags=function(){var e,t,r,n,a,s,o,i,c=this.el.outerHTML;for(i in this.tags){if(!this.tags.hasOwnProperty(i))return;r=this.template(this.regex,{name:i});for(var h=0,p=(e=c.match(new RegExp(r,"g"))||[]).length;h<p;h++)n=(t=e[h].match(new RegExp(r)))[3]?"":void 0,s=t[0],a=this.escapeTagRegExp(s),o=this.parseOptions(t[1]),t[2]&&(n=t[2].trim(),s=s.replace(n,"").replace(/\n\s*/g,""),a=this.escapeTagRegExp(s).replace("\\]\\[","\\]([\\s\\S]*?)\\[")),this.matches.push({name:i,tag:s,regex:a,options:o,contents:n})}},Shortcode.prototype.convertMatchesToNodes=function(){for(var e,t=this.el.innerHTML,r=function(e,t,r,n,a,s,o){if(t)return e;e=document.createElement("span");return e.setAttribute("data-sc-tag",this.tag),e.className="sc-node sc-node-"+this.name,e.outerHTML},n=0,a=this.matches.length;n<a;n++)e=new RegExp('((data-sc-tag=")|(<pre.*)|(<code.*))?'+this.matches[n].regex,"g"),t=t.replace(e,r.bind(this.matches[n]));this.el.innerHTML=t},Shortcode.prototype.replaceNodes=function(){for(var e,t,r,n,a=this,s=(this.el.querySelectorAll(".sc-node"),function(e){e.jquery&&(e=e[0]),e=a.parseCallbackResult(e),n.parentNode.replaceChild(e,n)}),o=0,i=this.matches.length;o<i;o++)e=this.matches[o],(n=this.el.querySelector(".sc-node-"+e.name))&&n.dataset.scTag===e.tag&&void 0!==(t=this.tags[e.name].bind(e)(r=s.bind(e)))&&r(t)},Shortcode.prototype.parseCallbackResult=function(e){var t,r,n;switch(typeof e){case"function":e=document.createTextNode(e());break;case"string":if(t=document.createElement("div"),r=document.createDocumentFragment(),t.innerHTML=e,(n=t.childNodes).length){for(var a=0,s=n.length;a<s;a++)r.appendChild(n[a].cloneNode(!0));e=r}else e=document.createTextNode(e);break;case"object":e.nodeType||(e=JSON.stringify(e),e=document.createTextNode(e))}return e},Shortcode.prototype.parseOptions=function(e){var t,r={};if(e){(t=e.replace(/(\w+=)/g,"\n$1").split("\n")).shift();for(var n=0;n<t.length;n++){var a=t[n].split("=");r[a[0]]=a[1].replace(/\'|\"/g,"").trim()}return r}},Shortcode.prototype.escapeTagRegExp=function(e){return e.replace(/[\[\]\/]/g,"\\$&")},Shortcode.prototype.template=function(e,t){for(var r in t)e=e.replace(new RegExp("{"+r+"}","g"),t[r]);return e},String.prototype.trim=String.prototype.trim||function(){return this.replace(/^\s+|\s+$/g,"")},window.jQuery&&(pluginName="shortcode",$.fn[pluginName]=function(e){return this.each(function(){$.data(this,pluginName)||$.data(this,pluginName,new Shortcode(this,e))}),this});