diff --git a/README.md b/README.md index aee6750..95811fb 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,4 @@ RAP.setBlackList(arr); RAP.setWhiteList(arr); ``` -其中arr可以包含匹配字符串,或正则对象,例:['test', /test/g] - - +其中arr可以包含匹配字符串,或正则对象,例:['test', /test/g] \ No newline at end of file diff --git a/WebContent/WEB-INF/urlrewrite.xml b/WebContent/WEB-INF/urlrewrite.xml index db023cd..efa11e4 100644 --- a/WebContent/WEB-INF/urlrewrite.xml +++ b/WebContent/WEB-INF/urlrewrite.xml @@ -20,7 +20,7 @@ mockjs plugin generator - ^/plugins/rap.plugin.js(.*)$ + ^/rap.plugin.js(.*)$ /mock/createPluginScript.action$1 \ No newline at end of file diff --git a/WebContent/WEB-INF/web.xml b/WebContent/WEB-INF/web.xml index 2a3011c..d380585 100644 --- a/WebContent/WEB-INF/web.xml +++ b/WebContent/WEB-INF/web.xml @@ -12,7 +12,6 @@ contextConfigLocation classpath*:applicationContext.xml - ssoFilter com.alibaba.buc.sso.client.filter.SSOFilter @@ -34,10 +33,9 @@ EXCLUSIONS - */stat/*,*/favicon.ico,/t/*,/crossdomain.xml,/*.htm,/*.html + */stat/*,*/favicon.ico,/t/*,/crossdomain.xml,/*.htm,/*.html,*.md - UrlRewriteFilter org.tuckey.web.filters.urlrewrite.UrlRewriteFilter @@ -58,8 +56,6 @@ true - - authCheckFilter com.taobao.rigel.rap.common.AuthCheckFilter @@ -76,7 +72,6 @@ utf-8 - ssoFilter /* diff --git a/WebContent/plugins/index.htm b/WebContent/demo/mock.plugin/index.htm similarity index 93% rename from WebContent/plugins/index.htm rename to WebContent/demo/mock.plugin/index.htm index 1197741..84c7c67 100644 --- a/WebContent/plugins/index.htm +++ b/WebContent/demo/mock.plugin/index.htm @@ -6,7 +6,7 @@ - + diff --git a/WebContent/plugins/jquery-2.0.3.min.js b/WebContent/demo/mock.plugin/jquery-2.0.3.min.js similarity index 100% rename from WebContent/plugins/jquery-2.0.3.min.js rename to WebContent/demo/mock.plugin/jquery-2.0.3.min.js diff --git a/WebContent/plugins/jquery-2.0.3.min.map b/WebContent/demo/mock.plugin/jquery-2.0.3.min.map similarity index 100% rename from WebContent/plugins/jquery-2.0.3.min.map rename to WebContent/demo/mock.plugin/jquery-2.0.3.min.map diff --git a/WebContent/mock/createPluginScript.vm b/WebContent/mock/createPluginScript.vm index 5997abf..23e4edf 100644 --- a/WebContent/mock/createPluginScript.vm +++ b/WebContent/mock/createPluginScript.vm @@ -1,31 +1,9 @@ -/********************************************************************************************************** - * - * 使用方法 - * 1. 在kissy, jQuery后面引入rap plugin - * - * 其中{{projectId}}为RAP提供的项目ID - * {{mode}}为RAP路由的工作模式, 默认值为3 - * 0 - 不拦截 - * 1 - 拦截全部 - * 2 - 黑名单中的项不拦截 - * 3 - 仅拦截白名单中的项 - * 2. 引入mock.js - * - * 3. 设置黑名单、白名单(可选) - * 设置黑名单 - * RAP.setBlackList(arr); - * 设置白名单 - * RAP.setWhiteList(arr); - * 其中arr可以包含匹配字符串,或正则对象,例:['test', /test/g] - * - ********************************************************************************************************/ - /*! rap.plugin Jan.22th 2014 */ (function(){function m(a){var b,g,c,d;if(!a||"string"!==typeof a)return console.warn("Illegal url:",a),!1;if(0!==e){if(1==e)return!0;if(2===e||3===e){d=(c=2===e)?k:l;for(b=0;b1),#end"$url"#end],k=[],e=3,n=[0,1,2,3],h=0;"undefined"===typeof window.console&&(window.console={log:function(){},warn:function(){}});d||(d=document.getElementsByTagName("script"), d=d[d.length-1]);var f=d.src.match(/(?:\?|&)projectId=([^&]+)(?:&|$)/);f&&(h=f[1]);if(f=d.src.match(/(?:\?|&)mode=([^&]+)(?:&|$)/))e=+f[1],e in n||(e=1);f=!0;console.log("Current RAP work mode:",e,"(0-disabled, 1-black list, 2-white list, 3-combo)");(d=d.src.match(/(?:\?|&)enable=([^&]+)(?:&|$)/))&&(f="true"==d[1]);if(f){if(window.jQuery){var p=jQuery.ajax;jQuery.ajax=function(){var a=arguments[0],b=a.url;m(b)&&h&&(a.jsonp="_c",a.dataType="jsonp",-1i;i++)if(c=arguments[i])for(d in c)e=h[d],f=c[d],h!==f&&f!==a&&(b.isArray(f)||b.isObject(f)?(b.isArray(f)&&(g=e&&b.isArray(e)?e:[]),b.isObject(f)&&(g=e&&b.isObject(e)?e:{}),h[d]=b.extend(g,f)):h[d]=f);return h},b.each=function(a,b,c){var d,e;if("number"===this.type(a))for(d=0;a>d;d++)b(d,d);else if(a.length===+a.length)for(d=0;d1/(b+c)*b?!d:d):Math.random()>=.5},bool:function(a,b,c){return this.boolean(a,b,c)},natural:function(a,b){return a="undefined"!=typeof a?parseInt(a,10):0,b="undefined"!=typeof b?parseInt(b,10):9007199254740992,Math.round(Math.random()*(b-a))+a},integer:function(a,b){return a="undefined"!=typeof a?parseInt(a,10):-9007199254740992,b="undefined"!=typeof b?parseInt(b,10):9007199254740992,Math.round(Math.random()*(b-a))+a},"int":function(a,b){return this.integer(a,b)},"float":function(b,c,d,e){d=d===a?0:d,d=Math.max(Math.min(d,17),0),e=e===a?17:e,e=Math.max(Math.min(e,17),0);for(var f=this.integer(b,c)+".",g=0,h=this.natural(d,e);h>g;g++)f+=this.character("number");return parseFloat(f,10)},character:function(a){var c={lower:"abcdefghijklmnopqrstuvwxyz",upper:"ABCDEFGHIJKLMNOPQRSTUVWXYZ",number:"0123456789",symbol:"!@#$%^&*()[]"};return c.alpha=c.lower+c.upper,c.undefined=c.lower+c.upper+c.number+c.symbol,a=c[(""+a).toLowerCase()]||a,a.charAt(b.natural(0,a.length-1))},"char":function(a){return this.character(a)},string:function(c,d,e){var f;3===arguments.length&&(f=b.natural(d,e)),2===arguments.length&&("string"==typeof arguments[0]?f=d:(f=b.natural(c,d),c=a)),1===arguments.length&&(f=c,c=a),0===arguments.length&&(f=b.natural(3,7));for(var g="",h=0;f>h;h++)g+=b.character(c);return g},str:function(a,b,c){return this.string(a,b,c)},range:function(a,b,c){arguments.length<=1&&(b=a||0,a=0),c=arguments[2]||1;for(var d=Math.max(Math.ceil((b-a)/c),0),e=0,f=new Array(d);d>e;)f[e++]=a,a+=c;return f}}),b.extend({patternLetters:{yyyy:"getFullYear",yy:function(a){return(""+a.getFullYear()).slice(2)},y:"yy",MM:function(a){var b=a.getMonth()+1;return 10>b?"0"+b:b},M:function(a){return a.getMonth()+1},dd:function(a){var b=a.getDate();return 10>b?"0"+b:b},d:"getDate",HH:function(a){var b=a.getHours();return 10>b?"0"+b:b},H:"getHours",hh:function(a){var b=a.getHours()%12;return 10>b?"0"+b:b},h:function(a){return a.getHours()%12},mm:function(a){var b=a.getMinutes();return 10>b?"0"+b:b},m:"getMinutes",ss:function(a){var b=a.getSeconds();return 10>b?"0"+b:b},s:"getSeconds",SS:function(a){var b=a.getMilliseconds();return 10>b&&"00"+b||100>b&&"0"+b||b},S:"getMilliseconds",A:function(a){return a.getHours()<12?"AM":"PM"},a:function(a){return a.getHours()<12?"am":"pm"}}}),b.extend({rformat:new RegExp(function(){var a=[];for(var c in b.patternLetters)a.push(c);return"("+a.join("|")+")"}(),"g"),format:function(a,c){var d=b.patternLetters,e=b.rformat;return c.replace(e,function(b,c){return"function"==typeof d[c]?d[c](a):d[c]in d?arguments.callee(b,d[c]):a[d[c]]()})},randomDate:function(b,c){return b=b===a?new Date(0):b,c=c===a?new Date:c,new Date(Math.random()*(c.getTime()-b.getTime()))},date:function(a){return a=a||"yyyy-MM-dd",this.format(this.randomDate(),a)},time:function(a){return a=a||"HH:mm:ss",this.format(this.randomDate(),a)},datetime:function(a){return a=a||"yyyy-MM-dd HH:mm:ss",this.format(this.randomDate(),a)}}),b.extend({ad_size:["300x250","250x250","240x400","336x280","180x150","720x300","468x60","234x60","88x31","120x90","120x60","120x240","125x125","728x90","160x600","120x600","300x600"],screen_size:["320x200","320x240","640x480","800x480","800x480","1024x600","1024x768","1280x800","1440x900","1920x1200","2560x1600"],video_size:["720x480","768x576","1280x720","1920x1080"],image:function(b,c,d,e,f){return 4===arguments.length&&(f=e,e=a),3===arguments.length&&(f=d,d=a),b||(b=this.pick(this.ad_size)),c&&~c.indexOf("#")&&(c=c.slice(1)),d&&~d.indexOf("#")&&(d=d.slice(1)),"http://dummyimage.com/"+b+(c?"/"+c:"")+(d?"/"+d:"")+(e?"."+e:"")+(f?"&text="+f:"")},img:function(){return this.image.apply(this,arguments)}}),b.extend({brandColors:{"4ormat":"#fb0a2a","500px":"#02adea","About.me (blue)":"#00405d","About.me (yellow)":"#ffcc33",Addvocate:"#ff6138",Adobe:"#ff0000",Aim:"#fcd20b",Amazon:"#e47911",Android:"#a4c639","Angie's List":"#7fbb00",AOL:"#0060a3",Atlassian:"#003366",Behance:"#053eff","Big Cartel":"#97b538",bitly:"#ee6123",Blogger:"#fc4f08",Boeing:"#0039a6","Booking.com":"#003580",Carbonmade:"#613854",Cheddar:"#ff7243","Code School":"#3d4944",Delicious:"#205cc0",Dell:"#3287c1",Designmoo:"#e54a4f",Deviantart:"#4e6252","Designer News":"#2d72da",Devour:"#fd0001",DEWALT:"#febd17","Disqus (blue)":"#59a3fc","Disqus (orange)":"#db7132",Dribbble:"#ea4c89",Dropbox:"#3d9ae8",Drupal:"#0c76ab",Dunked:"#2a323a",eBay:"#89c507",Ember:"#f05e1b",Engadget:"#00bdf6",Envato:"#528036",Etsy:"#eb6d20",Evernote:"#5ba525","Fab.com":"#dd0017",Facebook:"#3b5998",Firefox:"#e66000","Flickr (blue)":"#0063dc","Flickr (pink)":"#ff0084",Forrst:"#5b9a68",Foursquare:"#25a0ca",Garmin:"#007cc3",GetGlue:"#2d75a2",Gimmebar:"#f70078",GitHub:"#171515","Google Blue":"#0140ca","Google Green":"#16a61e","Google Red":"#dd1812","Google Yellow":"#fcca03","Google+":"#dd4b39",Grooveshark:"#f77f00",Groupon:"#82b548","Hacker News":"#ff6600",HelloWallet:"#0085ca","Heroku (light)":"#c7c5e6","Heroku (dark)":"#6567a5",HootSuite:"#003366",Houzz:"#73ba37",HTML5:"#ec6231",IKEA:"#ffcc33",IMDb:"#f3ce13",Instagram:"#3f729b",Intel:"#0071c5",Intuit:"#365ebf",Kickstarter:"#76cc1e",kippt:"#e03500",Kodery:"#00af81",LastFM:"#c3000d",LinkedIn:"#0e76a8",Livestream:"#cf0005",Lumo:"#576396",Mixpanel:"#a086d3",Meetup:"#e51937",Nokia:"#183693",NVIDIA:"#76b900",Opera:"#cc0f16",Path:"#e41f11","PayPal (dark)":"#1e477a","PayPal (light)":"#3b7bbf",Pinboard:"#0000e6",Pinterest:"#c8232c",PlayStation:"#665cbe",Pocket:"#ee4056",Prezi:"#318bff",Pusha:"#0f71b4",Quora:"#a82400","QUOTE.fm":"#66ceff",Rdio:"#008fd5",Readability:"#9c0000","Red Hat":"#cc0000",Resource:"#7eb400",Rockpack:"#0ba6ab",Roon:"#62b0d9",RSS:"#ee802f",Salesforce:"#1798c1",Samsung:"#0c4da2",Shopify:"#96bf48",Skype:"#00aff0",Snagajob:"#f47a20",Softonic:"#008ace",SoundCloud:"#ff7700","Space Box":"#f86960",Spotify:"#81b71a",Sprint:"#fee100",Squarespace:"#121212",StackOverflow:"#ef8236",Staples:"#cc0000","Status Chart":"#d7584f",Stripe:"#008cdd",StudyBlue:"#00afe1",StumbleUpon:"#f74425","T-Mobile":"#ea0a8e",Technorati:"#40a800","The Next Web":"#ef4423",Treehouse:"#5cb868",Trulia:"#5eab1f",Tumblr:"#34526f","Twitch.tv":"#6441a5",Twitter:"#00acee",TYPO3:"#ff8700",Ubuntu:"#dd4814",Ustream:"#3388ff",Verizon:"#ef1d1d",Vimeo:"#86c9ef",Vine:"#00a478",Virb:"#06afd8","Virgin Media":"#cc0000",Wooga:"#5b009c","WordPress (blue)":"#21759b","WordPress (orange)":"#d54e21","WordPress (grey)":"#464646",Wunderlist:"#2b88d9",XBOX:"#9bc848",XING:"#126567","Yahoo!":"#720e9e",Yandex:"#ffcc00",Yelp:"#c41200",YouTube:"#c4302b",Zalongo:"#5498dc",Zendesk:"#78a300",Zerply:"#9dcc7a",Zootool:"#5e8b1d"},brands:function(){var a=[];for(var b in this.brandColors)a.push(b);return a},dataImageHolder:function(a){return"holder.js/"+a},dataImage:function(b,c){var d="undefined"!=typeof document&&document.createElement("canvas"),e=d&&d.getContext&&d.getContext("2d");if(!d||!e)return"";b||(b=this.pick(this.ad_size)),c=c!==a?c:b,b=b.split("x");var f=parseInt(b[0],10),g=parseInt(b[1],10),h=this.brandColors[this.pick(this.brands())],i="#FFF",j=14,k="sans-serif";return d.width=f,d.height=g,e.textAlign="center",e.textBaseline="middle",e.fillStyle=h,e.fillRect(0,0,f,g),e.fillStyle=i,e.font="bold "+j+"px "+k,e.fillText(c,f/2,g/2,f),d.toDataURL("image/png")}}),b.extend({color:function(){var a=Math.floor(16777215*Math.random()).toString(16);return a="#"+("000000"+a).slice(-6)}}),b.extend({capitalize:function(a){return a.charAt(0).toUpperCase()+a.substr(1)},upper:function(a){return a.toUpperCase()},lower:function(a){return a.toLowerCase()},pick:function(a){return a[this.natural(0,a.length-1)]},shuffle:function(a){for(var b=a.slice(0),c=[],d=0,e=b.length,f=0;e>f;f++)d=this.natural(0,b.length-1),c.push(b[d]),b.splice(d,1);return c}}),b.extend({paragraph:function(a,c){var d;0===arguments.length&&(d=b.natural(3,7)),1===arguments.length&&(d=c=a),2===arguments.length&&(a=parseInt(a,10),c=parseInt(c,10),d=b.natural(a,c));for(var e=[],f=0;d>f;f++)e.push(b.sentence());return e.join(" ")},sentence:function(a,c){var d;0===arguments.length&&(d=b.natural(12,18)),1===arguments.length&&(d=c=a),2===arguments.length&&(a=parseInt(a,10),c=parseInt(c,10),d=b.natural(a,c));for(var e=[],f=0;d>f;f++)e.push(b.word());return b.capitalize(e.join(" "))+"."},word:function(a,c){var d;0===arguments.length&&(d=b.natural(3,10)),1===arguments.length&&(d=c=a),2===arguments.length&&(a=parseInt(a,10),c=parseInt(c,10),d=b.natural(a,c));for(var e="",f=0;d>f;f++)e+=b.character("lower");return e},title:function(a,c){var d,e=[];0===arguments.length&&(d=b.natural(3,7)),1===arguments.length&&(d=c=a),2===arguments.length&&(a=parseInt(a,10),c=parseInt(c,10),d=b.natural(a,c));for(var f=0;d>f;f++)e.push(this.capitalize(this.word()));return e.join(" ")}}),b.extend({first:function(){var a=["James","John","Robert","Michael","William","David","Richard","Charles","Joseph","Thomas","Christopher","Daniel","Paul","Mark","Donald","George","Kenneth","Steven","Edward","Brian","Ronald","Anthony","Kevin","Jason","Matthew","Gary","Timothy","Jose","Larry","Jeffrey","Frank","Scott","Eric"].concat(["Mary","Patricia","Linda","Barbara","Elizabeth","Jennifer","Maria","Susan","Margaret","Dorothy","Lisa","Nancy","Karen","Betty","Helen","Sandra","Donna","Carol","Ruth","Sharon","Michelle","Laura","Sarah","Kimberly","Deborah","Jessica","Shirley","Cynthia","Angela","Melissa","Brenda","Amy","Anna"]);return this.pick(a)},last:function(){var a=["Smith","Johnson","Williams","Brown","Jones","Miller","Davis","Garcia","Rodriguez","Wilson","Martinez","Anderson","Taylor","Thomas","Hernandez","Moore","Martin","Jackson","Thompson","White","Lopez","Lee","Gonzalez","Harris","Clark","Lewis","Robinson","Walker","Perez","Hall","Young","Allen"];return this.pick(a)},name:function(a){return this.first()+" "+(a?this.first()+" ":"")+this.last()}}),b.extend({url:function(){return"http://"+this.domain()+"/"+this.word()},domain:function(a){return this.word()+"."+(a||this.tld())},email:function(a){return this.character("lower")+"."+this.last().toLowerCase()+"@"+this.last().toLowerCase()+"."+this.tld()},ip:function(){return this.natural(0,255)+"."+this.natural(0,255)+"."+this.natural(0,255)+"."+this.natural(0,255)},tlds:["com","org","edu","gov","co.uk","net","io"],tld:function(){return this.pick(this.tlds)}}),b.extend({areas:["东北","华北","华东","华中","华南","西南","西北"],area:function(){return this.pick(this.areas)},regions:["110000 北京市","120000 天津市","130000 河北省","140000 山西省","150000 内蒙古自治区","210000 辽宁省","220000 吉林省","230000 黑龙江省","310000 上海市","320000 江苏省","330000 浙江省","340000 安徽省","350000 福建省","360000 江西省","370000 山东省","410000 河南省","420000 湖北省","430000 湖南省","440000 广东省","450000 广西壮族自治区","460000 海南省","500000 重庆市","510000 四川省","520000 贵州省","530000 云南省","540000 西藏自治区","610000 陕西省","620000 甘肃省","630000 青海省","640000 宁夏回族自治区","650000 新疆维吾尔自治区","650000 新疆维吾尔自治区","710000 台湾省","810000 香港特别行政区","820000 澳门特别行政区"],region:function(){return this.pick(this.regions).split(" ")[1]},address:function(){},city:function(){},phone:function(){},areacode:function(){},street:function(){},street_suffixes:function(){},street_suffix:function(){},states:function(){},state:function(){},zip:function(a){for(var b="",c=0;(a||6)>c;c++)b+=this.natural(0,9);return b}}),b.extend({todo:function(){return"todo"}}),b.extend({d4:function(){return this.natural(1,4)},d6:function(){return this.natural(1,6)},d8:function(){return this.natural(1,8)},d12:function(){return this.natural(1,12)},d20:function(){return this.natural(1,20)},d100:function(){return this.natural(1,100)},guid:function(){var a="ABCDEF1234567890",b=this.string(a,8)+"-"+this.string(a,4)+"-"+this.string(a,4)+"-"+this.string(a,4)+"-"+this.string(a,12);return b},id:function(){var a,b=0,c=["7","9","10","5","8","4","2","1","6","3","7","9","10","5","8","4","2"],d=["1","0","X","9","8","7","6","5","4","3","2"];a=this.pick(this.regions).split(" ")[0]+this.date("yyyyMMdd")+this.string("number",3);for(var e=0;e1)e=d.pick(h.gen(a.template));else for(b=0;b",g.rurl);var h=b.mock(g.template);return console.log("[mock]",h),e.success&&e.success(h,"success",d),e.complete&&e.complete(h,"success",d),a}}return c.apply(this,arguments)}}),b.Util=c,b.Random=d,b.heredoc=c.heredoc,"object"==typeof module&&module.exports?module.exports=b:"function"==typeof define&&define.amd?define(function(){return b}):"function"==typeof define&&define.cmd&&define(function(){return b}),this.Mock=b,this.Random=d,"undefined"!=typeof KISSY&&c.each(["mock","components/mock/index","mock/dist/mock","gallery/Mock/0.1.1/index","gallery/Mock/0.1.2/index"],function(a){KISSY.add(a,function(a){return b.mockjax(a),b},{requires:["ajax"]})}),function(a){var e={version:"0.0.1"};this.Mock||(module.exports=e),b.tpl=function(a,b,c,d){return e.mock(a,b,c,d)},b.parse=function(a){return Handlebars.parse(a)},e.mock=function(a,b,d,e){return d=d?c.extend({},d,Handlebars.helpers):Handlebars.helpers,e=e?c.extend({},e,Handlebars.partials):Handlebars.partials,f.gen(a,null,b,d,e)};var f={debug:e.debug||!1,extend:c.extend};f.gen=function(a,b,d,g,h){if(c.isString(a)){var i=Handlebars.parse(a);d=f.parseOptions(a,d);var j=f.gen(i,b,d,g,h);return j}if(b=b||[{}],d=d||{},this[a.type]!==c.noop){d.__path=d.__path||[],(e.debug||f.debug)&&(console.log(),console.group("["+a.type+"]",JSON.stringify(a)),console.log("[options]",d.__path.length,JSON.stringify(d)));var k=d.__path.length;return this[a.type](a,b,d,g,h),d.__path.splice(k),(e.debug||f.debug)&&console.groupEnd(),b[b.length-1]}},f.parseOptions=function(a,b){var d,e,f,g=//g,h=a.match(g),i={};for(d=0;h&&di&&b.splice(0,b.length-i)},f.block=function(a,b,e,f,h){var i,j,k,l,m,n=a.mustache.id.parts,o=b[0],p=b.length;if(a.inverse,a.mustache.isHelper||f&&f[a.mustache.id.string])m=n[0],l=(g[m]||g.custom).apply(this,arguments),o=b[0];else for(i=0;ii;i++)o.push("undefined"!=typeof l[i]?l[i]:{}),e.__path.push("[]"),b.unshift(o[o.length-1]),this.gen(a.program,b,e,f,h),e.__path.pop(),b.shift();else this.gen(a.program,b,e,f,h);b.length>p&&b.splice(0,b.length-p)},f.hash=function(a,b,c,d,e){var f,g,h,i=a.pairs;for(g=0;ge;e++)d.__path.push(n[e]),g=n[e],h=n[e-1],m=d[h],i=e===f-1?o[g]:{},j=this.val(g,d,b,i),k=c.type(o[g]),l=c.type(j),"undefined"===k?o[g]=f-1>e&&"object"!==l&&"array"!==l?{}:c.isArray(j)&&[]||j:f-1>e&&"object"!==k&&"array"!==k&&(o[g]=c.isArray(j)&&[]||{}),k=c.type(o[g]),("object"===k||"array"===k)&&(o=o[g],b.unshift(o));else;b.length>p&&b.splice(0,b.length-p)},f.partial=function(a,b,c,d,e){var g=a.partialName.name,h=e&&e[g],i=b.length;h&&f.gen(h,b,c,d,e),b.length>i&&b.splice(0,b.length-i)},f.content=c.noop,f.PARTIAL_NAME=c.noop,f.DATA=c.noop,f.STRING=c.noop,f.INTEGER=c.noop,f.BOOLEAN=c.noop,f.comment=c.noop;var g={};g.each=function(a,b,d){var e,f,g,h,i,j,k,l=b[0];for(i=a.mustache.params[0].parts,e=0,f=i.length;f>e;e++)d.__path.push(i[e]),g=i[e],j=e===f-1?[]:{},h=this.val(g,d,b,j),l[g]=c.isArray(h)&&[]||h,k=c.type(l[g]),("object"===k||"array"===k)&&(l=l[g],b.unshift(l));return h},g["if"]=g.unless=function(a,b,d){var e,f,g,h,i,j,k,l=a.mustache.params,m=b[0];for(e=0;ee;e++)d.__path.push(i[e]),g=i[e],j=e===f-1?[]:{},h=this.val(g,d,b,j),l[g]=c.isArray(h)&&[]||h,k=c.type(l[g]),("object"===k||"array"===k)&&(l=l[g],b.unshift(l));return h}}}.call(this),function(a){if("undefined"!=typeof KISSY){var e,f={debug:!1};KISSY.use("xtemplate",function(a,b){e=b}),this.Mock||(module.exports=f),b.xtpl=function(a,b,c,d){return f.mock(a,b,c,d)},b.xparse=function(a){return e.compiler.parse(a)},f.mock=function(a,b,d,f){return d=d?c.extend({},d,e.RunTime.commands):e.RunTime.commands,f=f?c.extend({},f,e.RunTime.subTpls):e.RunTime.subTpls,this.gen(a,null,b,d,f,{})},f.parse=function(a){return e.compiler.parse(a)},f.gen=function(a,b,d,e,g,h){if("string"==typeof a){f.debug&&console.log("[tpl ]\n",a);var i=this.parse(a);d=this.parseOptions(a,d);var j=this.gen(i,b,d,e,g,h);return j}if(b=b||[{}],d=d||{},a.type=a.type,this[a.type]!==c.noop){d.__path=d.__path||[],f.debug&&(console.log(),console.group("["+a.type+"]",JSON.stringify(a)),console.log("[context]","[before]",b.length,JSON.stringify(b)),console.log("[options]","[before]",d.__path.length,JSON.stringify(d)),console.log("[other ]","[before]",JSON.stringify(h)));var k=d.__path.length;return this[a.type](a,b,d,e,g,h),f.debug&&console.log("[__path ]","[after ]",d.__path),(!h.hold||"function"==typeof h.hold&&!h.hold(a,d,b))&&d.__path.splice(k),f.debug&&(console.log("[context]","[after ]",b.length,JSON.stringify(b)),console.groupEnd()),b[b.length-1]}},f.parseOptions=function(a,b){var d,e,f,g=//g,h=a.match(g),i={};for(d=0;h&&d0)return j[0];if(d in i)return i[d]}return c.isArray(g[0])?{}:h!==a?h:d},f.program=function(a,b,c,d,e,f){for(var g=0;gl;l++)n.push(k&&k[l]!==a?k[l]:{}),f.__path.push(l),e.unshift(n[n.length-1]),this.gen(b.program,e,f,g,h,i),f.__path.pop(),e.shift();else this.gen(b.program,e,f,g,h,i);(!i.hold||"function"==typeof i.hold&&!i.hold(b,f,e))&&e.splice(0,e.length-j)},f.tpl=function(a,b,d,e,f,g){if(a.params&&a.params.length){g=c.extend({},g,{def:{each:[],"if":"@BOOL(2,1,true)",unless:"@BOOL(2,1,false)","with":{}}[a.path.string],hold:{each:!0,"if":function(a,b,c,d,e){return"object"==typeof e},unless:function(a,b,c,d,e){return"object"==typeof e},"with":!0,include:!1}[a.path.string]});for(var h,i=0;i-1?d.float(-Math.pow(10,10),Math.pow(10,10),1,Math.pow(10,6)):d.integer():a}()})),this.gen(b.op2,e,f,g,h,c.extend({},i,{def:function(){return"number"===b.op1.type?b.op1.value.indexOf(".")>-1?d.float(-Math.pow(10,10),Math.pow(10,10),1,Math.pow(10,6)):d.integer():a}()}))},f.relationalExpression=function(a,b,c,d,e,f){this.gen(a.op1,b,c,d,e,f),this.gen(a.op2,b,c,d,e,f)},f.equalityExpression=c.noop,f.conditionalAndExpression=c.noop,f.conditionalOrExpression=c.noop,f.string=c.noop,f.number=c.noop,f.boolean=c.noop,f.hash=function(a,b,c,d,e,f){var g,h=a.value;for(g in h)this.gen(h[g],b,c,d,e,f)},f.id=function(b,d,e,g,h,i){function j(a,b,d,e,f){var g=c.type(a[e]),h=c.type(f);return f="true"===f?!0:"false"===f?!1:f,"undefined"===g?a[e]=d-1>b&&!c.isObjectOrArray(f)?{}:c.isArray(f)&&[]||f:d-1>b&&"object"!==g&&"array"!==g?a[e]=c.isArray(f)&&[]||{}:"object"!==g&&"array"!==g&&"object"!==h&&"array"!==h&&(a[e]=f),a[e]}var k,l,m,n,o,p=d.length,q=b.parts,r=d[b.depth];for(c.isArray(r)&&(r=d[b.depth+1]),k=0,l=q.length;l>k;k++)(0!==k||"this"!==q[k])&&(/^(xindex|xcount|xkey)$/.test(q[k])||0===k&&1===l&&q[k]in g||(e.__path.push(q[k]),m=q[k],n=k===l-1?i.def!==a?i.def:d[0][m]:{},o=this.val(m,e,d,n),f.debug&&(console.log("[def ]",JSON.stringify(n)),console.log("[val ]",JSON.stringify(o))),o=j(r,k,l,m,o),c.isObjectOrArray(r[m])&&d.unshift(r=r[m])));(!i.hold||"function"==typeof i.hold&&!i.hold(b,e,d,m,o))&&d.splice(0,d.length-p)}}}.call(this)}).call(this); -//# sourceMappingURL=dist/mock-min.map +//# sourceMappingURL=http://mockjs.com/dist/mock-min.map diff --git a/WebContent/platform/help.about.vm b/WebContent/platform/help.about.vm index b7b613e..a18fb73 100644 --- a/WebContent/platform/help.about.vm +++ b/WebContent/platform/help.about.vm @@ -1 +1,6 @@ 在开发WEB应用时前后端会约定请求接口,包含请求链接、参数等细节。RAP提供了接口数据的共享平台,功能强大使用方便。同时利用这些数据自动化的生成伪造数据、提供后端开发工具包等,减少重复劳动并提升开发效率。 + + +```bash +test.abc +``` diff --git a/WebContent/platform/help.vm b/WebContent/platform/help.vm index 94b11df..d8bd4ca 100644 --- a/WebContent/platform/help.vm +++ b/WebContent/platform/help.vm @@ -7,47 +7,20 @@ #includeNewRapStatic + #bodyNewStart -
- -
-
-

#parse('/platform/help.about.vm')

-
-
-

#parse('/platform/help.edit.vm')

-
-
-

#parse('/platform/help.mock.vm')

-
-
-

#parse('/platform/help.tagy.vm')

-
-
-

#parse('/platform/help.test.vm')

-
-
-

#parse('/platform/help.console.vm')

-
-
-
+
#bodyEnd diff --git a/WebContent/plugins/rap.plugin.js b/WebContent/plugin/rap.mock.js similarity index 85% rename from WebContent/plugins/rap.plugin.js rename to WebContent/plugin/rap.mock.js index f33b8aa..942a74b 100644 --- a/WebContent/plugins/rap.plugin.js +++ b/WebContent/plugin/rap.mock.js @@ -1,24 +1,3 @@ -/********************************************************************************************************** - * - * 使用方法 - * 1. 在kissy, jQuery后面引入rap plugin - * - * 其中{{projectId}}为RAP提供的项目ID - * {{mode}}为RAP路由的工作模式, 默认值为3 - * 0 - 不拦截 - * 1 - 拦截全部 - * 2 - 黑名单中的项不拦截 - * 3 - 仅拦截白名单中的项 - * 2. 引入mock.js - * - * 3. 设置黑名单、白名单(可选) - * 设置黑名单 - * RAP.setBlackList(arr); - * 设置白名单 - * RAP.setWhiteList(arr); - * 其中arr可以包含匹配字符串,或正则对象,例:['test', /test/g] - * - ********************************************************************************************************/ (function() { var node = document.getElementById('rap'); var blackList = []; diff --git a/WebContent/stat/js/core/markdown.js b/WebContent/stat/js/core/markdown.js new file mode 100644 index 0000000..65b04e4 --- /dev/null +++ b/WebContent/stat/js/core/markdown.js @@ -0,0 +1,1740 @@ +// Released under MIT license +// Copyright (c) 2009-2010 Dominic Baggott +// Copyright (c) 2009-2010 Ash Berlin +// Copyright (c) 2011 Christoph Dorn (http://www.christophdorn.com) +// Date: 2013-09-15T16:12Z + +(function(expose) { + + + + + var MarkdownHelpers = {}; + + // For Spidermonkey based engines + function mk_block_toSource() { + return "Markdown.mk_block( " + + uneval(this.toString()) + + ", " + + uneval(this.trailing) + + ", " + + uneval(this.lineNumber) + + " )"; + } + + // node + function mk_block_inspect() { + var util = require("util"); + return "Markdown.mk_block( " + + util.inspect(this.toString()) + + ", " + + util.inspect(this.trailing) + + ", " + + util.inspect(this.lineNumber) + + " )"; + + } + + MarkdownHelpers.mk_block = function(block, trail, line) { + // Be helpful for default case in tests. + if ( arguments.length === 1 ) + trail = "\n\n"; + + // We actually need a String object, not a string primitive + /* jshint -W053 */ + var s = new String(block); + s.trailing = trail; + // To make it clear its not just a string + s.inspect = mk_block_inspect; + s.toSource = mk_block_toSource; + + if ( line !== undefined ) + s.lineNumber = line; + + return s; + }; + + + var isArray = MarkdownHelpers.isArray = Array.isArray || function(obj) { + return Object.prototype.toString.call(obj) === "[object Array]"; + }; + + // Don't mess with Array.prototype. Its not friendly + if ( Array.prototype.forEach ) { + MarkdownHelpers.forEach = function forEach( arr, cb, thisp ) { + return arr.forEach( cb, thisp ); + }; + } + else { + MarkdownHelpers.forEach = function forEach(arr, cb, thisp) { + for (var i = 0; i < arr.length; i++) + cb.call(thisp || arr, arr[i], i, arr); + }; + } + + MarkdownHelpers.isEmpty = function isEmpty( obj ) { + for ( var key in obj ) { + if ( hasOwnProperty.call( obj, key ) ) + return false; + } + return true; + }; + + MarkdownHelpers.extract_attr = function extract_attr( jsonml ) { + return isArray(jsonml) + && jsonml.length > 1 + && typeof jsonml[ 1 ] === "object" + && !( isArray(jsonml[ 1 ]) ) + ? jsonml[ 1 ] + : undefined; + }; + + + + + /** + * class Markdown + * + * Markdown processing in Javascript done right. We have very particular views + * on what constitutes 'right' which include: + * + * - produces well-formed HTML (this means that em and strong nesting is + * important) + * + * - has an intermediate representation to allow processing of parsed data (We + * in fact have two, both as [JsonML]: a markdown tree and an HTML tree). + * + * - is easily extensible to add new dialects without having to rewrite the + * entire parsing mechanics + * + * - has a good test suite + * + * This implementation fulfills all of these (except that the test suite could + * do with expanding to automatically run all the fixtures from other Markdown + * implementations.) + * + * ##### Intermediate Representation + * + * *TODO* Talk about this :) Its JsonML, but document the node names we use. + * + * [JsonML]: http://jsonml.org/ "JSON Markup Language" + **/ + var Markdown = function(dialect) { + switch (typeof dialect) { + case "undefined": + this.dialect = Markdown.dialects.Gruber; + break; + case "object": + this.dialect = dialect; + break; + default: + if ( dialect in Markdown.dialects ) + this.dialect = Markdown.dialects[dialect]; + else + throw new Error("Unknown Markdown dialect '" + String(dialect) + "'"); + break; + } + this.em_state = []; + this.strong_state = []; + this.debug_indent = ""; + }; + + /** + * Markdown.dialects + * + * Namespace of built-in dialects. + **/ + Markdown.dialects = {}; + + + + + // Imported functions + var mk_block = Markdown.mk_block = MarkdownHelpers.mk_block, + isArray = MarkdownHelpers.isArray; + + /** + * parse( markdown, [dialect] ) -> JsonML + * - markdown (String): markdown string to parse + * - dialect (String | Dialect): the dialect to use, defaults to gruber + * + * Parse `markdown` and return a markdown document as a Markdown.JsonML tree. + **/ + Markdown.parse = function( source, dialect ) { + // dialect will default if undefined + var md = new Markdown( dialect ); + return md.toTree( source ); + }; + + function count_lines( str ) { + var n = 0, + i = -1; + while ( ( i = str.indexOf("\n", i + 1) ) !== -1 ) + n++; + return n; + } + + // Internal - split source into rough blocks + Markdown.prototype.split_blocks = function splitBlocks( input ) { + input = input.replace(/(\r\n|\n|\r)/g, "\n"); + // [\s\S] matches _anything_ (newline or space) + // [^] is equivalent but doesn't work in IEs. + var re = /([\s\S]+?)($|\n#|\n(?:\s*\n|$)+)/g, + blocks = [], + m; + + var line_no = 1; + + if ( ( m = /^(\s*\n)/.exec(input) ) !== null ) { + // skip (but count) leading blank lines + line_no += count_lines( m[0] ); + re.lastIndex = m[0].length; + } + + while ( ( m = re.exec(input) ) !== null ) { + if (m[2] === "\n#") { + m[2] = "\n"; + re.lastIndex--; + } + blocks.push( mk_block( m[1], m[2], line_no ) ); + line_no += count_lines( m[0] ); + } + + return blocks; + }; + + /** + * Markdown#processBlock( block, next ) -> undefined | [ JsonML, ... ] + * - block (String): the block to process + * - next (Array): the following blocks + * + * Process `block` and return an array of JsonML nodes representing `block`. + * + * It does this by asking each block level function in the dialect to process + * the block until one can. Succesful handling is indicated by returning an + * array (with zero or more JsonML nodes), failure by a false value. + * + * Blocks handlers are responsible for calling [[Markdown#processInline]] + * themselves as appropriate. + * + * If the blocks were split incorrectly or adjacent blocks need collapsing you + * can adjust `next` in place using shift/splice etc. + * + * If any of this default behaviour is not right for the dialect, you can + * define a `__call__` method on the dialect that will get invoked to handle + * the block processing. + */ + Markdown.prototype.processBlock = function processBlock( block, next ) { + var cbs = this.dialect.block, + ord = cbs.__order__; + + if ( "__call__" in cbs ) + return cbs.__call__.call(this, block, next); + + for ( var i = 0; i < ord.length; i++ ) { + //D:this.debug( "Testing", ord[i] ); + var res = cbs[ ord[i] ].call( this, block, next ); + if ( res ) { + //D:this.debug(" matched"); + if ( !isArray(res) || ( res.length > 0 && !( isArray(res[0]) ) ) ) + this.debug(ord[i], "didn't return a proper array"); + //D:this.debug( "" ); + return res; + } + } + + // Uhoh! no match! Should we throw an error? + return []; + }; + + Markdown.prototype.processInline = function processInline( block ) { + return this.dialect.inline.__call__.call( this, String( block ) ); + }; + + /** + * Markdown#toTree( source ) -> JsonML + * - source (String): markdown source to parse + * + * Parse `source` into a JsonML tree representing the markdown document. + **/ + // custom_tree means set this.tree to `custom_tree` and restore old value on return + Markdown.prototype.toTree = function toTree( source, custom_root ) { + var blocks = source instanceof Array ? source : this.split_blocks( source ); + + // Make tree a member variable so its easier to mess with in extensions + var old_tree = this.tree; + try { + this.tree = custom_root || this.tree || [ "markdown" ]; + + blocks_loop: + while ( blocks.length ) { + var b = this.processBlock( blocks.shift(), blocks ); + + // Reference blocks and the like won't return any content + if ( !b.length ) + continue blocks_loop; + + this.tree.push.apply( this.tree, b ); + } + return this.tree; + } + finally { + if ( custom_root ) + this.tree = old_tree; + } + }; + + // Noop by default + Markdown.prototype.debug = function () { + var args = Array.prototype.slice.call( arguments); + args.unshift(this.debug_indent); + if ( typeof print !== "undefined" ) + print.apply( print, args ); + if ( typeof console !== "undefined" && typeof console.log !== "undefined" ) + console.log.apply( null, args ); + }; + + Markdown.prototype.loop_re_over_block = function( re, block, cb ) { + // Dont use /g regexps with this + var m, + b = block.valueOf(); + + while ( b.length && (m = re.exec(b) ) !== null ) { + b = b.substr( m[0].length ); + cb.call(this, m); + } + return b; + }; + + // Build default order from insertion order. + Markdown.buildBlockOrder = function(d) { + var ord = []; + for ( var i in d ) { + if ( i === "__order__" || i === "__call__" ) + continue; + ord.push( i ); + } + d.__order__ = ord; + }; + + // Build patterns for inline matcher + Markdown.buildInlinePatterns = function(d) { + var patterns = []; + + for ( var i in d ) { + // __foo__ is reserved and not a pattern + if ( i.match( /^__.*__$/) ) + continue; + var l = i.replace( /([\\.*+?|()\[\]{}])/g, "\\$1" ) + .replace( /\n/, "\\n" ); + patterns.push( i.length === 1 ? l : "(?:" + l + ")" ); + } + + patterns = patterns.join("|"); + d.__patterns__ = patterns; + //print("patterns:", uneval( patterns ) ); + + var fn = d.__call__; + d.__call__ = function(text, pattern) { + if ( pattern !== undefined ) + return fn.call(this, text, pattern); + else + return fn.call(this, text, patterns); + }; + }; + + + + + var extract_attr = MarkdownHelpers.extract_attr; + + /** + * renderJsonML( jsonml[, options] ) -> String + * - jsonml (Array): JsonML array to render to XML + * - options (Object): options + * + * Converts the given JsonML into well-formed XML. + * + * The options currently understood are: + * + * - root (Boolean): wether or not the root node should be included in the + * output, or just its children. The default `false` is to not include the + * root itself. + */ + Markdown.renderJsonML = function( jsonml, options ) { + options = options || {}; + // include the root element in the rendered output? + options.root = options.root || false; + + var content = []; + + if ( options.root ) { + content.push( render_tree( jsonml ) ); + } + else { + jsonml.shift(); // get rid of the tag + if ( jsonml.length && typeof jsonml[ 0 ] === "object" && !( jsonml[ 0 ] instanceof Array ) ) + jsonml.shift(); // get rid of the attributes + + while ( jsonml.length ) + content.push( render_tree( jsonml.shift() ) ); + } + + return content.join( "\n\n" ); + }; + + + /** + * toHTMLTree( markdown, [dialect] ) -> JsonML + * toHTMLTree( md_tree ) -> JsonML + * - markdown (String): markdown string to parse + * - dialect (String | Dialect): the dialect to use, defaults to gruber + * - md_tree (Markdown.JsonML): parsed markdown tree + * + * Turn markdown into HTML, represented as a JsonML tree. If a string is given + * to this function, it is first parsed into a markdown tree by calling + * [[parse]]. + **/ + Markdown.toHTMLTree = function toHTMLTree( input, dialect , options ) { + + // convert string input to an MD tree + if ( typeof input === "string" ) + input = this.parse( input, dialect ); + + // Now convert the MD tree to an HTML tree + + // remove references from the tree + var attrs = extract_attr( input ), + refs = {}; + + if ( attrs && attrs.references ) + refs = attrs.references; + + var html = convert_tree_to_html( input, refs , options ); + merge_text_nodes( html ); + return html; + }; + + /** + * toHTML( markdown, [dialect] ) -> String + * toHTML( md_tree ) -> String + * - markdown (String): markdown string to parse + * - md_tree (Markdown.JsonML): parsed markdown tree + * + * Take markdown (either as a string or as a JsonML tree) and run it through + * [[toHTMLTree]] then turn it into a well-formated HTML fragment. + **/ + Markdown.toHTML = function toHTML( source , dialect , options ) { + var input = this.toHTMLTree( source , dialect , options ); + + return this.renderJsonML( input ); + }; + + + function escapeHTML( text ) { + return text.replace( /&/g, "&" ) + .replace( //g, ">" ) + .replace( /"/g, """ ) + .replace( /'/g, "'" ); + } + + function render_tree( jsonml ) { + // basic case + if ( typeof jsonml === "string" ) + return escapeHTML( jsonml ); + + var tag = jsonml.shift(), + attributes = {}, + content = []; + + if ( jsonml.length && typeof jsonml[ 0 ] === "object" && !( jsonml[ 0 ] instanceof Array ) ) + attributes = jsonml.shift(); + + while ( jsonml.length ) + content.push( render_tree( jsonml.shift() ) ); + + var tag_attrs = ""; + for ( var a in attributes ) + tag_attrs += " " + a + '="' + escapeHTML( attributes[ a ] ) + '"'; + + // be careful about adding whitespace here for inline elements + if ( tag === "img" || tag === "br" || tag === "hr" ) + return "<"+ tag + tag_attrs + "/>"; + else + return "<"+ tag + tag_attrs + ">" + content.join( "" ) + ""; + } + + function convert_tree_to_html( tree, references, options ) { + var i; + options = options || {}; + + // shallow clone + var jsonml = tree.slice( 0 ); + + if ( typeof options.preprocessTreeNode === "function" ) + jsonml = options.preprocessTreeNode(jsonml, references); + + // Clone attributes if they exist + var attrs = extract_attr( jsonml ); + if ( attrs ) { + jsonml[ 1 ] = {}; + for ( i in attrs ) { + jsonml[ 1 ][ i ] = attrs[ i ]; + } + attrs = jsonml[ 1 ]; + } + + // basic case + if ( typeof jsonml === "string" ) + return jsonml; + + // convert this node + switch ( jsonml[ 0 ] ) { + case "header": + jsonml[ 0 ] = "h" + jsonml[ 1 ].level; + delete jsonml[ 1 ].level; + break; + case "bulletlist": + jsonml[ 0 ] = "ul"; + break; + case "numberlist": + jsonml[ 0 ] = "ol"; + break; + case "listitem": + jsonml[ 0 ] = "li"; + break; + case "para": + jsonml[ 0 ] = "p"; + break; + case "markdown": + jsonml[ 0 ] = "html"; + if ( attrs ) + delete attrs.references; + break; + case "code_block": + jsonml[ 0 ] = "pre"; + i = attrs ? 2 : 1; + var code = [ "code" ]; + code.push.apply( code, jsonml.splice( i, jsonml.length - i ) ); + jsonml[ i ] = code; + break; + case "inlinecode": + jsonml[ 0 ] = "code"; + break; + case "img": + jsonml[ 1 ].src = jsonml[ 1 ].href; + delete jsonml[ 1 ].href; + break; + case "linebreak": + jsonml[ 0 ] = "br"; + break; + case "link": + jsonml[ 0 ] = "a"; + break; + case "link_ref": + jsonml[ 0 ] = "a"; + + // grab this ref and clean up the attribute node + var ref = references[ attrs.ref ]; + + // if the reference exists, make the link + if ( ref ) { + delete attrs.ref; + + // add in the href and title, if present + attrs.href = ref.href; + if ( ref.title ) + attrs.title = ref.title; + + // get rid of the unneeded original text + delete attrs.original; + } + // the reference doesn't exist, so revert to plain text + else { + return attrs.original; + } + break; + case "img_ref": + jsonml[ 0 ] = "img"; + + // grab this ref and clean up the attribute node + var ref = references[ attrs.ref ]; + + // if the reference exists, make the link + if ( ref ) { + delete attrs.ref; + + // add in the href and title, if present + attrs.src = ref.href; + if ( ref.title ) + attrs.title = ref.title; + + // get rid of the unneeded original text + delete attrs.original; + } + // the reference doesn't exist, so revert to plain text + else { + return attrs.original; + } + break; + } + + // convert all the children + i = 1; + + // deal with the attribute node, if it exists + if ( attrs ) { + // if there are keys, skip over it + for ( var key in jsonml[ 1 ] ) { + i = 2; + break; + } + // if there aren't, remove it + if ( i === 1 ) + jsonml.splice( i, 1 ); + } + + for ( ; i < jsonml.length; ++i ) { + jsonml[ i ] = convert_tree_to_html( jsonml[ i ], references, options ); + } + + return jsonml; + } + + + // merges adjacent text nodes into a single node + function merge_text_nodes( jsonml ) { + // skip the tag name and attribute hash + var i = extract_attr( jsonml ) ? 2 : 1; + + while ( i < jsonml.length ) { + // if it's a string check the next item too + if ( typeof jsonml[ i ] === "string" ) { + if ( i + 1 < jsonml.length && typeof jsonml[ i + 1 ] === "string" ) { + // merge the second string into the first and remove it + jsonml[ i ] += jsonml.splice( i + 1, 1 )[ 0 ]; + } + else { + ++i; + } + } + // if it's not a string recurse + else { + merge_text_nodes( jsonml[ i ] ); + ++i; + } + } + }; + + + + var DialectHelpers = {}; + DialectHelpers.inline_until_char = function( text, want ) { + var consumed = 0, + nodes = []; + + while ( true ) { + if ( text.charAt( consumed ) === want ) { + // Found the character we were looking for + consumed++; + return [ consumed, nodes ]; + } + + if ( consumed >= text.length ) { + // No closing char found. Abort. + return null; + } + + var res = this.dialect.inline.__oneElement__.call(this, text.substr( consumed ) ); + consumed += res[ 0 ]; + // Add any returned nodes. + nodes.push.apply( nodes, res.slice( 1 ) ); + } + }; + + // Helper function to make sub-classing a dialect easier + DialectHelpers.subclassDialect = function( d ) { + function Block() {} + Block.prototype = d.block; + function Inline() {} + Inline.prototype = d.inline; + + return { block: new Block(), inline: new Inline() }; + }; + + + + + var forEach = MarkdownHelpers.forEach, + extract_attr = MarkdownHelpers.extract_attr, + mk_block = MarkdownHelpers.mk_block, + isEmpty = MarkdownHelpers.isEmpty, + inline_until_char = DialectHelpers.inline_until_char; + + /** + * Gruber dialect + * + * The default dialect that follows the rules set out by John Gruber's + * markdown.pl as closely as possible. Well actually we follow the behaviour of + * that script which in some places is not exactly what the syntax web page + * says. + **/ + var Gruber = { + block: { + atxHeader: function atxHeader( block, next ) { + var m = block.match( /^(#{1,6})\s*(.*?)\s*#*\s*(?:\n|$)/ ); + + if ( !m ) + return undefined; + + var header = [ "header", { level: m[ 1 ].length } ]; + Array.prototype.push.apply(header, this.processInline(m[ 2 ])); + + if ( m[0].length < block.length ) + next.unshift( mk_block( block.substr( m[0].length ), block.trailing, block.lineNumber + 2 ) ); + + return [ header ]; + }, + + setextHeader: function setextHeader( block, next ) { + var m = block.match( /^(.*)\n([-=])\2\2+(?:\n|$)/ ); + + if ( !m ) + return undefined; + + var level = ( m[ 2 ] === "=" ) ? 1 : 2, + header = [ "header", { level : level }, m[ 1 ] ]; + + if ( m[0].length < block.length ) + next.unshift( mk_block( block.substr( m[0].length ), block.trailing, block.lineNumber + 2 ) ); + + return [ header ]; + }, + + code: function code( block, next ) { + // | Foo + // |bar + // should be a code block followed by a paragraph. Fun + // + // There might also be adjacent code block to merge. + + var ret = [], + re = /^(?: {0,3}\t| {4})(.*)\n?/; + + // 4 spaces + content + if ( !block.match( re ) ) + return undefined; + + block_search: + do { + // Now pull out the rest of the lines + var b = this.loop_re_over_block( + re, block.valueOf(), function( m ) { ret.push( m[1] ); } ); + + if ( b.length ) { + // Case alluded to in first comment. push it back on as a new block + next.unshift( mk_block(b, block.trailing) ); + break block_search; + } + else if ( next.length ) { + // Check the next block - it might be code too + if ( !next[0].match( re ) ) + break block_search; + + // Pull how how many blanks lines follow - minus two to account for .join + ret.push ( block.trailing.replace(/[^\n]/g, "").substring(2) ); + + block = next.shift(); + } + else { + break block_search; + } + } while ( true ); + + return [ [ "code_block", ret.join("\n") ] ]; + }, + + horizRule: function horizRule( block, next ) { + // this needs to find any hr in the block to handle abutting blocks + var m = block.match( /^(?:([\s\S]*?)\n)?[ \t]*([-_*])(?:[ \t]*\2){2,}[ \t]*(?:\n([\s\S]*))?$/ ); + + if ( !m ) + return undefined; + + var jsonml = [ [ "hr" ] ]; + + // if there's a leading abutting block, process it + if ( m[ 1 ] ) { + var contained = mk_block( m[ 1 ], "", block.lineNumber ); + jsonml.unshift.apply( jsonml, this.toTree( contained, [] ) ); + } + + // if there's a trailing abutting block, stick it into next + if ( m[ 3 ] ) + next.unshift( mk_block( m[ 3 ], block.trailing, block.lineNumber + 1 ) ); + + return jsonml; + }, + + // There are two types of lists. Tight and loose. Tight lists have no whitespace + // between the items (and result in text just in the
  • ) and loose lists, + // which have an empty line between list items, resulting in (one or more) + // paragraphs inside the
  • . + // + // There are all sorts weird edge cases about the original markdown.pl's + // handling of lists: + // + // * Nested lists are supposed to be indented by four chars per level. But + // if they aren't, you can get a nested list by indenting by less than + // four so long as the indent doesn't match an indent of an existing list + // item in the 'nest stack'. + // + // * The type of the list (bullet or number) is controlled just by the + // first item at the indent. Subsequent changes are ignored unless they + // are for nested lists + // + lists: (function( ) { + // Use a closure to hide a few variables. + var any_list = "[*+-]|\\d+\\.", + bullet_list = /[*+-]/, + // Capture leading indent as it matters for determining nested lists. + is_list_re = new RegExp( "^( {0,3})(" + any_list + ")[ \t]+" ), + indent_re = "(?: {0,3}\\t| {4})"; + + // TODO: Cache this regexp for certain depths. + // Create a regexp suitable for matching an li for a given stack depth + function regex_for_depth( depth ) { + + return new RegExp( + // m[1] = indent, m[2] = list_type + "(?:^(" + indent_re + "{0," + depth + "} {0,3})(" + any_list + ")\\s+)|" + + // m[3] = cont + "(^" + indent_re + "{0," + (depth-1) + "}[ ]{0,4})" + ); + } + function expand_tab( input ) { + return input.replace( / {0,3}\t/g, " " ); + } + + // Add inline content `inline` to `li`. inline comes from processInline + // so is an array of content + function add(li, loose, inline, nl) { + if ( loose ) { + li.push( [ "para" ].concat(inline) ); + return; + } + // Hmmm, should this be any block level element or just paras? + var add_to = li[li.length -1] instanceof Array && li[li.length - 1][0] === "para" + ? li[li.length -1] + : li; + + // If there is already some content in this list, add the new line in + if ( nl && li.length > 1 ) + inline.unshift(nl); + + for ( var i = 0; i < inline.length; i++ ) { + var what = inline[i], + is_str = typeof what === "string"; + if ( is_str && add_to.length > 1 && typeof add_to[add_to.length-1] === "string" ) + add_to[ add_to.length-1 ] += what; + else + add_to.push( what ); + } + } + + // contained means have an indent greater than the current one. On + // *every* line in the block + function get_contained_blocks( depth, blocks ) { + + var re = new RegExp( "^(" + indent_re + "{" + depth + "}.*?\\n?)*$" ), + replace = new RegExp("^" + indent_re + "{" + depth + "}", "gm"), + ret = []; + + while ( blocks.length > 0 ) { + if ( re.exec( blocks[0] ) ) { + var b = blocks.shift(), + // Now remove that indent + x = b.replace( replace, ""); + + ret.push( mk_block( x, b.trailing, b.lineNumber ) ); + } + else + break; + } + return ret; + } + + // passed to stack.forEach to turn list items up the stack into paras + function paragraphify(s, i, stack) { + var list = s.list; + var last_li = list[list.length-1]; + + if ( last_li[1] instanceof Array && last_li[1][0] === "para" ) + return; + if ( i + 1 === stack.length ) { + // Last stack frame + // Keep the same array, but replace the contents + last_li.push( ["para"].concat( last_li.splice(1, last_li.length - 1) ) ); + } + else { + var sublist = last_li.pop(); + last_li.push( ["para"].concat( last_li.splice(1, last_li.length - 1) ), sublist ); + } + } + + // The matcher function + return function( block, next ) { + var m = block.match( is_list_re ); + if ( !m ) + return undefined; + + function make_list( m ) { + var list = bullet_list.exec( m[2] ) + ? ["bulletlist"] + : ["numberlist"]; + + stack.push( { list: list, indent: m[1] } ); + return list; + } + + + var stack = [], // Stack of lists for nesting. + list = make_list( m ), + last_li, + loose = false, + ret = [ stack[0].list ], + i; + + // Loop to search over block looking for inner block elements and loose lists + loose_search: + while ( true ) { + // Split into lines preserving new lines at end of line + var lines = block.split( /(?=\n)/ ); + + // We have to grab all lines for a li and call processInline on them + // once as there are some inline things that can span lines. + var li_accumulate = "", nl = ""; + + // Loop over the lines in this block looking for tight lists. + tight_search: + for ( var line_no = 0; line_no < lines.length; line_no++ ) { + nl = ""; + var l = lines[line_no].replace(/^\n/, function(n) { nl = n; return ""; }); + + + // TODO: really should cache this + var line_re = regex_for_depth( stack.length ); + + m = l.match( line_re ); + //print( "line:", uneval(l), "\nline match:", uneval(m) ); + + // We have a list item + if ( m[1] !== undefined ) { + // Process the previous list item, if any + if ( li_accumulate.length ) { + add( last_li, loose, this.processInline( li_accumulate ), nl ); + // Loose mode will have been dealt with. Reset it + loose = false; + li_accumulate = ""; + } + + m[1] = expand_tab( m[1] ); + var wanted_depth = Math.floor(m[1].length/4)+1; + //print( "want:", wanted_depth, "stack:", stack.length); + if ( wanted_depth > stack.length ) { + // Deep enough for a nested list outright + //print ( "new nested list" ); + list = make_list( m ); + last_li.push( list ); + last_li = list[1] = [ "listitem" ]; + } + else { + // We aren't deep enough to be strictly a new level. This is + // where Md.pl goes nuts. If the indent matches a level in the + // stack, put it there, else put it one deeper then the + // wanted_depth deserves. + var found = false; + for ( i = 0; i < stack.length; i++ ) { + if ( stack[ i ].indent !== m[1] ) + continue; + + list = stack[ i ].list; + stack.splice( i+1, stack.length - (i+1) ); + found = true; + break; + } + + if (!found) { + //print("not found. l:", uneval(l)); + wanted_depth++; + if ( wanted_depth <= stack.length ) { + stack.splice(wanted_depth, stack.length - wanted_depth); + //print("Desired depth now", wanted_depth, "stack:", stack.length); + list = stack[wanted_depth-1].list; + //print("list:", uneval(list) ); + } + else { + //print ("made new stack for messy indent"); + list = make_list(m); + last_li.push(list); + } + } + + //print( uneval(list), "last", list === stack[stack.length-1].list ); + last_li = [ "listitem" ]; + list.push(last_li); + } // end depth of shenegains + nl = ""; + } + + // Add content + if ( l.length > m[0].length ) + li_accumulate += nl + l.substr( m[0].length ); + } // tight_search + + if ( li_accumulate.length ) { + add( last_li, loose, this.processInline( li_accumulate ), nl ); + // Loose mode will have been dealt with. Reset it + loose = false; + li_accumulate = ""; + } + + // Look at the next block - we might have a loose list. Or an extra + // paragraph for the current li + var contained = get_contained_blocks( stack.length, next ); + + // Deal with code blocks or properly nested lists + if ( contained.length > 0 ) { + // Make sure all listitems up the stack are paragraphs + forEach( stack, paragraphify, this); + + last_li.push.apply( last_li, this.toTree( contained, [] ) ); + } + + var next_block = next[0] && next[0].valueOf() || ""; + + if ( next_block.match(is_list_re) || next_block.match( /^ / ) ) { + block = next.shift(); + + // Check for an HR following a list: features/lists/hr_abutting + var hr = this.dialect.block.horizRule( block, next ); + + if ( hr ) { + ret.push.apply(ret, hr); + break; + } + + // Make sure all listitems up the stack are paragraphs + forEach( stack, paragraphify, this); + + loose = true; + continue loose_search; + } + break; + } // loose_search + + return ret; + }; + })(), + + blockquote: function blockquote( block, next ) { + if ( !block.match( /^>/m ) ) + return undefined; + + var jsonml = []; + + // separate out the leading abutting block, if any. I.e. in this case: + // + // a + // > b + // + if ( block[ 0 ] !== ">" ) { + var lines = block.split( /\n/ ), + prev = [], + line_no = block.lineNumber; + + // keep shifting lines until you find a crotchet + while ( lines.length && lines[ 0 ][ 0 ] !== ">" ) { + prev.push( lines.shift() ); + line_no++; + } + + var abutting = mk_block( prev.join( "\n" ), "\n", block.lineNumber ); + jsonml.push.apply( jsonml, this.processBlock( abutting, [] ) ); + // reassemble new block of just block quotes! + block = mk_block( lines.join( "\n" ), block.trailing, line_no ); + } + + + // if the next block is also a blockquote merge it in + while ( next.length && next[ 0 ][ 0 ] === ">" ) { + var b = next.shift(); + block = mk_block( block + block.trailing + b, b.trailing, block.lineNumber ); + } + + // Strip off the leading "> " and re-process as a block. + var input = block.replace( /^> ?/gm, "" ), + old_tree = this.tree, + processedBlock = this.toTree( input, [ "blockquote" ] ), + attr = extract_attr( processedBlock ); + + // If any link references were found get rid of them + if ( attr && attr.references ) { + delete attr.references; + // And then remove the attribute object if it's empty + if ( isEmpty( attr ) ) + processedBlock.splice( 1, 1 ); + } + + jsonml.push( processedBlock ); + return jsonml; + }, + + referenceDefn: function referenceDefn( block, next) { + var re = /^\s*\[(.*?)\]:\s*(\S+)(?:\s+(?:(['"])(.*?)\3|\((.*?)\)))?\n?/; + // interesting matches are [ , ref_id, url, , title, title ] + + if ( !block.match(re) ) + return undefined; + + // make an attribute node if it doesn't exist + if ( !extract_attr( this.tree ) ) + this.tree.splice( 1, 0, {} ); + + var attrs = extract_attr( this.tree ); + + // make a references hash if it doesn't exist + if ( attrs.references === undefined ) + attrs.references = {}; + + var b = this.loop_re_over_block(re, block, function( m ) { + + if ( m[2] && m[2][0] === "<" && m[2][m[2].length-1] === ">" ) + m[2] = m[2].substring( 1, m[2].length - 1 ); + + var ref = attrs.references[ m[1].toLowerCase() ] = { + href: m[2] + }; + + if ( m[4] !== undefined ) + ref.title = m[4]; + else if ( m[5] !== undefined ) + ref.title = m[5]; + + } ); + + if ( b.length ) + next.unshift( mk_block( b, block.trailing ) ); + + return []; + }, + + para: function para( block ) { + // everything's a para! + return [ ["para"].concat( this.processInline( block ) ) ]; + } + }, + + inline: { + + __oneElement__: function oneElement( text, patterns_or_re, previous_nodes ) { + var m, + res; + + patterns_or_re = patterns_or_re || this.dialect.inline.__patterns__; + var re = new RegExp( "([\\s\\S]*?)(" + (patterns_or_re.source || patterns_or_re) + ")" ); + + m = re.exec( text ); + if (!m) { + // Just boring text + return [ text.length, text ]; + } + else if ( m[1] ) { + // Some un-interesting text matched. Return that first + return [ m[1].length, m[1] ]; + } + + var res; + if ( m[2] in this.dialect.inline ) { + res = this.dialect.inline[ m[2] ].call( + this, + text.substr( m.index ), m, previous_nodes || [] ); + } + // Default for now to make dev easier. just slurp special and output it. + res = res || [ m[2].length, m[2] ]; + return res; + }, + + __call__: function inline( text, patterns ) { + + var out = [], + res; + + function add(x) { + //D:self.debug(" adding output", uneval(x)); + if ( typeof x === "string" && typeof out[out.length-1] === "string" ) + out[ out.length-1 ] += x; + else + out.push(x); + } + + while ( text.length > 0 ) { + res = this.dialect.inline.__oneElement__.call(this, text, patterns, out ); + text = text.substr( res.shift() ); + forEach(res, add ); + } + + return out; + }, + + // These characters are intersting elsewhere, so have rules for them so that + // chunks of plain text blocks don't include them + "]": function () {}, + "}": function () {}, + + __escape__ : /^\\[\\`\*_{}\[\]()#\+.!\-]/, + + "\\": function escaped( text ) { + // [ length of input processed, node/children to add... ] + // Only esacape: \ ` * _ { } [ ] ( ) # * + - . ! + if ( this.dialect.inline.__escape__.exec( text ) ) + return [ 2, text.charAt( 1 ) ]; + else + // Not an esacpe + return [ 1, "\\" ]; + }, + + "![": function image( text ) { + + // Unlike images, alt text is plain text only. no other elements are + // allowed in there + + // ![Alt text](/path/to/img.jpg "Optional title") + // 1 2 3 4 <--- captures + var m = text.match( /^!\[(.*?)\][ \t]*\([ \t]*([^")]*?)(?:[ \t]+(["'])(.*?)\3)?[ \t]*\)/ ); + + if ( m ) { + if ( m[2] && m[2][0] === "<" && m[2][m[2].length-1] === ">" ) + m[2] = m[2].substring( 1, m[2].length - 1 ); + + m[2] = this.dialect.inline.__call__.call( this, m[2], /\\/ )[0]; + + var attrs = { alt: m[1], href: m[2] || "" }; + if ( m[4] !== undefined) + attrs.title = m[4]; + + return [ m[0].length, [ "img", attrs ] ]; + } + + // ![Alt text][id] + m = text.match( /^!\[(.*?)\][ \t]*\[(.*?)\]/ ); + + if ( m ) { + // We can't check if the reference is known here as it likely wont be + // found till after. Check it in md tree->hmtl tree conversion + return [ m[0].length, [ "img_ref", { alt: m[1], ref: m[2].toLowerCase(), original: m[0] } ] ]; + } + + // Just consume the '![' + return [ 2, "![" ]; + }, + + "[": function link( text ) { + + var orig = String(text); + // Inline content is possible inside `link text` + var res = inline_until_char.call( this, text.substr(1), "]" ); + + // No closing ']' found. Just consume the [ + if ( !res ) + return [ 1, "[" ]; + + var consumed = 1 + res[ 0 ], + children = res[ 1 ], + link, + attrs; + + // At this point the first [...] has been parsed. See what follows to find + // out which kind of link we are (reference or direct url) + text = text.substr( consumed ); + + // [link text](/path/to/img.jpg "Optional title") + // 1 2 3 <--- captures + // This will capture up to the last paren in the block. We then pull + // back based on if there a matching ones in the url + // ([here](/url/(test)) + // The parens have to be balanced + var m = text.match( /^\s*\([ \t]*([^"']*)(?:[ \t]+(["'])(.*?)\2)?[ \t]*\)/ ); + if ( m ) { + var url = m[1]; + consumed += m[0].length; + + if ( url && url[0] === "<" && url[url.length-1] === ">" ) + url = url.substring( 1, url.length - 1 ); + + // If there is a title we don't have to worry about parens in the url + if ( !m[3] ) { + var open_parens = 1; // One open that isn't in the capture + for ( var len = 0; len < url.length; len++ ) { + switch ( url[len] ) { + case "(": + open_parens++; + break; + case ")": + if ( --open_parens === 0) { + consumed -= url.length - len; + url = url.substring(0, len); + } + break; + } + } + } + + // Process escapes only + url = this.dialect.inline.__call__.call( this, url, /\\/ )[0]; + + attrs = { href: url || "" }; + if ( m[3] !== undefined) + attrs.title = m[3]; + + link = [ "link", attrs ].concat( children ); + return [ consumed, link ]; + } + + // [Alt text][id] + // [Alt text] [id] + m = text.match( /^\s*\[(.*?)\]/ ); + + if ( m ) { + + consumed += m[ 0 ].length; + + // [links][] uses links as its reference + attrs = { ref: ( m[ 1 ] || String(children) ).toLowerCase(), original: orig.substr( 0, consumed ) }; + + link = [ "link_ref", attrs ].concat( children ); + + // We can't check if the reference is known here as it likely wont be + // found till after. Check it in md tree->hmtl tree conversion. + // Store the original so that conversion can revert if the ref isn't found. + return [ consumed, link ]; + } + + // [id] + // Only if id is plain (no formatting.) + if ( children.length === 1 && typeof children[0] === "string" ) { + + attrs = { ref: children[0].toLowerCase(), original: orig.substr( 0, consumed ) }; + link = [ "link_ref", attrs, children[0] ]; + return [ consumed, link ]; + } + + // Just consume the "[" + return [ 1, "[" ]; + }, + + + "<": function autoLink( text ) { + var m; + + if ( ( m = text.match( /^<(?:((https?|ftp|mailto):[^>]+)|(.*?@.*?\.[a-zA-Z]+))>/ ) ) !== null ) { + if ( m[3] ) + return [ m[0].length, [ "link", { href: "mailto:" + m[3] }, m[3] ] ]; + else if ( m[2] === "mailto" ) + return [ m[0].length, [ "link", { href: m[1] }, m[1].substr("mailto:".length ) ] ]; + else + return [ m[0].length, [ "link", { href: m[1] }, m[1] ] ]; + } + + return [ 1, "<" ]; + }, + + "`": function inlineCode( text ) { + // Inline code block. as many backticks as you like to start it + // Always skip over the opening ticks. + var m = text.match( /(`+)(([\s\S]*?)\1)/ ); + + if ( m && m[2] ) + return [ m[1].length + m[2].length, [ "inlinecode", m[3] ] ]; + else { + // TODO: No matching end code found - warn! + return [ 1, "`" ]; + } + }, + + " \n": function lineBreak() { + return [ 3, [ "linebreak" ] ]; + } + + } + }; + + // Meta Helper/generator method for em and strong handling + function strong_em( tag, md ) { + + var state_slot = tag + "_state", + other_slot = tag === "strong" ? "em_state" : "strong_state"; + + function CloseTag(len) { + this.len_after = len; + this.name = "close_" + md; + } + + return function ( text ) { + + if ( this[state_slot][0] === md ) { + // Most recent em is of this type + //D:this.debug("closing", md); + this[state_slot].shift(); + + // "Consume" everything to go back to the recrusion in the else-block below + return[ text.length, new CloseTag(text.length-md.length) ]; + } + else { + // Store a clone of the em/strong states + var other = this[other_slot].slice(), + state = this[state_slot].slice(); + + this[state_slot].unshift(md); + + //D:this.debug_indent += " "; + + // Recurse + var res = this.processInline( text.substr( md.length ) ); + //D:this.debug_indent = this.debug_indent.substr(2); + + var last = res[res.length - 1]; + + //D:this.debug("processInline from", tag + ": ", uneval( res ) ); + + var check = this[state_slot].shift(); + if ( last instanceof CloseTag ) { + res.pop(); + // We matched! Huzzah. + var consumed = text.length - last.len_after; + return [ consumed, [ tag ].concat(res) ]; + } + else { + // Restore the state of the other kind. We might have mistakenly closed it. + this[other_slot] = other; + this[state_slot] = state; + + // We can't reuse the processed result as it could have wrong parsing contexts in it. + return [ md.length, md ]; + } + } + }; // End returned function + } + + Gruber.inline["**"] = strong_em("strong", "**"); + Gruber.inline["__"] = strong_em("strong", "__"); + Gruber.inline["*"] = strong_em("em", "*"); + Gruber.inline["_"] = strong_em("em", "_"); + + Markdown.dialects.Gruber = Gruber; + Markdown.buildBlockOrder ( Markdown.dialects.Gruber.block ); + Markdown.buildInlinePatterns( Markdown.dialects.Gruber.inline ); + + + + var Maruku = DialectHelpers.subclassDialect( Gruber ), + extract_attr = MarkdownHelpers.extract_attr, + forEach = MarkdownHelpers.forEach; + + Maruku.processMetaHash = function processMetaHash( meta_string ) { + var meta = split_meta_hash( meta_string ), + attr = {}; + + for ( var i = 0; i < meta.length; ++i ) { + // id: #foo + if ( /^#/.test( meta[ i ] ) ) + attr.id = meta[ i ].substring( 1 ); + // class: .foo + else if ( /^\./.test( meta[ i ] ) ) { + // if class already exists, append the new one + if ( attr["class"] ) + attr["class"] = attr["class"] + meta[ i ].replace( /./, " " ); + else + attr["class"] = meta[ i ].substring( 1 ); + } + // attribute: foo=bar + else if ( /\=/.test( meta[ i ] ) ) { + var s = meta[ i ].split( /\=/ ); + attr[ s[ 0 ] ] = s[ 1 ]; + } + } + + return attr; + }; + + function split_meta_hash( meta_string ) { + var meta = meta_string.split( "" ), + parts = [ "" ], + in_quotes = false; + + while ( meta.length ) { + var letter = meta.shift(); + switch ( letter ) { + case " " : + // if we're in a quoted section, keep it + if ( in_quotes ) + parts[ parts.length - 1 ] += letter; + // otherwise make a new part + else + parts.push( "" ); + break; + case "'" : + case '"' : + // reverse the quotes and move straight on + in_quotes = !in_quotes; + break; + case "\\" : + // shift off the next letter to be used straight away. + // it was escaped so we'll keep it whatever it is + letter = meta.shift(); + /* falls through */ + default : + parts[ parts.length - 1 ] += letter; + break; + } + } + + return parts; + } + + Maruku.block.document_meta = function document_meta( block ) { + // we're only interested in the first block + if ( block.lineNumber > 1 ) + return undefined; + + // document_meta blocks consist of one or more lines of `Key: Value\n` + if ( ! block.match( /^(?:\w+:.*\n)*\w+:.*$/ ) ) + return undefined; + + // make an attribute node if it doesn't exist + if ( !extract_attr( this.tree ) ) + this.tree.splice( 1, 0, {} ); + + var pairs = block.split( /\n/ ); + for ( var p in pairs ) { + var m = pairs[ p ].match( /(\w+):\s*(.*)$/ ), + key = m[ 1 ].toLowerCase(), + value = m[ 2 ]; + + this.tree[ 1 ][ key ] = value; + } + + // document_meta produces no content! + return []; + }; + + Maruku.block.block_meta = function block_meta( block ) { + // check if the last line of the block is an meta hash + var m = block.match( /(^|\n) {0,3}\{:\s*((?:\\\}|[^\}])*)\s*\}$/ ); + if ( !m ) + return undefined; + + // process the meta hash + var attr = this.dialect.processMetaHash( m[ 2 ] ), + hash; + + // if we matched ^ then we need to apply meta to the previous block + if ( m[ 1 ] === "" ) { + var node = this.tree[ this.tree.length - 1 ]; + hash = extract_attr( node ); + + // if the node is a string (rather than JsonML), bail + if ( typeof node === "string" ) + return undefined; + + // create the attribute hash if it doesn't exist + if ( !hash ) { + hash = {}; + node.splice( 1, 0, hash ); + } + + // add the attributes in + for ( var a in attr ) + hash[ a ] = attr[ a ]; + + // return nothing so the meta hash is removed + return []; + } + + // pull the meta hash off the block and process what's left + var b = block.replace( /\n.*$/, "" ), + result = this.processBlock( b, [] ); + + // get or make the attributes hash + hash = extract_attr( result[ 0 ] ); + if ( !hash ) { + hash = {}; + result[ 0 ].splice( 1, 0, hash ); + } + + // attach the attributes to the block + for ( var a in attr ) + hash[ a ] = attr[ a ]; + + return result; + }; + + Maruku.block.definition_list = function definition_list( block, next ) { + // one or more terms followed by one or more definitions, in a single block + var tight = /^((?:[^\s:].*\n)+):\s+([\s\S]+)$/, + list = [ "dl" ], + i, m; + + // see if we're dealing with a tight or loose block + if ( ( m = block.match( tight ) ) ) { + // pull subsequent tight DL blocks out of `next` + var blocks = [ block ]; + while ( next.length && tight.exec( next[ 0 ] ) ) + blocks.push( next.shift() ); + + for ( var b = 0; b < blocks.length; ++b ) { + var m = blocks[ b ].match( tight ), + terms = m[ 1 ].replace( /\n$/, "" ).split( /\n/ ), + defns = m[ 2 ].split( /\n:\s+/ ); + + // print( uneval( m ) ); + + for ( i = 0; i < terms.length; ++i ) + list.push( [ "dt", terms[ i ] ] ); + + for ( i = 0; i < defns.length; ++i ) { + // run inline processing over the definition + list.push( [ "dd" ].concat( this.processInline( defns[ i ].replace( /(\n)\s+/, "$1" ) ) ) ); + } + } + } + else { + return undefined; + } + + return [ list ]; + }; + + // splits on unescaped instances of @ch. If @ch is not a character the result + // can be unpredictable + + Maruku.block.table = function table ( block ) { + + var _split_on_unescaped = function( s, ch ) { + ch = ch || '\\s'; + if ( ch.match(/^[\\|\[\]{}?*.+^$]$/) ) + ch = '\\' + ch; + var res = [ ], + r = new RegExp('^((?:\\\\.|[^\\\\' + ch + '])*)' + ch + '(.*)'), + m; + while ( ( m = s.match( r ) ) ) { + res.push( m[1] ); + s = m[2]; + } + res.push(s); + return res; + }; + + var leading_pipe = /^ {0,3}\|(.+)\n {0,3}\|\s*([\-:]+[\-| :]*)\n((?:\s*\|.*(?:\n|$))*)(?=\n|$)/, + // find at least an unescaped pipe in each line + no_leading_pipe = /^ {0,3}(\S(?:\\.|[^\\|])*\|.*)\n {0,3}([\-:]+\s*\|[\-| :]*)\n((?:(?:\\.|[^\\|])*\|.*(?:\n|$))*)(?=\n|$)/, + i, + m; + if ( ( m = block.match( leading_pipe ) ) ) { + // remove leading pipes in contents + // (header and horizontal rule already have the leading pipe left out) + m[3] = m[3].replace(/^\s*\|/gm, ''); + } else if ( ! ( m = block.match( no_leading_pipe ) ) ) { + return undefined; + } + + var table = [ "table", [ "thead", [ "tr" ] ], [ "tbody" ] ]; + + // remove trailing pipes, then split on pipes + // (no escaped pipes are allowed in horizontal rule) + m[2] = m[2].replace(/\|\s*$/, '').split('|'); + + // process alignment + var html_attrs = [ ]; + forEach (m[2], function (s) { + if (s.match(/^\s*-+:\s*$/)) + html_attrs.push({align: "right"}); + else if (s.match(/^\s*:-+\s*$/)) + html_attrs.push({align: "left"}); + else if (s.match(/^\s*:-+:\s*$/)) + html_attrs.push({align: "center"}); + else + html_attrs.push({}); + }); + + // now for the header, avoid escaped pipes + m[1] = _split_on_unescaped(m[1].replace(/\|\s*$/, ''), '|'); + for (i = 0; i < m[1].length; i++) { + table[1][1].push(['th', html_attrs[i] || {}].concat( + this.processInline(m[1][i].trim()))); + } + + // now for body contents + forEach (m[3].replace(/\|\s*$/mg, '').split('\n'), function (row) { + var html_row = ['tr']; + row = _split_on_unescaped(row, '|'); + for (i = 0; i < row.length; i++) + html_row.push(['td', html_attrs[i] || {}].concat(this.processInline(row[i].trim()))); + table[2].push(html_row); + }, this); + + return [table]; + }; + + Maruku.inline[ "{:" ] = function inline_meta( text, matches, out ) { + if ( !out.length ) + return [ 2, "{:" ]; + + // get the preceeding element + var before = out[ out.length - 1 ]; + + if ( typeof before === "string" ) + return [ 2, "{:" ]; + + // match a meta hash + var m = text.match( /^\{:\s*((?:\\\}|[^\}])*)\s*\}/ ); + + // no match, false alarm + if ( !m ) + return [ 2, "{:" ]; + + // attach the attributes to the preceeding element + var meta = this.dialect.processMetaHash( m[ 1 ] ), + attr = extract_attr( before ); + + if ( !attr ) { + attr = {}; + before.splice( 1, 0, attr ); + } + + for ( var k in meta ) + attr[ k ] = meta[ k ]; + + // cut out the string and replace it with nothing + return [ m[ 0 ].length, "" ]; + }; + + + Markdown.dialects.Maruku = Maruku; + Markdown.dialects.Maruku.inline.__escape__ = /^\\[\\`\*_{}\[\]()#\+.!\-|:]/; + Markdown.buildBlockOrder ( Markdown.dialects.Maruku.block ); + Markdown.buildInlinePatterns( Markdown.dialects.Maruku.inline ); + + +// Include all our depndencies and; + expose.Markdown = Markdown; + expose.parse = Markdown.parse; + expose.toHTML = Markdown.toHTML; + expose.toHTMLTree = Markdown.toHTMLTree; + expose.renderJsonML = Markdown.renderJsonML; + +})(function() { + window.markdown = {}; + return window.markdown; +}()); diff --git a/WebContent/stat/js/core/markdown.min.js b/WebContent/stat/js/core/markdown.min.js new file mode 100644 index 0000000..68a1b45 --- /dev/null +++ b/WebContent/stat/js/core/markdown.min.js @@ -0,0 +1 @@ +!function(a){function b(){return"Markdown.mk_block( "+uneval(this.toString())+", "+uneval(this.trailing)+", "+uneval(this.lineNumber)+" )"}function c(){var a=require("util");return"Markdown.mk_block( "+a.inspect(this.toString())+", "+a.inspect(this.trailing)+", "+a.inspect(this.lineNumber)+" )"}function d(a){for(var b=0,c=-1;-1!==(c=a.indexOf("\n",c+1));)b++;return b}function e(a){return a.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function f(a){if("string"==typeof a)return e(a);var b=a.shift(),c={},d=[];for(!a.length||"object"!=typeof a[0]||a[0]instanceof Array||(c=a.shift());a.length;)d.push(f(a.shift()));var g="";for(var h in c)g+=" "+h+'="'+e(c[h])+'"';return"img"===b||"br"===b||"hr"===b?"<"+b+g+"/>":"<"+b+g+">"+d.join("")+""}function g(a,b,c){var d;c=c||{};var e=a.slice(0);"function"==typeof c.preprocessTreeNode&&(e=c.preprocessTreeNode(e,b));var f=o(e);if(f){e[1]={};for(d in f)e[1][d]=f[d];f=e[1]}if("string"==typeof e)return e;switch(e[0]){case"header":e[0]="h"+e[1].level,delete e[1].level;break;case"bulletlist":e[0]="ul";break;case"numberlist":e[0]="ol";break;case"listitem":e[0]="li";break;case"para":e[0]="p";break;case"markdown":e[0]="html",f&&delete f.references;break;case"code_block":e[0]="pre",d=f?2:1;var h=["code"];h.push.apply(h,e.splice(d,e.length-d)),e[d]=h;break;case"inlinecode":e[0]="code";break;case"img":e[1].src=e[1].href,delete e[1].href;break;case"linebreak":e[0]="br";break;case"link":e[0]="a";break;case"link_ref":e[0]="a";var i=b[f.ref];if(!i)return f.original;delete f.ref,f.href=i.href,i.title&&(f.title=i.title),delete f.original;break;case"img_ref":e[0]="img";var i=b[f.ref];if(!i)return f.original;delete f.ref,f.src=i.href,i.title&&(f.title=i.title),delete f.original}if(d=1,f){for(var j in e[1]){d=2;break}1===d&&e.splice(d,1)}for(;d1&&"object"==typeof a[1]&&!l(a[1])?a[1]:void 0};var m=function(a){switch(typeof a){case"undefined":this.dialect=m.dialects.Gruber;break;case"object":this.dialect=a;break;default:if(!(a in m.dialects))throw new Error("Unknown Markdown dialect '"+String(a)+"'");this.dialect=m.dialects[a]}this.em_state=[],this.strong_state=[],this.debug_indent=""};m.dialects={};var n=m.mk_block=k.mk_block,l=k.isArray;m.parse=function(a,b){var c=new m(b);return c.toTree(a)},m.prototype.split_blocks=function(a){a=a.replace(/(\r\n|\n|\r)/g,"\n");var b,c=/([\s\S]+?)($|\n#|\n(?:\s*\n|$)+)/g,e=[],f=1;for(null!==(b=/^(\s*\n)/.exec(a))&&(f+=d(b[0]),c.lastIndex=b[0].length);null!==(b=c.exec(a));)"\n#"===b[2]&&(b[2]="\n",c.lastIndex--),e.push(n(b[1],b[2],f)),f+=d(b[0]);return e},m.prototype.processBlock=function(a,b){var c=this.dialect.block,d=c.__order__;if("__call__"in c)return c.__call__.call(this,a,b);for(var e=0;e0&&!l(f[0]))&&this.debug(d[e],"didn't return a proper array"),f}return[]},m.prototype.processInline=function(a){return this.dialect.inline.__call__.call(this,String(a))},m.prototype.toTree=function(a,b){var c=a instanceof Array?a:this.split_blocks(a),d=this.tree;try{for(this.tree=b||this.tree||["markdown"];c.length;){var e=this.processBlock(c.shift(),c);e.length&&this.tree.push.apply(this.tree,e)}return this.tree}finally{b&&(this.tree=d)}},m.prototype.debug=function(){var a=Array.prototype.slice.call(arguments);a.unshift(this.debug_indent),"undefined"!=typeof print&&print.apply(print,a),"undefined"!=typeof console&&"undefined"!=typeof console.log&&console.log.apply(null,a)},m.prototype.loop_re_over_block=function(a,b,c){for(var d,e=b.valueOf();e.length&&null!==(d=a.exec(e));)e=e.substr(d[0].length),c.call(this,d);return e},m.buildBlockOrder=function(a){var b=[];for(var c in a)"__order__"!==c&&"__call__"!==c&&b.push(c);a.__order__=b},m.buildInlinePatterns=function(a){var b=[];for(var c in a)if(!c.match(/^__.*__$/)){var d=c.replace(/([\\.*+?|()\[\]{}])/g,"\\$1").replace(/\n/,"\\n");b.push(1===c.length?d:"(?:"+d+")")}b=b.join("|"),a.__patterns__=b;var e=a.__call__;a.__call__=function(a,c){return void 0!==c?e.call(this,a,c):e.call(this,a,b)}};var o=k.extract_attr;m.renderJsonML=function(a,b){b=b||{},b.root=b.root||!1;var c=[];if(b.root)c.push(f(a));else for(a.shift(),!a.length||"object"!=typeof a[0]||a[0]instanceof Array||a.shift();a.length;)c.push(f(a.shift()));return c.join("\n\n")},m.toHTMLTree=function(a,b,c){"string"==typeof a&&(a=this.parse(a,b));var d=o(a),e={};d&&d.references&&(e=d.references);var f=g(a,e,c);return h(f),f},m.toHTML=function(a,b,c){var d=this.toHTMLTree(a,b,c);return this.renderJsonML(d)};var p={};p.inline_until_char=function(a,b){for(var c=0,d=[];;){if(a.charAt(c)===b)return c++,[c,d];if(c>=a.length)return null;var e=this.dialect.inline.__oneElement__.call(this,a.substr(c));c+=e[0],d.push.apply(d,e.slice(1))}},p.subclassDialect=function(a){function b(){}function c(){}return b.prototype=a.block,c.prototype=a.inline,{block:new b,inline:new c}};var q=k.forEach,o=k.extract_attr,n=k.mk_block,r=k.isEmpty,s=p.inline_until_char,t={block:{atxHeader:function(a,b){var c=a.match(/^(#{1,6})\s*(.*?)\s*#*\s*(?:\n|$)/);if(!c)return void 0;var d=["header",{level:c[1].length}];return Array.prototype.push.apply(d,this.processInline(c[2])),c[0].length1&&c.unshift(d);for(var f=0;f1&&"string"==typeof e[e.length-1]?e[e.length-1]+=g:e.push(g)}}function d(a,b){for(var c=new RegExp("^("+i+"{"+a+"}.*?\\n?)*$"),d=new RegExp("^"+i+"{"+a+"}","gm"),e=[];b.length>0&&c.exec(b[0]);){var f=b.shift(),g=f.replace(d,"");e.push(n(g,f.trailing,f.lineNumber))}return e}function e(a,b,c){var d=a.list,e=d[d.length-1];if(!(e[1]instanceof Array&&"para"===e[1][0]))if(b+1===c.length)e.push(["para"].concat(e.splice(1,e.length-1)));else{var f=e.pop();e.push(["para"].concat(e.splice(1,e.length-1)),f)}}var f="[*+-]|\\d+\\.",g=/[*+-]/,h=new RegExp("^( {0,3})("+f+")[ ]+"),i="(?: {0,3}\\t| {4})";return function(f,i){function j(a){var b=g.exec(a[2])?["bulletlist"]:["numberlist"];return n.push({list:b,indent:a[1]}),b}var k=f.match(h);if(!k)return void 0;for(var l,m,n=[],o=j(k),p=!1,r=[n[0].list];;){for(var s=f.split(/(?=\n)/),t="",u="",v=0;vn.length)o=j(k),l.push(o),l=o[1]=["listitem"];else{var z=!1;for(m=0;mk[0].length&&(t+=u+w.substr(k[0].length))}t.length&&(c(l,p,this.processInline(t),u),p=!1,t="");var A=d(n.length,i);A.length>0&&(q(n,e,this),l.push.apply(l,this.toTree(A,[])));var B=i[0]&&i[0].valueOf()||"";if(!B.match(h)&&!B.match(/^ /))break;f=i.shift();var C=this.dialect.block.horizRule(f,i);if(C){r.push.apply(r,C);break}q(n,e,this),p=!0}return r}}(),blockquote:function(a,b){if(!a.match(/^>/m))return void 0;var c=[];if(">"!==a[0]){for(var d=a.split(/\n/),e=[],f=a.lineNumber;d.length&&">"!==d[0][0];)e.push(d.shift()),f++;var g=n(e.join("\n"),"\n",a.lineNumber);c.push.apply(c,this.processBlock(g,[])),a=n(d.join("\n"),a.trailing,f)}for(;b.length&&">"===b[0][0];){var h=b.shift();a=n(a+a.trailing+h,h.trailing,a.lineNumber)}var i=a.replace(/^> ?/gm,""),j=(this.tree,this.toTree(i,["blockquote"])),k=o(j);return k&&k.references&&(delete k.references,r(k)&&j.splice(1,1)),c.push(j),c},referenceDefn:function(a,b){var c=/^\s*\[(.*?)\]:\s*(\S+)(?:\s+(?:(['"])(.*?)\3|\((.*?)\)))?\n?/;if(!a.match(c))return void 0;o(this.tree)||this.tree.splice(1,0,{});var d=o(this.tree);void 0===d.references&&(d.references={});var e=this.loop_re_over_block(c,a,function(a){a[2]&&"<"===a[2][0]&&">"===a[2][a[2].length-1]&&(a[2]=a[2].substring(1,a[2].length-1));var b=d.references[a[1].toLowerCase()]={href:a[2]};void 0!==a[4]?b.title=a[4]:void 0!==a[5]&&(b.title=a[5])});return e.length&&b.unshift(n(e,a.trailing)),[]},para:function(a){return[["para"].concat(this.processInline(a))]}},inline:{__oneElement__:function(a,b,c){var d,e;b=b||this.dialect.inline.__patterns__;var f=new RegExp("([\\s\\S]*?)("+(b.source||b)+")");if(d=f.exec(a),!d)return[a.length,a];if(d[1])return[d[1].length,d[1]];var e;return d[2]in this.dialect.inline&&(e=this.dialect.inline[d[2]].call(this,a.substr(d.index),d,c||[])),e=e||[d[2].length,d[2]]},__call__:function(a,b){function c(a){"string"==typeof a&&"string"==typeof e[e.length-1]?e[e.length-1]+=a:e.push(a)}for(var d,e=[];a.length>0;)d=this.dialect.inline.__oneElement__.call(this,a,b,e),a=a.substr(d.shift()),q(d,c);return e},"]":function(){},"}":function(){},__escape__:/^\\[\\`\*_{}\[\]()#\+.!\-]/,"\\":function(a){return this.dialect.inline.__escape__.exec(a)?[2,a.charAt(1)]:[1,"\\"]},"![":function(a){var b=a.match(/^!\[(.*?)\][ \t]*\([ \t]*([^")]*?)(?:[ \t]+(["'])(.*?)\3)?[ \t]*\)/);if(b){b[2]&&"<"===b[2][0]&&">"===b[2][b[2].length-1]&&(b[2]=b[2].substring(1,b[2].length-1)),b[2]=this.dialect.inline.__call__.call(this,b[2],/\\/)[0];var c={alt:b[1],href:b[2]||""};return void 0!==b[4]&&(c.title=b[4]),[b[0].length,["img",c]]}return b=a.match(/^!\[(.*?)\][ \t]*\[(.*?)\]/),b?[b[0].length,["img_ref",{alt:b[1],ref:b[2].toLowerCase(),original:b[0]}]]:[2,"!["]},"[":function v(a){var b=String(a),c=s.call(this,a.substr(1),"]");if(!c)return[1,"["];var v,d,e=1+c[0],f=c[1];a=a.substr(e);var g=a.match(/^\s*\([ \t]*([^"']*)(?:[ \t]+(["'])(.*?)\2)?[ \t]*\)/);if(g){var h=g[1];if(e+=g[0].length,h&&"<"===h[0]&&">"===h[h.length-1]&&(h=h.substring(1,h.length-1)),!g[3])for(var i=1,j=0;j]+)|(.*?@.*?\.[a-zA-Z]+))>/))?b[3]?[b[0].length,["link",{href:"mailto:"+b[3]},b[3]]]:"mailto"===b[2]?[b[0].length,["link",{href:b[1]},b[1].substr("mailto:".length)]]:[b[0].length,["link",{href:b[1]},b[1]]]:[1,"<"]},"`":function(a){var b=a.match(/(`+)(([\s\S]*?)\1)/);return b&&b[2]?[b[1].length+b[2].length,["inlinecode",b[3]]]:[1,"`"]}," \n":function(){return[3,["linebreak"]]}}};t.inline["**"]=i("strong","**"),t.inline.__=i("strong","__"),t.inline["*"]=i("em","*"),t.inline._=i("em","_"),m.dialects.Gruber=t,m.buildBlockOrder(m.dialects.Gruber.block),m.buildInlinePatterns(m.dialects.Gruber.inline);var u=p.subclassDialect(t),o=k.extract_attr,q=k.forEach;u.processMetaHash=function(a){for(var b=j(a),c={},d=0;d1)return void 0;if(!a.match(/^(?:\w+:.*\n)*\w+:.*$/))return void 0;o(this.tree)||this.tree.splice(1,0,{});var b=a.split(/\n/);for(var c in b){var d=b[c].match(/(\w+):\s*(.*)$/),e=d[1].toLowerCase(),f=d[2];this.tree[1][e]=f}return[]},u.block.block_meta=function(a){var b=a.match(/(^|\n) {0,3}\{:\s*((?:\\\}|[^\}])*)\s*\}$/);if(!b)return void 0;var c,d=this.dialect.processMetaHash(b[2]);if(""===b[1]){var e=this.tree[this.tree.length-1];if(c=o(e),"string"==typeof e)return void 0;c||(c={},e.splice(1,0,c));for(var f in d)c[f]=d[f];return[]}var g=a.replace(/\n.*$/,""),h=this.processBlock(g,[]);c=o(h[0]),c||(c={},h[0].splice(1,0,c));for(var f in d)c[f]=d[f];return h},u.block.definition_list=function(a,b){var c,d,e=/^((?:[^\s:].*\n)+):\s+([\s\S]+)$/,f=["dl"];if(!(d=a.match(e)))return void 0;for(var g=[a];b.length&&e.exec(b[0]);)g.push(b.shift());for(var h=0;h