├── .gitignore ├── README.md ├── TODO.txt ├── _attachments ├── app.html ├── apps.html ├── images │ ├── couchapp.png │ ├── icon.png │ └── tile.png ├── index.html ├── script │ ├── app.js │ ├── jquery.scrollTo.js │ └── md5.js └── style │ └── main.css ├── couchapp.json ├── evently ├── apps │ └── _init │ │ ├── data.js │ │ ├── mustache.html │ │ ├── query.json │ │ └── render.txt ├── garden │ └── _init │ │ ├── after.js │ │ ├── async.js │ │ ├── data.js │ │ └── mustache.html ├── installs │ ├── load │ │ ├── after.js │ │ ├── path.txt │ │ └── xasync.js │ └── render │ │ ├── data.js │ │ ├── mustache.html │ │ └── selectors │ │ └── a.share │ │ └── click.js └── shares │ └── render │ ├── after.js │ ├── data.js │ ├── mustache.html │ ├── query.js │ ├── render.txt │ └── selectors │ └── form │ ├── change.js │ └── submit.js ├── lib └── garden.js ├── vendor └── couchapp │ ├── README.md │ ├── _attachments │ ├── docs.css │ ├── docs.html │ ├── docs.js │ ├── jquery.couch.app.js │ ├── jquery.couch.app.util.js │ ├── jquery.evently.js │ ├── jquery.mustache.js │ └── jquery.pathbinder.js │ ├── docs │ ├── account.md │ ├── couchapp.md │ ├── docs.md │ ├── evently.md │ ├── pathbinder.md │ └── profile.md │ ├── evently │ ├── account │ │ ├── _init.js │ │ ├── adminParty.js │ │ ├── doLogin.js │ │ ├── doLogout.js │ │ ├── doSignup.js │ │ ├── loggedIn │ │ │ ├── after.js │ │ │ ├── data.js │ │ │ ├── mustache.html │ │ │ └── selectors.json │ │ ├── loggedOut │ │ │ ├── mustache.html │ │ │ └── selectors.json │ │ ├── loginForm │ │ │ ├── after.js │ │ │ ├── mustache.html │ │ │ └── selectors │ │ │ │ ├── a[href=#signup].json │ │ │ │ └── form │ │ │ │ └── submit.js │ │ └── signupForm │ │ │ ├── after.js │ │ │ ├── mustache.html │ │ │ └── selectors │ │ │ ├── a[href=#login].json │ │ │ └── form │ │ │ └── submit.js │ ├── docs │ │ ├── index │ │ │ ├── data.js │ │ │ ├── mustache.html │ │ │ └── path.txt │ │ └── topic │ │ │ ├── after.js │ │ │ ├── data.js │ │ │ ├── edit │ │ │ └── _init │ │ │ │ ├── fun.js │ │ │ │ └── selectors │ │ │ │ ├── a.edit │ │ │ │ └── click.js │ │ │ │ └── a.run │ │ │ │ └── click.js │ │ │ ├── mustache.html │ │ │ └── path.txt │ └── profile │ │ ├── loggedIn.js │ │ ├── loggedOut │ │ ├── after.js │ │ └── mustache.html │ │ ├── noProfile │ │ ├── data.js │ │ ├── mustache.html │ │ └── selectors │ │ │ └── form │ │ │ └── submit.js │ │ └── profileReady │ │ ├── after.js │ │ ├── data.js │ │ └── mustache.html │ ├── lib │ ├── atom.js │ ├── cache.js │ ├── docform.js │ ├── list.js │ ├── markdown.js │ ├── path.js │ └── redirect.js │ └── metadata.json └── views └── apps └── map.js /.gitignore: -------------------------------------------------------------------------------- 1 | .couchapprc -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## CouchApp Garden 2 | 3 | I thought it would be fun to have a way to see all my installed CouchApps, so I made this. 4 | 5 | I hope you like it. 6 | 7 | If it doesn't run on your system, let me know -- it's pretty basic, so it should be easy to figure out. 8 | 9 | I'm following the #evently hashtag on twitter if people need assistance. 10 | 11 | Requires CouchDB 0.11 12 | 13 | Screenshot: 14 | 15 | [Screenshot of a list of CouchApps with icons and links](http://github.com/jchris/garden/blob/master/_attachments/images/icon.png) 16 | 17 | Patches welcome! 18 | -------------------------------------------------------------------------------- /TODO.txt: -------------------------------------------------------------------------------- 1 | share this app! (Can do without query) 2 | shared_by should be profile 3 | copy app to garden db 4 | install this app 5 | pick a db 6 | copy to ddoc 7 | record install rev for noticing edits 8 | 9 | make index info as semantic html in a list function 10 | 11 | evently shared templates 12 | 13 | replication manager / db 14 | 15 | elsewhere: 16 | jchrisa.net 17 | plok.org 18 | couchapp.org 19 | etc 20 | +1 new 21 | 22 | for each: 23 | replicate 24 | app (push / pull) 25 | data (push / pull) 26 | 27 | 28 | versions: 29 | drl 1-rev 30 | sofa 2-rev 31 | 32 | 33 | 34 | Sofa, running in: 35 | 36 | [Daytime Running Lights](db.html#/db/drl) 37 | [jchris/sofa](source username when self rev match -- unedited) 38 | [Old Drl](db.html#/db/drl-old) 39 | [jchris/sofa]() update (when unedited but not same as same-users-shared) 40 | [Couchio Talk](db.html#/db/talk) 41 | [couchio/sofa]() 42 | [Sofa](db.html#/db/sofa) 43 | [sofa]() share (if rev no match) 44 | 45 | function db_link_username() { 46 | unedited 47 | username 48 | edited 49 | if (usename == me) 50 | me 51 | else 52 | remove username 53 | end 54 | } 55 | 56 | update() { 57 | unedited && shared[username].rev != my rev 58 | } 59 | 60 | edited() { 61 | install_rev != ddoc_rev 62 | // store in install record 63 | (could we use rev prefix?) 64 | } 65 | 66 | share() { 67 | edited || !doc.garden 68 | } 69 | 70 | Shared Versions: 71 | 72 | [couchio/sofa](shared/couchio/_design/sofa) 73 | Install 74 | [jchris/sofa](shared/jchris/_design/sofa) 75 | Install 76 | on click 77 | to which db? 78 | drl 79 | drl-old 80 | sofa 81 | + other / new 82 | 83 | 84 | [oreillymedia/sofa](shared/oreillymedia/_design/sofa) 85 | Install 86 | [benoit/sofa](shared/benoit/_design/sofa) 87 | Install -------------------------------------------------------------------------------- /_attachments/app.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Share and Update : CouchApp Garden 5 | 6 | 7 | 8 |
9 |

CouchApp Garden -- App Info

10 |

Back to my apps

11 | 12 |
13 |

Shared versions of App:

14 | 16 |
17 | 18 |
19 |

App is installed in these databases:

20 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /_attachments/apps.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | CouchApp Garden 5 | 6 | 7 | 8 |
9 |

CouchApp Garden

10 |

Install these CouchApps.

11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /_attachments/images/couchapp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jchris/garden/7238b9b182b56e3d3311419cb9673f9ea9709ccb/_attachments/images/couchapp.png -------------------------------------------------------------------------------- /_attachments/images/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jchris/garden/7238b9b182b56e3d3311419cb9673f9ea9709ccb/_attachments/images/icon.png -------------------------------------------------------------------------------- /_attachments/images/tile.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jchris/garden/7238b9b182b56e3d3311419cb9673f9ea9709ccb/_attachments/images/tile.png -------------------------------------------------------------------------------- /_attachments/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | CouchApp Garden 5 | 6 | 7 | 8 |
9 |

CouchApp Garden

10 |

Easy access to all your CouchApps. Browse available apps.

11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /_attachments/script/app.js: -------------------------------------------------------------------------------- 1 | $.couch.app(function() { 2 | var app = this; 3 | 4 | // $("#garden").evently(app.ddoc.evently.garden, app); 5 | // $("#replicate").evently(app.ddoc.evently.replicate, app); 6 | $("#account").evently(app.ddoc.vendor.couchapp.evently.account, app); 7 | 8 | // $.pathbinder.begin("/"); 9 | 10 | 11 | 12 | 13 | // give an option to copy those ddocs to the garden db for sharing 14 | 15 | // ability to replicate remote gardens into the local garden 16 | 17 | // bookmark remote gardens info in the garden, so that that info also replicates 18 | // remote garden bookmarks should have non-uuid docids to prevent duplicate entries for popular sources? 19 | 20 | // ability to install ddocs in the local garden into local databases 21 | // this should have a warning! 22 | }); -------------------------------------------------------------------------------- /_attachments/script/jquery.scrollTo.js: -------------------------------------------------------------------------------- 1 | /** 2 | * jQuery.ScrollTo - Easy element scrolling using jQuery. 3 | * Copyright (c) 2007-2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com 4 | * Dual licensed under MIT and GPL. 5 | * Date: 9/11/2008 6 | * @author Ariel Flesler 7 | * @version 1.4 8 | * 9 | * http://flesler.blogspot.com/2007/10/jqueryscrollto.html 10 | */ 11 | ;(function(h){var m=h.scrollTo=function(b,c,g){h(window).scrollTo(b,c,g)};m.defaults={axis:'y',duration:1};m.window=function(b){return h(window).scrollable()};h.fn.scrollable=function(){return this.map(function(){var b=this.parentWindow||this.defaultView,c=this.nodeName=='#document'?b.frameElement||b:this,g=c.contentDocument||(c.contentWindow||c).document,i=c.setInterval;return c.nodeName=='IFRAME'||i&&h.browser.safari?g.body:i?g.documentElement:this})};h.fn.scrollTo=function(r,j,a){if(typeof j=='object'){a=j;j=0}if(typeof a=='function')a={onAfter:a};a=h.extend({},m.defaults,a);j=j||a.speed||a.duration;a.queue=a.queue&&a.axis.length>1;if(a.queue)j/=2;a.offset=n(a.offset);a.over=n(a.over);return this.scrollable().each(function(){var k=this,o=h(k),d=r,l,e={},p=o.is('html,body');switch(typeof d){case'number':case'string':if(/^([+-]=)?\d+(px)?$/.test(d)){d=n(d);break}d=h(d,this);case'object':if(d.is||d.style)l=(d=h(d)).offset()}h.each(a.axis.split(''),function(b,c){var g=c=='x'?'Left':'Top',i=g.toLowerCase(),f='scroll'+g,s=k[f],t=c=='x'?'Width':'Height',v=t.toLowerCase();if(l){e[f]=l[i]+(p?0:s-o.offset()[i]);if(a.margin){e[f]-=parseInt(d.css('margin'+g))||0;e[f]-=parseInt(d.css('border'+g+'Width'))||0}e[f]+=a.offset[i]||0;if(a.over[i])e[f]+=d[v]()*a.over[i]}else e[f]=d[i];if(/^\d+$/.test(e[f]))e[f]=e[f]<=0?0:Math.min(e[f],u(t));if(!b&&a.queue){if(s!=e[f])q(a.onAfterFirst);delete e[f]}});q(a.onAfter);function q(b){o.animate(e,j,a.easing,b&&function(){b.call(this,r,a)})};function u(b){var c='scroll'+b,g=k.ownerDocument;return p?Math.max(g.documentElement[c],g.body[c]):k[c]}}).end()};function n(b){return typeof b=='object'?b:{top:b,left:b}}})(jQuery); -------------------------------------------------------------------------------- /_attachments/script/md5.js: -------------------------------------------------------------------------------- 1 | /* 2 | * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message 3 | * Digest Algorithm, as defined in RFC 1321. 4 | * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002. 5 | * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet 6 | * Distributed under the BSD License 7 | * See http://pajhome.org.uk/crypt/md5 for more info. 8 | */ 9 | 10 | /* 11 | * Configurable variables. You may need to tweak these to be compatible with 12 | * the server-side, but the defaults work in most cases. 13 | */ 14 | var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */ 15 | var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */ 16 | var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */ 17 | 18 | /* 19 | * These are the functions you'll usually want to call 20 | * They take string arguments and return either hex or base-64 encoded strings 21 | */ 22 | function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));} 23 | function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));} 24 | function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));} 25 | function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); } 26 | function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); } 27 | function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); } 28 | 29 | /* 30 | * Perform a simple self-test to see if the VM is working 31 | */ 32 | function md5_vm_test() 33 | { 34 | return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72"; 35 | } 36 | 37 | /* 38 | * Calculate the MD5 of an array of little-endian words, and a bit length 39 | */ 40 | function core_md5(x, len) 41 | { 42 | /* append padding */ 43 | x[len >> 5] |= 0x80 << ((len) % 32); 44 | x[(((len + 64) >>> 9) << 4) + 14] = len; 45 | 46 | var a = 1732584193; 47 | var b = -271733879; 48 | var c = -1732584194; 49 | var d = 271733878; 50 | 51 | for(var i = 0; i < x.length; i += 16) 52 | { 53 | var olda = a; 54 | var oldb = b; 55 | var oldc = c; 56 | var oldd = d; 57 | 58 | a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936); 59 | d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586); 60 | c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819); 61 | b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330); 62 | a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897); 63 | d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426); 64 | c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341); 65 | b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983); 66 | a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416); 67 | d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417); 68 | c = md5_ff(c, d, a, b, x[i+10], 17, -42063); 69 | b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162); 70 | a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682); 71 | d = md5_ff(d, a, b, c, x[i+13], 12, -40341101); 72 | c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290); 73 | b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329); 74 | 75 | a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510); 76 | d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632); 77 | c = md5_gg(c, d, a, b, x[i+11], 14, 643717713); 78 | b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302); 79 | a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691); 80 | d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083); 81 | c = md5_gg(c, d, a, b, x[i+15], 14, -660478335); 82 | b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848); 83 | a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438); 84 | d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690); 85 | c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961); 86 | b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501); 87 | a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467); 88 | d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784); 89 | c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473); 90 | b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734); 91 | 92 | a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558); 93 | d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463); 94 | c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562); 95 | b = md5_hh(b, c, d, a, x[i+14], 23, -35309556); 96 | a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060); 97 | d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353); 98 | c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632); 99 | b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640); 100 | a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174); 101 | d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222); 102 | c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979); 103 | b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189); 104 | a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487); 105 | d = md5_hh(d, a, b, c, x[i+12], 11, -421815835); 106 | c = md5_hh(c, d, a, b, x[i+15], 16, 530742520); 107 | b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651); 108 | 109 | a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844); 110 | d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415); 111 | c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905); 112 | b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055); 113 | a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571); 114 | d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606); 115 | c = md5_ii(c, d, a, b, x[i+10], 15, -1051523); 116 | b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799); 117 | a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359); 118 | d = md5_ii(d, a, b, c, x[i+15], 10, -30611744); 119 | c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380); 120 | b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649); 121 | a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070); 122 | d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379); 123 | c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259); 124 | b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551); 125 | 126 | a = safe_add(a, olda); 127 | b = safe_add(b, oldb); 128 | c = safe_add(c, oldc); 129 | d = safe_add(d, oldd); 130 | } 131 | return Array(a, b, c, d); 132 | 133 | } 134 | 135 | /* 136 | * These functions implement the four basic operations the algorithm uses. 137 | */ 138 | function md5_cmn(q, a, b, x, s, t) 139 | { 140 | return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b); 141 | } 142 | function md5_ff(a, b, c, d, x, s, t) 143 | { 144 | return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); 145 | } 146 | function md5_gg(a, b, c, d, x, s, t) 147 | { 148 | return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); 149 | } 150 | function md5_hh(a, b, c, d, x, s, t) 151 | { 152 | return md5_cmn(b ^ c ^ d, a, b, x, s, t); 153 | } 154 | function md5_ii(a, b, c, d, x, s, t) 155 | { 156 | return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); 157 | } 158 | 159 | /* 160 | * Calculate the HMAC-MD5, of a key and some data 161 | */ 162 | function core_hmac_md5(key, data) 163 | { 164 | var bkey = str2binl(key); 165 | if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz); 166 | 167 | var ipad = Array(16), opad = Array(16); 168 | for(var i = 0; i < 16; i++) 169 | { 170 | ipad[i] = bkey[i] ^ 0x36363636; 171 | opad[i] = bkey[i] ^ 0x5C5C5C5C; 172 | } 173 | 174 | var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz); 175 | return core_md5(opad.concat(hash), 512 + 128); 176 | } 177 | 178 | /* 179 | * Add integers, wrapping at 2^32. This uses 16-bit operations internally 180 | * to work around bugs in some JS interpreters. 181 | */ 182 | function safe_add(x, y) 183 | { 184 | var lsw = (x & 0xFFFF) + (y & 0xFFFF); 185 | var msw = (x >> 16) + (y >> 16) + (lsw >> 16); 186 | return (msw << 16) | (lsw & 0xFFFF); 187 | } 188 | 189 | /* 190 | * Bitwise rotate a 32-bit number to the left. 191 | */ 192 | function bit_rol(num, cnt) 193 | { 194 | return (num << cnt) | (num >>> (32 - cnt)); 195 | } 196 | 197 | /* 198 | * Convert a string to an array of little-endian words 199 | * If chrsz is ASCII, characters >255 have their hi-byte silently ignored. 200 | */ 201 | function str2binl(str) 202 | { 203 | var bin = Array(); 204 | var mask = (1 << chrsz) - 1; 205 | for(var i = 0; i < str.length * chrsz; i += chrsz) 206 | bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32); 207 | return bin; 208 | } 209 | 210 | /* 211 | * Convert an array of little-endian words to a string 212 | */ 213 | function binl2str(bin) 214 | { 215 | var str = ""; 216 | var mask = (1 << chrsz) - 1; 217 | for(var i = 0; i < bin.length * 32; i += chrsz) 218 | str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask); 219 | return str; 220 | } 221 | 222 | /* 223 | * Convert an array of little-endian words to a hex string. 224 | */ 225 | function binl2hex(binarray) 226 | { 227 | var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef"; 228 | var str = ""; 229 | for(var i = 0; i < binarray.length * 4; i++) 230 | { 231 | str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) + 232 | hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF); 233 | } 234 | return str; 235 | } 236 | 237 | /* 238 | * Convert an array of little-endian words to a base-64 string 239 | */ 240 | function binl2b64(binarray) 241 | { 242 | var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; 243 | var str = ""; 244 | for(var i = 0; i < binarray.length * 4; i += 3) 245 | { 246 | var triplet = (((binarray[i >> 2] >> 8 * ( i %4)) & 0xFF) << 16) 247 | | (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 ) 248 | | ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF); 249 | for(var j = 0; j < 4; j++) 250 | { 251 | if(i * 8 + j * 6 > binarray.length * 32) str += b64pad; 252 | else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F); 253 | } 254 | } 255 | return str; 256 | } 257 | -------------------------------------------------------------------------------- /_attachments/style/main.css: -------------------------------------------------------------------------------- 1 | /* add styles here */ 2 | 3 | pre { 4 | background:#eee; 5 | } 6 | 7 | body { 8 | font:1em Helvetica, sans-serif; 9 | padding:4px; 10 | background:url(../images/tile.png); 11 | } 12 | 13 | h1, h3 { 14 | margin:0; 15 | padding:0; 16 | } 17 | 18 | ul { 19 | list-style-type: none; 20 | margin:0; padding:0; 21 | } 22 | 23 | #account { 24 | float:right; 25 | } 26 | 27 | #garden h4 { 28 | padding:0; 29 | margin:0 0 8px 0; 30 | } 31 | 32 | li { 33 | margin:8px; 34 | padding:8px; 35 | border:4px dotted #bbc; 36 | } 37 | 38 | #shares .icon img { 39 | border:2px solid #bbc; 40 | } 41 | 42 | li.app { 43 | float:left; 44 | width:200px; 45 | height:200px; 46 | border:4px solid #55b; 47 | background:#eef; 48 | overflow:hidden; 49 | text-align:center; 50 | } 51 | 52 | #garden li.app h3 { 53 | padding:0; 54 | margin:0; 55 | font-size:1em; 56 | } 57 | 58 | #garden li.app h4 { 59 | font-size:0.8em; 60 | color:#555; 61 | text-align:left; 62 | } 63 | 64 | #shares { 65 | width:40%; 66 | float:left; 67 | } 68 | 69 | #installs { 70 | width:40%; 71 | float:left; 72 | } 73 | 74 | div.icon { 75 | max-height:150px; 76 | overflow:hidden; 77 | } 78 | 79 | .icon img { 80 | width:150px; 81 | } 82 | 83 | .info { 84 | float:right; 85 | font-size:0.75em; 86 | } 87 | 88 | div.screen { 89 | float:left; 90 | margin-right:8px; 91 | } 92 | 93 | .clear { 94 | clear:left; 95 | } -------------------------------------------------------------------------------- /couchapp.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "CouchApp Garden", 3 | "description": "Tells you all the local CouchApps, allows you to share them!" 4 | } -------------------------------------------------------------------------------- /evently/apps/_init/data.js: -------------------------------------------------------------------------------- 1 | function(row) { 2 | var info = row.value.shared.info; 3 | info.shared_by = row.value.shared.by; 4 | info.icon = info.icon || "images/couchapp.png"; 5 | info.shared_doc_id = row.id; 6 | return info; 7 | }; -------------------------------------------------------------------------------- /evently/apps/_init/mustache.html: -------------------------------------------------------------------------------- 1 |
  • 2 |
    3 | {{name}} on {{db}} 4 |
    5 |

    {{name}}

    6 |

    shared by: {{#shared_by}}{{shared_by}}{{/shared_by}}

    7 |
    8 |
  • 9 | 10 | -------------------------------------------------------------------------------- /evently/apps/_init/query.json: -------------------------------------------------------------------------------- 1 | { 2 | "view" : "apps", 3 | "type" : "newRows" 4 | } -------------------------------------------------------------------------------- /evently/apps/_init/render.txt: -------------------------------------------------------------------------------- 1 | append -------------------------------------------------------------------------------- /evently/garden/_init/after.js: -------------------------------------------------------------------------------- 1 | function() { 2 | var app = $$(this).app; 3 | }; -------------------------------------------------------------------------------- /evently/garden/_init/async.js: -------------------------------------------------------------------------------- 1 | function(cb) { 2 | var widget = $$(this); 3 | var app = widget.app; 4 | var garden = app.require("lib/garden"); 5 | garden.cachedApps(app, cb); 6 | }; 7 | -------------------------------------------------------------------------------- /evently/garden/_init/data.js: -------------------------------------------------------------------------------- 1 | function(apps) { 2 | $.log(arguments) 3 | // var apps = $$(this).apps; 4 | var stash = { 5 | couchapps : apps 6 | }; 7 | return stash; 8 | } -------------------------------------------------------------------------------- /evently/garden/_init/mustache.html: -------------------------------------------------------------------------------- 1 | 17 | -------------------------------------------------------------------------------- /evently/installs/load/after.js: -------------------------------------------------------------------------------- 1 | function(e, params) { 2 | var name = params.name; 3 | $(".app").text(name); 4 | document.title = name + " : Share and Update : CouchApp Garden"; 5 | // load all ddocs with the matching name in any database 6 | var widget = $(this); 7 | var app = $$(this).app; 8 | var garden = app.require("lib/garden"); 9 | garden.installedApps(app, name, function(installs) { 10 | $(widget).trigger("render", [name, installs]); 11 | }); 12 | }; -------------------------------------------------------------------------------- /evently/installs/load/path.txt: -------------------------------------------------------------------------------- 1 | /app/:name -------------------------------------------------------------------------------- /evently/installs/load/xasync.js: -------------------------------------------------------------------------------- 1 | function(cb, e, params) { 2 | var name = params.name; 3 | // load all ddocs with the matching name in any database 4 | var widget = $(this); 5 | var app = $$(this).app; 6 | var garden = app.require("lib/garden"); 7 | garden.installedApps(app, name, function(installs) { 8 | $(widget).trigger("render", [installs]); 9 | }); 10 | }; 11 | -------------------------------------------------------------------------------- /evently/installs/render/data.js: -------------------------------------------------------------------------------- 1 | function(e, name, installs) { 2 | return { 3 | installs : installs 4 | }; 5 | }; 6 | -------------------------------------------------------------------------------- /evently/installs/render/mustache.html: -------------------------------------------------------------------------------- 1 | {{#installs}} 2 |
  • 3 |
    4 | {{name}} on {{db}} 5 |
    6 | 7 |

    {{db}}

    8 |

    {{#shared_by}}Shared by: {{shared_by}}/{{/shared_by}}{{name}}

    9 | {{#share}} 10 | share 11 | {{/share}} 12 | {{#update}} 13 | update 14 | {{/update}} 15 |
    16 |
  • 17 | {{/installs}} 18 | 19 | -------------------------------------------------------------------------------- /evently/installs/render/selectors/a.share/click.js: -------------------------------------------------------------------------------- 1 | function(e) { 2 | e.preventDefault(); 3 | var share = this; 4 | var widget = $$(this); 5 | var app = widget.app; 6 | var garden = app.require("lib/garden"); 7 | var ddoc_path = $(share).attr("href"); 8 | $.log(ddoc_path) 9 | $(share).text("Sharing..."); 10 | garden.shareApp(app, $$("#account").userCtx.name, ddoc_path, { 11 | success : function() { 12 | $(share).text("Shared!"); 13 | window.location.reload() 14 | } 15 | }); 16 | return false; 17 | }; -------------------------------------------------------------------------------- /evently/shares/render/after.js: -------------------------------------------------------------------------------- 1 | function() { 2 | $("form", this).trigger("change"); 3 | }; -------------------------------------------------------------------------------- /evently/shares/render/data.js: -------------------------------------------------------------------------------- 1 | function(row, e, name, installs) { 2 | var info = row.value.shared.info; 3 | info.shared_by = row.value.shared.by; 4 | info.icon = info.icon || "images/couchapp.png"; 5 | info.installs = installs; 6 | info.shared_doc_id = row.id; 7 | info.from_db = info.db; 8 | return info; 9 | }; -------------------------------------------------------------------------------- /evently/shares/render/mustache.html: -------------------------------------------------------------------------------- 1 |
  • 2 |
    3 | {{name}} on {{db}} 4 |
    5 |

    shared by: {{#shared_by}}{{shared_by}}{{/shared_by}}

    6 |

    from db: {{#from_db}}{{from_db}}{{/from_db}}

    7 |
    8 | 9 | 15 |
    16 | 17 | 18 | 19 | 20 |
    21 | 22 | 23 |
    24 |
    25 |
  • 26 | 27 | -------------------------------------------------------------------------------- /evently/shares/render/query.js: -------------------------------------------------------------------------------- 1 | function(e, name, installs) { 2 | return { 3 | view : "apps", 4 | type : "newRows", 5 | key : name 6 | }; 7 | }; 8 | -------------------------------------------------------------------------------- /evently/shares/render/render.txt: -------------------------------------------------------------------------------- 1 | append -------------------------------------------------------------------------------- /evently/shares/render/selectors/form/change.js: -------------------------------------------------------------------------------- 1 | function(e) { 2 | var db = $("select",this).val(); 3 | $.log(db) 4 | if (db == "_other") { 5 | $(".other",this).show(); 6 | } else { 7 | $(".other",this).hide(); 8 | } 9 | }; -------------------------------------------------------------------------------- /evently/shares/render/selectors/form/submit.js: -------------------------------------------------------------------------------- 1 | function(e) { 2 | e.preventDefault(); 3 | var app = $$(this).app; 4 | var db = $("select",this).val(); 5 | var shared_doc_id = $("input[name=shared_doc_id]",this).val(); 6 | var garden = app.require("lib/garden"); 7 | var form = this; 8 | function installApp() { 9 | $(form).append('

    Installing into ' + db + '...

    '); 10 | garden.installApp(app, db, shared_doc_id, { 11 | success : function() { 12 | $(".progress:last",form).text("Installed into "+db); 13 | } 14 | }); 15 | } 16 | 17 | if (db == "_other") { 18 | db = $("[name=other]", form).val(); 19 | var create = $("[name=create]", form).is(':checked'); 20 | if (create) { 21 | $.couch.db(db).create({ 22 | success : installApp, 23 | error : installApp 24 | }); 25 | } else { 26 | installApp(); 27 | } 28 | } else { 29 | installApp(); 30 | } 31 | 32 | return false; 33 | }; -------------------------------------------------------------------------------- /lib/garden.js: -------------------------------------------------------------------------------- 1 | function couchAppName(ddoc) { 2 | var name; 3 | name = ddoc.couchapp && ddoc.couchapp.name; 4 | if (name && name != "Name of your CouchApp") { 5 | return name; 6 | } else { 7 | name = ddoc._id.split('/'); 8 | name.shift(); 9 | return name.join('/'); 10 | } 11 | } 12 | 13 | function couchAppSlug(ddoc) { 14 | var slug = ddoc._id.split('/'); 15 | slug.shift(); 16 | return slug.join('/'); 17 | } 18 | 19 | 20 | function couchAppIcon(db, ddoc) { 21 | if (ddoc._attachments && ddoc._attachments["images/icon.png"]) { 22 | return ['', db, ddoc._id, "images/icon.png"].join('/'); 23 | } 24 | } 25 | 26 | function couchAppPath(db, ddoc) { 27 | var index, path; 28 | index = ddoc.couchapp && ddoc.couchapp.index; 29 | if (index) { 30 | path = ['', db, ddoc._id, index].join('/'); 31 | } else if (ddoc._attachments && ddoc._attachments["index.html"]) { 32 | path = ['', db, ddoc._id, "index.html"].join('/'); 33 | } 34 | return path; 35 | } 36 | 37 | function installId(db, ddoc) { 38 | return [db, ddoc._id].join("/"); 39 | } 40 | 41 | function edited(ddoc) { 42 | return false; 43 | } 44 | 45 | function share(ddoc) { 46 | return (!ddoc.garden || edited(ddoc)); 47 | }; 48 | 49 | function couchAppSharedBy(ddoc) { 50 | if (ddoc.garden && ddoc.garden.shared) {return ddoc.garden.shared.shared_by;} 51 | }; 52 | 53 | // update must be called at render time, when shares are known 54 | // function update(ddoc) { 55 | // return !edited() && shared[username].rev != my rev 56 | // } 57 | 58 | // todo use this in map fun 59 | function appInfo(db, ddoc) { 60 | var info = { 61 | name : couchAppName(ddoc), 62 | shared_by : couchAppSharedBy(ddoc), 63 | slug : couchAppSlug(ddoc), 64 | path : couchAppPath(db, ddoc), 65 | icon : couchAppIcon(db, ddoc), 66 | db : db, 67 | install_id : installId(db, ddoc), 68 | share : share(ddoc) 69 | } 70 | if (info.path) { 71 | return info; 72 | } 73 | }; 74 | 75 | function appInfos(db, rows) { 76 | var app_infos = []; 77 | for (var i=0; i < rows.length; i++) { 78 | var row = rows[i]; 79 | var app_info = appInfo(db, row.doc); 80 | if (app_info) { 81 | app_infos.push(app_info); 82 | } 83 | } 84 | return app_infos; 85 | } 86 | 87 | function findApps(dbs, app_infos, cb) { 88 | var db = dbs.pop(); 89 | if (db) { 90 | $.couch.db(db).allDesignDocs({ 91 | include_docs : true, 92 | success : function(resp) { 93 | findApps(dbs, app_infos.concat(appInfos(db, resp.rows)), cb); 94 | }, 95 | error : function(resp) { 96 | findApps(dbs, app_infos, cb); 97 | } 98 | }); 99 | } else { // did the last db 100 | cb(app_infos); 101 | } 102 | } 103 | 104 | function localApps(cb) { 105 | $.couch.allDbs({ 106 | success : function(dbs) { 107 | findApps(dbs, [], function(apps) { 108 | cb(apps); 109 | }); 110 | } 111 | }); 112 | } 113 | 114 | exports.localApps = localApps; 115 | 116 | function cachedApps(app, fun) { 117 | var cache = app.require("vendor/couchapp/lib/cache"); 118 | cache.get(app.db, "local_apps_cache", function(value_cb) { 119 | localApps(function(apps) { 120 | value_cb(apps.map(function(a) { 121 | a.icon = a.icon || "images/couchapp.png"; 122 | return a; 123 | })); 124 | }); 125 | }, fun); 126 | }; 127 | exports.cachedApps = cachedApps; 128 | 129 | exports.installedApps = function(app, name, fun) { 130 | cachedApps(app, function(apps) { 131 | var installs = []; 132 | apps.forEach(function(a) { 133 | if (a.slug == name) { 134 | installs.push(a) 135 | } 136 | }); 137 | fun(installs) 138 | }); 139 | } 140 | 141 | function clearCache(app) { 142 | var cache = app.require("vendor/couchapp/lib/cache"); 143 | cache.clear(app.db, "local_apps_cache"); 144 | }; 145 | 146 | exports.installApp = function(app, db, shared_doc_id, opts) { 147 | // load the doc 148 | var target_db = $.couch.db(db); 149 | var userSuccess = opts.success; 150 | opts.success = function() { 151 | clearCache(app); 152 | userSuccess.apply(this, arguments); 153 | }; 154 | app.db.openDoc(shared_doc_id, { 155 | attachments : true, 156 | success : function(shared) { 157 | // get install id 158 | var install_id = shared.garden.shared.id; 159 | target_db.openDoc(install_id, { 160 | success : function(target) { 161 | shared._rev = target._rev; 162 | shared._id = target._id; 163 | target_db.saveDoc(shared, opts); 164 | }, 165 | error : function() { 166 | shared._id = install_id; 167 | delete shared._rev; 168 | target_db.saveDoc(shared, opts); 169 | } 170 | }); 171 | } 172 | }); 173 | 174 | }; 175 | 176 | exports.shareApp = function(app, userName, path, opts) { 177 | // load the ddoc from the path, save it to app.db, call success 178 | var parts = path.split('/'); 179 | var db = parts.shift(); 180 | var ddoc_id = parts.join('/'); 181 | $.couch.db(db).openDoc(ddoc_id, { 182 | attachments : true, 183 | success : function(doc) { 184 | doc.garden = doc.garden || {}; 185 | // use appInfo? 186 | doc.garden.shared = { 187 | id : doc._id, 188 | rev : doc._rev, 189 | info : appInfo(db, doc), 190 | at : new Date(), 191 | by : userName 192 | }; 193 | var garden_id = ["shared", userName, doc._id].join('/'); 194 | doc._id = garden_id; 195 | app.db.openDoc(garden_id, { 196 | success : function(shared) { 197 | doc._rev = shared._rev; 198 | app.db.saveDoc(doc, opts); 199 | }, 200 | error : function() { 201 | delete doc._rev; 202 | app.db.saveDoc(doc, opts); 203 | } 204 | }); 205 | } 206 | }); 207 | }; 208 | -------------------------------------------------------------------------------- /vendor/couchapp/README.md: -------------------------------------------------------------------------------- 1 | ## CouchApp - more than just a filesystem mapper 2 | 3 | This is where documentation will go for the client and server JavaScript parts of CouchApp. -------------------------------------------------------------------------------- /vendor/couchapp/_attachments/docs.css: -------------------------------------------------------------------------------- 1 | body { 2 | font:1em Helvetica, sans-serif; 3 | margin:0; 4 | padding:4px; 5 | } 6 | 7 | h1 { 8 | margin:0.5em; 9 | } 10 | 11 | h2 { 12 | color:#222; 13 | } 14 | 15 | pre { 16 | padding:4px; 17 | margin:4px; 18 | background:#bbb; 19 | } 20 | 21 | #content { 22 | padding:4px; 23 | margin:2px; 24 | } 25 | 26 | #sidebar { 27 | float:right; 28 | width:34%; 29 | } 30 | 31 | #docs { 32 | -moz-box-shadow:0 0 2em #000; 33 | -webkit-box-shadow:0 0 2em #000; 34 | width:58%; 35 | padding:8px; 36 | margin:4px; 37 | } 38 | 39 | .example { 40 | background:#ffd; 41 | padding:4px; 42 | margin:4px; 43 | position:absolute; 44 | } 45 | 46 | textarea.code { 47 | width:100%; 48 | } 49 | 50 | .edit { 51 | float:right; 52 | font-size:0.8em; 53 | } 54 | -------------------------------------------------------------------------------- /vendor/couchapp/_attachments/docs.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Evently and CouchApp Docs 5 | 6 | 7 | 8 | 12 |
    13 | 16 |
    17 |
    18 |
    19 |
    20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /vendor/couchapp/_attachments/docs.js: -------------------------------------------------------------------------------- 1 | $.log = function() { 2 | // console.log(arguments) 3 | }; 4 | 5 | $.couch.app(function(app) { 6 | $("#docs").evently(app.ddoc.vendor.couchapp.evently.docs, app); 7 | $.pathbinder.begin("/"); 8 | }); -------------------------------------------------------------------------------- /vendor/couchapp/_attachments/jquery.couch.app.js: -------------------------------------------------------------------------------- 1 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not 2 | // use this file except in compliance with the License. You may obtain a copy 3 | // of the License at 4 | // 5 | // http://www.apache.org/licenses/LICENSE-2.0 6 | // 7 | // Unless required by applicable law or agreed to in writing, software 8 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 9 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 10 | // License for the specific language governing permissions and limitations under 11 | // the License. 12 | 13 | // Usage: The passed in function is called when the page is ready. 14 | // CouchApp passes in the app object, which takes care of linking to 15 | // the proper database, and provides access to the CouchApp helpers. 16 | // $.couch.app(function(app) { 17 | // app.db.view(...) 18 | // ... 19 | // }); 20 | 21 | (function($) { 22 | 23 | function Design(db, name) { 24 | this.doc_id = "_design/"+name; 25 | this.view = function(view, opts) { 26 | db.view(name+'/'+view, opts); 27 | }; 28 | } 29 | 30 | $.couch.app = $.couch.app || function(appFun) { 31 | $(function() { 32 | var dbname = document.location.href.split('/')[3]; 33 | var dname = unescape(document.location.href).split('/')[5]; 34 | var db = $.couch.db(dbname); 35 | var design = new Design(db, dname); 36 | 37 | // docForm applies CouchDB behavior to HTML forms. 38 | // todo make this a couch.app plugin 39 | function docForm(formSelector, opts) { 40 | var localFormDoc = {}; 41 | opts = opts || {}; 42 | opts.fields = opts.fields || []; 43 | 44 | // turn the form into deep json 45 | // field names like 'author-email' get turned into json like 46 | // {"author":{"email":"quentin@example.com"}} 47 | function formToDeepJSON(form, fields, doc) { 48 | form = $(form); 49 | opts.fields.forEach(function(field) { 50 | var val = form.find("[name="+field+"]").val(); 51 | if (!val) {return;} 52 | var parts = field.split('-'); 53 | var frontObj = doc, frontName = parts.shift(); 54 | while (parts.length > 0) { 55 | frontObj[frontName] = frontObj[frontName] || {}; 56 | frontObj = frontObj[frontName]; 57 | frontName = parts.shift(); 58 | } 59 | frontObj[frontName] = val; 60 | }); 61 | } 62 | 63 | // Apply the behavior 64 | $(formSelector).submit(function(e) { 65 | e.preventDefault(); 66 | // formToDeepJSON acts on localFormDoc by reference 67 | formToDeepJSON(this, opts.fields, localFormDoc); 68 | if (opts.beforeSave) {opts.beforeSave(localFormDoc);} 69 | db.saveDoc(localFormDoc, { 70 | success : function(resp) { 71 | if (opts.success) {opts.success(resp, localFormDoc);} 72 | } 73 | }); 74 | 75 | return false; 76 | }); 77 | 78 | // populate form from an existing doc 79 | function docToForm(doc) { 80 | var form = $(formSelector); 81 | // fills in forms 82 | opts.fields.forEach(function(field) { 83 | var parts = field.split('-'); 84 | var run = true, frontObj = doc, frontName = parts.shift(); 85 | while (frontObj && parts.length > 0) { 86 | frontObj = frontObj[frontName]; 87 | frontName = parts.shift(); 88 | } 89 | if (frontObj && frontObj[frontName]) { 90 | form.find("[name="+field+"]").val(frontObj[frontName]); 91 | } 92 | }); 93 | } 94 | 95 | if (opts.id) { 96 | db.openDoc(opts.id, { 97 | success: function(doc) { 98 | if (opts.onLoad) {opts.onLoad(doc);} 99 | localFormDoc = doc; 100 | docToForm(doc); 101 | }}); 102 | } else if (opts.template) { 103 | if (opts.onLoad) {opts.onLoad(opts.template);} 104 | localFormDoc = opts.template; 105 | docToForm(localFormDoc); 106 | } 107 | var instance = { 108 | deleteDoc : function(opts) { 109 | opts = opts || {}; 110 | if (confirm("Really delete this document?")) { 111 | db.removeDoc(localFormDoc, opts); 112 | } 113 | }, 114 | localDoc : function() { 115 | formToDeepJSON(formSelector, opts.fields, localFormDoc); 116 | return localFormDoc; 117 | } 118 | }; 119 | return instance; 120 | } 121 | 122 | function resolveModule(names, parent, current) { 123 | if (names.length === 0) { 124 | if (typeof current != "string") { 125 | throw ["error","invalid_require_path", 126 | 'Must require a JavaScript string, not: '+(typeof current)]; 127 | } 128 | return [current, parent]; 129 | } 130 | // we need to traverse the path 131 | var n = names.shift(); 132 | if (n == '..') { 133 | if (!(parent && parent.parent)) { 134 | throw ["error", "invalid_require_path", 'Object has no parent '+JSON.stringify(current)]; 135 | } 136 | return resolveModule(names, parent.parent.parent, parent.parent); 137 | } else if (n == '.') { 138 | if (!parent) { 139 | throw ["error", "invalid_require_path", 'Object has no parent '+JSON.stringify(current)]; 140 | } 141 | return resolveModule(names, parent.parent, parent); 142 | } 143 | if (!current[n]) { 144 | throw ["error", "invalid_require_path", 'Object has no property "'+n+'". '+JSON.stringify(current)]; 145 | } 146 | var p = current; 147 | current = current[n]; 148 | current.parent = p; 149 | return resolveModule(names, p, current); 150 | } 151 | 152 | var p = document.location.pathname.split('/'); 153 | p.shift(); 154 | var qs = document.location.search.replace(/^\?/,'').split('&'); 155 | var q = {}; 156 | qs.forEach(function(param) { 157 | var ps = param.split('='); 158 | var k = decodeURIComponent(ps[0]); 159 | var v = decodeURIComponent(ps[1]); 160 | if (["startkey", "endkey", "key"].indexOf(k) != -1) { 161 | q[k] = JSON.parse(v); 162 | } else { 163 | q[k] = v; 164 | } 165 | }); 166 | var mockReq = { 167 | path : p, 168 | query : q 169 | }; 170 | 171 | var appExports = $.extend({ 172 | db : db, 173 | design : design, 174 | view : design.view, 175 | docForm : docForm, 176 | req : mockReq 177 | }, $.couch.app.app); 178 | 179 | function handleDDoc(ddoc) { 180 | if (ddoc) { 181 | var require = function(name, parent) { 182 | var exports = {}; 183 | var resolved = resolveModule(name.split('/'), parent, ddoc); 184 | var source = resolved[0]; 185 | parent = resolved[1]; 186 | var s = "var func = function (exports, require) { " + source + " };"; 187 | try { 188 | eval(s); 189 | func.apply(ddoc, [exports, function(name) {return require(name, parent, source)}]); 190 | } catch(e) { 191 | throw ["error","compilation_error","Module require('"+name+"') raised error "+e.toSource()]; 192 | } 193 | return exports; 194 | } 195 | appExports.ddoc = ddoc; 196 | appExports.require = require; 197 | } 198 | // todo make app-exports the this in the execution context? 199 | appFun.apply(appExports, [appExports]); 200 | } 201 | 202 | if ($.couch.app.ddocs[design.doc_id]) { 203 | handleDDoc($.couch.app.ddocs[design.doc_id]) 204 | } else { 205 | // only open 1 connection for this ddoc 206 | if ($.couch.app.ddoc_handlers[design.doc_id]) { 207 | // we are already fetching, just wait 208 | $.couch.app.ddoc_handlers[design.doc_id].push(handleDDoc); 209 | } else { 210 | $.couch.app.ddoc_handlers[design.doc_id] = [handleDDoc]; 211 | db.openDoc(design.doc_id, { 212 | success : function(doc) { 213 | $.couch.app.ddocs[design.doc_id] = doc; 214 | $.couch.app.ddoc_handlers[design.doc_id].forEach(function(h) { 215 | h(doc); 216 | }); 217 | $.couch.app.ddoc_handlers[design.doc_id] = null; 218 | }, 219 | error : function() { 220 | $.couch.app.ddoc_handlers[design.doc_id].forEach(function(h) { 221 | h(); 222 | }); 223 | $.couch.app.ddoc_handlers[design.doc_id] = null; 224 | } 225 | }); 226 | } 227 | } 228 | 229 | }); 230 | }; 231 | $.couch.app.ddocs = {}; 232 | $.couch.app.ddoc_handlers = {}; 233 | // legacy support. $.CouchApp is deprecated, please use $.couch.app 234 | $.CouchApp = $.couch.app; 235 | })(jQuery); 236 | -------------------------------------------------------------------------------- /vendor/couchapp/_attachments/jquery.couch.app.util.js: -------------------------------------------------------------------------------- 1 | $.log = function(m) { 2 | if (window && window.console && window.console.log) { 3 | window.console.log(arguments.length == 1 ? m : arguments); 4 | } 5 | }; 6 | 7 | // todo remove this crap 8 | function escapeHTML(st) { 9 | return( 10 | st && st.replace(/&/g,'&'). 11 | replace(/>/g,'>'). 12 | replace(/'+a+''; 25 | }).replace(/\@([\w\-]+)/g,function(user,name) { 26 | return ''+user+''; 27 | }).replace(/\#([\w\-\.]+)/g,function(word,tag) { 28 | return ''+word+''; 29 | }); 30 | }; 31 | 32 | $.fn.prettyDate = function() { 33 | $(this).each(function() { 34 | $(this).text($.prettyDate($(this).text())); 35 | }); 36 | }; 37 | 38 | $.prettyDate = function(time){ 39 | 40 | var date = new Date(time.replace(/-/g,"/").replace("T", " ").replace("Z", " +0000").replace(/(\d*\:\d*:\d*)\.\d*/g,"$1")), 41 | diff = (((new Date()).getTime() - date.getTime()) / 1000), 42 | day_diff = Math.floor(diff / 86400); 43 | 44 | if (isNaN(day_diff)) return time; 45 | 46 | return day_diff < 1 && ( 47 | diff < 60 && "just now" || 48 | diff < 120 && "1 minute ago" || 49 | diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" || 50 | diff < 7200 && "1 hour ago" || 51 | diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") || 52 | day_diff == 1 && "yesterday" || 53 | day_diff < 21 && day_diff + " days ago" || 54 | day_diff < 45 && Math.ceil( day_diff / 7 ) + " weeks ago" || 55 | day_diff < 730 && Math.ceil( day_diff / 31 ) + " months ago" || 56 | Math.ceil( day_diff / 365 ) + " years ago"; 57 | }; 58 | 59 | $.argsToArray = function(args) { 60 | if (!args.callee) return args; 61 | var array = []; 62 | for (var i=0; i < args.length; i++) { 63 | array.push(args[i]); 64 | }; 65 | return array; 66 | } 67 | -------------------------------------------------------------------------------- /vendor/couchapp/_attachments/jquery.evently.js: -------------------------------------------------------------------------------- 1 | // $$ inspired by @wycats: http://yehudakatz.com/2009/04/20/evented-programming-with-jquery/ 2 | function $$(node) { 3 | var data = $(node).data("$$"); 4 | if (data) { 5 | return data; 6 | } else { 7 | data = {}; 8 | $(node).data("$$", data); 9 | return data; 10 | } 11 | }; 12 | 13 | (function($) { 14 | // utility functions used in the implementation 15 | 16 | function forIn(obj, fun) { 17 | var name; 18 | for (name in obj) { 19 | if (obj.hasOwnProperty(name)) { 20 | fun(name, obj[name]); 21 | } 22 | } 23 | }; 24 | $.forIn = forIn; 25 | function funViaString(fun) { 26 | if (fun && fun.match && fun.match(/function/)) { 27 | eval("var f = "+fun); 28 | if (typeof f == "function") { 29 | return function() { 30 | try { 31 | return f.apply(this, arguments); 32 | } catch(e) { 33 | // IF YOU SEE AN ERROR HERE IT HAPPENED WHEN WE TRIED TO RUN YOUR FUNCTION 34 | // $.log({"message": "Error in evently function.", "error": e, "src" : fun}); 35 | throw(e); 36 | } 37 | }; 38 | } 39 | } 40 | return fun; 41 | }; 42 | 43 | function runIfFun(me, fun, args) { 44 | // if the field is a function, call it, bound to the widget 45 | var f = funViaString(fun); 46 | if (typeof f == "function") { 47 | return f.apply(me, args); 48 | } else { 49 | return fun; 50 | } 51 | } 52 | 53 | $.evently = { 54 | connect : function(source, target, events) { 55 | events.forEach(function(ev) { 56 | source.bind(ev, function() { 57 | var args = $.makeArray(arguments); 58 | // remove the original event to keep from stacking args extra deep 59 | // it would be nice if jquery had a way to pass the original 60 | // event to the trigger method. 61 | args.shift(); 62 | target.trigger(ev, args); 63 | return false; 64 | }); 65 | }); 66 | }, 67 | paths : [], 68 | changesDBs : {} 69 | }; 70 | 71 | $.fn.evently = function(events, app, args) { 72 | var elem = $(this); 73 | // store the app on the element for later use 74 | if (app) { 75 | $$(elem).app = app; 76 | } 77 | $$(elem).evently = events; 78 | // setup the handlers onto elem 79 | forIn(events, function(name, h) { 80 | eventlyHandler(elem, name, h, args); 81 | }); 82 | 83 | if (events._init) { 84 | $.log("ev _init", elem); 85 | elem.trigger("_init", args); 86 | } 87 | 88 | if (app && events._changes) { 89 | $("body").bind("evently.changes."+app.db.name, function() { 90 | // we want to unbind this function when the element is deleted. 91 | // maybe jquery 1.4.2 has this covered? 92 | $.log('changes', elem); 93 | elem.trigger("_changes"); 94 | }); 95 | followChanges(app); 96 | elem.trigger("_changes"); 97 | } 98 | }; 99 | 100 | // eventlyHandler applies the user's handler (h) to the 101 | // elem, bound to trigger based on name. 102 | function eventlyHandler(elem, name, h, args) { 103 | if (h.path) { 104 | elem.pathbinder(name, h.path); 105 | } 106 | var f = funViaString(h); 107 | if (typeof f == "function") { 108 | elem.bind(name, {args:args}, f); 109 | } else if (typeof f == "string") { 110 | elem.bind(name, {args:args}, function() { 111 | $(this).trigger(f, arguments); 112 | return false; 113 | }); 114 | } else if ($.isArray(h)) { 115 | // handle arrays recursively 116 | for (var i=0; i < h.length; i++) { 117 | eventlyHandler(elem, name, h[i], args); 118 | } 119 | } else { 120 | // an object is using the evently / mustache template system 121 | if (h.fun) { 122 | elem.bind(name, {args:args}, funViaString(h.fun)); 123 | } 124 | // templates, selectors, etc are intepreted 125 | // when our named event is triggered. 126 | elem.bind(name, {args:args}, function() { 127 | renderElement($(this), h, arguments); 128 | return false; 129 | }); 130 | } 131 | }; 132 | 133 | $.fn.replace = function(elem) { 134 | $.log("Replace", this) 135 | $(this).empty().append(elem); 136 | }; 137 | 138 | // todo: ability to call this 139 | // to render and "prepend/append/etc" a new element to the host element (me) 140 | // as well as call this in a way that replaces the host elements content 141 | // this would be easy if there is a simple way to get at the element we just appended 142 | // (as html) so that we can attache the selectors 143 | function renderElement(me, h, args, qrun, arun) { 144 | // if there's a query object we run the query, 145 | // and then call the data function with the response. 146 | if (h.async && !arun) { 147 | runAsync(me, h, args) 148 | } else if (h.query && !qrun) { 149 | // $.log("query before renderElement", arguments) 150 | runQuery(me, h, args) 151 | } else { 152 | // $.log("renderElement") 153 | // $.log(me, h, args, qrun) 154 | // otherwise we just render the template with the current args 155 | var selectors = runIfFun(me, h.selectors, args); 156 | var act = h.render || "replace"; 157 | var app = $$(me).app; 158 | if (h.mustache) { 159 | $.log("rendering", h.mustache) 160 | var newElem = mustachioed(me, h, args); 161 | me[act](newElem); 162 | } 163 | if (selectors) { 164 | if (act == "replace") { 165 | var s = me; 166 | } else { 167 | var s = newElem; 168 | } 169 | forIn(selectors, function(selector, handlers) { 170 | // $.log("selector", selector); 171 | // $.log("selected", $(selector, s)); 172 | $(selector, s).evently(handlers, app, args); 173 | // $.log("applied", selector); 174 | }); 175 | } 176 | if (h.after) { 177 | funViaString(h.after).apply(me, args); 178 | } 179 | } 180 | }; 181 | 182 | // todo this should return the new element 183 | function mustachioed(me, h, args) { 184 | return $($.mustache( 185 | runIfFun(me, h.mustache, args), 186 | runIfFun(me, h.data, args), 187 | runIfFun(me, h.partials, args))); 188 | }; 189 | 190 | function runAsync(me, h, args) { 191 | // the callback is the first argument 192 | funViaString(h.async).apply(me, [function() { 193 | renderElement(me, h, 194 | $.argsToArray(arguments).concat($.argsToArray(args)), false, true); 195 | }].concat($.argsToArray(args))); 196 | }; 197 | 198 | 199 | function runQuery(me, h, args) { 200 | // $.log("runQuery: args", args) 201 | var app = $$(me).app; 202 | var qu = runIfFun(me, h.query, args); 203 | var qType = qu.type; 204 | var viewName = qu.view; 205 | var userSuccess = qu.success; 206 | // $.log("qType", qType) 207 | 208 | var q = {}; 209 | forIn(qu, function(k, v) { 210 | q[k] = v; 211 | }); 212 | 213 | if (qType == "newRows") { 214 | q.success = function(resp) { 215 | $.log("runQuery newRows success", resp.rows.length, me, resp) 216 | resp.rows.reverse().forEach(function(row) { 217 | renderElement(me, h, [row].concat($.argsToArray(args)), true) 218 | }); 219 | if (userSuccess) userSuccess(resp); 220 | }; 221 | newRows(me, app, viewName, q); 222 | } else { 223 | q.success = function(resp) { 224 | // $.log("runQuery success", resp) 225 | renderElement(me, h, [resp].concat($.argsToArray(args)), true); 226 | userSuccess && userSuccess(resp); 227 | }; 228 | $.log(app) 229 | app.view(viewName, q); 230 | } 231 | } 232 | 233 | // this is for the items handler 234 | // var lastViewId, highKey, inFlight; 235 | // this needs to key per elem 236 | function newRows(elem, app, view, opts) { 237 | // $.log("newRows", arguments); 238 | // on success we'll set the top key 239 | var thisViewId, successCallback = opts.success, full = false; 240 | function successFun(resp) { 241 | // $.log("newRows success", resp) 242 | $$(elem).inFlight = false; 243 | var JSONhighKey = JSON.stringify($$(elem).highKey); 244 | resp.rows = resp.rows.filter(function(r) { 245 | return JSON.stringify(r.key) != JSONhighKey; 246 | }); 247 | if (resp.rows.length > 0) { 248 | if (opts.descending) { 249 | $$(elem).highKey = resp.rows[0].key; 250 | } else { 251 | $$(elem).highKey = resp.rows[resp.rows.length -1].key; 252 | } 253 | }; 254 | if (successCallback) {successCallback(resp, full)}; 255 | }; 256 | opts.success = successFun; 257 | 258 | if (opts.descending) { 259 | thisViewId = view + (opts.startkey ? JSON.stringify(opts.startkey) : ""); 260 | } else { 261 | thisViewId = view + (opts.endkey ? JSON.stringify(opts.endkey) : ""); 262 | } 263 | // $.log(["thisViewId",thisViewId]) 264 | // for query we'll set keys 265 | if (thisViewId == $$(elem).lastViewId) { 266 | // we only want the rows newer than changesKey 267 | var hk = $$(elem).highKey; 268 | if (hk !== undefined) { 269 | if (opts.descending) { 270 | opts.endkey = hk; 271 | // opts.inclusive_end = false; 272 | } else { 273 | opts.startkey = hk; 274 | } 275 | } 276 | // $.log("add view rows", opts) 277 | if (!$$(elem).inFlight) { 278 | $$(elem).inFlight = true; 279 | app.view(view, opts); 280 | } 281 | } else { 282 | // full refresh 283 | // $.log("new view stuff") 284 | full = true; 285 | $$(elem).lastViewId = thisViewId; 286 | $$(elem).highKey = undefined; 287 | $$(elem).inFlight = true; 288 | app.view(view, opts); 289 | } 290 | }; 291 | 292 | // only start one changes listener per db 293 | function followChanges(app) { 294 | var dbName = app.db.name; 295 | if (!$.evently.changesDBs[dbName]) { 296 | connectToChanges(app, function() { 297 | $("body").trigger("evently.changes."+dbName); 298 | }); 299 | $.evently.changesDBs[dbName] = true; 300 | } 301 | } 302 | 303 | function connectToChanges(app, fun) { 304 | function resetHXR(x) { 305 | x.abort(); 306 | connectToChanges(app, fun); 307 | }; 308 | app.db.info({success: function(db_info) { 309 | var c_xhr = jQuery.ajaxSettings.xhr(); 310 | c_xhr.open("GET", app.db.uri+"_changes?feed=continuous&since="+db_info.update_seq, true); 311 | c_xhr.send(""); 312 | // todo use a timeout to prevent rapid triggers 313 | var t; 314 | c_xhr.onreadystatechange = function() { 315 | clearTimeout(t); 316 | t = setTimeout(fun, 100); 317 | }; 318 | setTimeout(function() { 319 | resetHXR(c_xhr); 320 | }, 1000 * 60); 321 | }}); 322 | }; 323 | 324 | })(jQuery); 325 | -------------------------------------------------------------------------------- /vendor/couchapp/_attachments/jquery.mustache.js: -------------------------------------------------------------------------------- 1 | /* 2 | Shameless port of a shameless port 3 | @defunkt => @janl => @aq 4 | 5 | See http://github.com/defunkt/mustache for more info. 6 | */ 7 | 8 | ;(function($) { 9 | 10 | /* 11 | Shamless port of http://github.com/defunkt/mustache 12 | by Jan Lehnardt , Alexander Lang , 13 | Sebastian Cohnen 14 | 15 | Thanks @defunkt for the awesome code. 16 | 17 | See http://github.com/defunkt/mustache for more info. 18 | */ 19 | 20 | var Mustache = function() { 21 | var Renderer = function() {}; 22 | 23 | Renderer.prototype = { 24 | otag: "{{", 25 | ctag: "}}", 26 | pragmas: {}, 27 | 28 | render: function(template, context, partials) { 29 | // fail fast 30 | if(template.indexOf(this.otag) == -1) { 31 | return template; 32 | } 33 | 34 | template = this.render_pragmas(template); 35 | var html = this.render_section(template, context, partials); 36 | return this.render_tags(html, context, partials); 37 | }, 38 | 39 | /* 40 | Looks for %PRAGMAS 41 | */ 42 | render_pragmas: function(template) { 43 | // no pragmas 44 | if(template.indexOf(this.otag + "%") == -1) { 45 | return template; 46 | } 47 | 48 | var that = this; 49 | var regex = new RegExp(this.otag + "%(.+)" + this.ctag); 50 | return template.replace(regex, function(match, pragma) { 51 | that.pragmas[pragma] = true; 52 | return ""; 53 | // ignore unknown pragmas silently 54 | }); 55 | }, 56 | 57 | /* 58 | Tries to find a partial in the global scope and render it 59 | */ 60 | render_partial: function(name, context, partials) { 61 | if(typeof(context[name]) != "object") { 62 | throw({message: "subcontext for '" + name + "' is not an object"}); 63 | } 64 | if(!partials || !partials[name]) { 65 | throw({message: "unknown_partial"}); 66 | } 67 | return this.render(partials[name], context[name], partials); 68 | }, 69 | 70 | /* 71 | Renders boolean and enumerable sections 72 | */ 73 | render_section: function(template, context, partials) { 74 | if(template.indexOf(this.otag + "#") == -1) { 75 | return template; 76 | } 77 | var that = this; 78 | // CSW - Added "+?" so it finds the tighest bound, not the widest 79 | var regex = new RegExp(this.otag + "\\#(.+)" + this.ctag + 80 | "\\s*([\\s\\S]+?)" + this.otag + "\\/\\1" + this.ctag + "\\s*", "mg"); 81 | 82 | // for each {{#foo}}{{/foo}} section do... 83 | return template.replace(regex, function(match, name, content) { 84 | var value = that.find(name, context); 85 | if(that.is_array(value)) { // Enumerable, Let's loop! 86 | return that.map(value, function(row) { 87 | return that.render(content, that.merge(context, 88 | that.create_context(row)), partials); 89 | }).join(''); 90 | } else if(value) { // boolean section 91 | return that.render(content, context, partials); 92 | } else { 93 | return ""; 94 | } 95 | }); 96 | }, 97 | 98 | /* 99 | Replace {{foo}} and friends with values from our view 100 | */ 101 | render_tags: function(template, context, partials) { 102 | var lines = template.split("\n"); 103 | 104 | var new_regex = function() { 105 | return new RegExp(that.otag + "(=|!|>|\\{|%)?([^\/#]+?)\\1?" + 106 | that.ctag + "+", "g"); 107 | }; 108 | 109 | // tit for tat 110 | var that = this; 111 | 112 | var regex = new_regex(); 113 | for (var i=0; i < lines.length; i++) { 114 | lines[i] = lines[i].replace(regex, function (match,operator,name) { 115 | switch(operator) { 116 | case "!": // ignore comments 117 | return match; 118 | case "=": // set new delimiters, rebuild the replace regexp 119 | that.set_delimiters(name); 120 | regex = new_regex(); 121 | // redo the line in order to get tags with the new delimiters 122 | // on the same line 123 | i--; 124 | return ""; 125 | case ">": // render partial 126 | return that.render_partial(name, context, partials); 127 | case "{": // the triple mustache is unescaped 128 | return that.find(name, context); 129 | return ""; 130 | default: // escape the value 131 | return that.escape(that.find(name, context)); 132 | } 133 | },this); 134 | }; 135 | return lines.join("\n"); 136 | }, 137 | 138 | set_delimiters: function(delimiters) { 139 | var dels = delimiters.split(" "); 140 | this.otag = this.escape_regex(dels[0]); 141 | this.ctag = this.escape_regex(dels[1]); 142 | }, 143 | 144 | escape_regex: function(text) { 145 | // thank you Simon Willison 146 | if(!arguments.callee.sRE) { 147 | var specials = [ 148 | '/', '.', '*', '+', '?', '|', 149 | '(', ')', '[', ']', '{', '}', '\\' 150 | ]; 151 | arguments.callee.sRE = new RegExp( 152 | '(\\' + specials.join('|\\') + ')', 'g' 153 | ); 154 | } 155 | return text.replace(arguments.callee.sRE, '\\$1'); 156 | }, 157 | 158 | /* 159 | find `name` in current `context`. That is find me a value 160 | from the view object 161 | */ 162 | find: function(name, context) { 163 | name = this.trim(name); 164 | if(typeof context[name] === "function") { 165 | return context[name].apply(context); 166 | } 167 | if(context[name] !== undefined) { 168 | return context[name]; 169 | } 170 | // silently ignore unkown variables 171 | return ""; 172 | }, 173 | 174 | // Utility methods 175 | 176 | /* 177 | Does away with nasty characters 178 | */ 179 | escape: function(s) { 180 | return s.toString().replace(/[&"<>\\]/g, function(s) { 181 | switch(s) { 182 | case "&": return "&"; 183 | case "\\": return "\\\\";; 184 | case '"': return '\"';; 185 | case "<": return "<"; 186 | case ">": return ">"; 187 | default: return s; 188 | } 189 | }); 190 | }, 191 | 192 | /* 193 | Merges all properties of object `b` into object `a`. 194 | `b.property` overwrites a.property` 195 | */ 196 | merge: function(a, b) { 197 | var _new = {}; 198 | for(var name in a) { 199 | if(a.hasOwnProperty(name)) { 200 | _new[name] = a[name]; 201 | } 202 | }; 203 | for(var name in b) { 204 | if(b.hasOwnProperty(name)) { 205 | _new[name] = b[name]; 206 | } 207 | }; 208 | return _new; 209 | }, 210 | 211 | // by @langalex, support for arrays of strings 212 | create_context: function(_context) { 213 | if(this.is_object(_context)) { 214 | return _context; 215 | } else if(this.pragmas["JSTACHE-ENABLE-STRING-ARRAYS"]) { 216 | return {'.': _context}; 217 | } 218 | }, 219 | 220 | is_object: function(a) { 221 | return a && typeof a == 'object' 222 | }, 223 | 224 | /* 225 | Thanks Doug Crockford 226 | JavaScript — The Good Parts lists an alternative that works better with 227 | frames. Frames can suck it, we use the simple version. 228 | */ 229 | is_array: function(a) { 230 | return (a && 231 | typeof a === 'object' && 232 | a.constructor === Array); 233 | }, 234 | 235 | /* 236 | Gets rid of leading and trailing whitespace 237 | */ 238 | trim: function(s) { 239 | return s.replace(/^\s*|\s*$/g, ''); 240 | }, 241 | 242 | /* 243 | Why, why, why? Because IE. Cry, cry cry. 244 | */ 245 | map: function(array, fn) { 246 | if (typeof array.map == "function") { 247 | return array.map(fn) 248 | } else { 249 | var r = []; 250 | var l = array.length; 251 | for(i=0;i{{json}}", 23 | data : function() { 24 | var widget = app.ddoc.vendor.couchapp.evently.account; 25 | return { 26 | json : JSON.stringify(widget, null, 2) 27 | } 28 | } 29 | } 30 | }); 31 | }); 32 | 33 | The top level keys are the most important: `loggedIn`, `loggedOut`, `adminParty`, `signupForm`, `loginForm`, `doLogin`, `doSignup`, and `_init`. Each one of these corresponds to an event or state the system can be in. Some of them draw user interface elements, other directly trigger further events. 34 | 35 | ### _init 36 | 37 | The `_init` event is special, in that Evently will automatically trigger it when the widget is created. Here is the code for the account widget's `_init` event handler. 38 | 39 | function() { 40 | var elem = $(this); 41 | $.couch.session({ 42 | success : function(r) { 43 | var userCtx = r.userCtx; 44 | if (userCtx.name) { 45 | elem.trigger("loggedIn", [r]); 46 | } else if (userCtx.roles.indexOf("_admin") != -1) { 47 | elem.trigger("adminParty"); 48 | } else { 49 | elem.trigger("loggedOut"); 50 | }; 51 | } 52 | }); 53 | } 54 | 55 | This code does one query to CouchDB, to retrieve the session information for the current user. For this we use the `$.couch.session()` function which is part of the [jquery.couch.js](/_utils/script/jquery.couch.js) library which is part of the CouchDB distribution. 56 | 57 | The response is handled in one of three ways, depending on the user's session information. Either we trigger the `loggedIn` or `loggedOut` events, or in the special case where we detect that CouchDB's security is not properly configured, we trigger the `adminParty` event to warn the user. 58 | 59 | ### loggedOut 60 | 61 | Because most visitors start logged out, let's now turn our attention to the `loggedOut` event handler to see what will greet a new visitor: 62 | 63 | "loggedOut": { 64 | "mustache": "Signup or Login", 65 | "selectors": { 66 | "a[href=#login]": { 67 | "click": "loginForm" 68 | }, 69 | "a[href=#signup]": { 70 | "click": "signupForm" 71 | } 72 | } 73 | } 74 | 75 | There are two main components to this handler: `mustache` and `selectors`. `mustache` is a template file with two HTML links. `selectors` contains a set of CSS selectors with events bound to them. You can think of each selector as a nested Evently widget. In this case, clicking "Login" will trigger the `loginForm` event, while clicking "Signup" triggers the `signupForm` event. 76 | 77 | ### signupForm 78 | 79 | Let's see what happens during signup. We'll skip showing the whole handler (it should be in the sidebar anyway if you clicked "run" earlier.) 80 | 81 | When the `signupForm` event is triggered, a mustache template draws the form. Then the selectors are run, assigning this function to the form's submit event: 82 | 83 | function(e) { 84 | var name = $('input[name=name]', this).val(), 85 | pass = $('input[name=password]', this).val(); 86 | $(this).trigger('doSignup', [name, pass]); 87 | return false; 88 | } 89 | 90 | This handler is as simple as possible, all it does is use jQuery to pull the user data from the form, and send the name and password to the `doSignup` event. We could just use a function call here, but it's nice to keep our individual events as small as possible, as this makes customizing Evently widgets simpler. 91 | 92 | ### doSignup 93 | 94 | Here is the `doSignup` handler: 95 | 96 | function(e, name, pass) { 97 | var elem = $(this); 98 | $.couch.signup({ 99 | name : name 100 | }, pass, { 101 | success : function() { 102 | elem.trigger("doLogin", [name, pass]); 103 | } 104 | }); 105 | } 106 | 107 | Again, all the complex signup logic (encrypting passwords, etc) is pushed to the [jquery.couch.js](/_utils/script/jquery.couch.js) library (via the `$.couch.signup()` call), so our application code can stay as simple as possible. When signup is complete, we trigger the `doLogin` event, so new users don't have to go through another action. 108 | 109 | ### doLogin 110 | 111 | The code for `doLogin` isn't much different, just take the name and password, and call a jquery.couch.js library function with it. 112 | 113 | function(e, name, pass) { 114 | var elem = $(this); 115 | $.couch.login({ 116 | name : name, 117 | password : pass, 118 | success : function(r) { 119 | elem.trigger("_init") 120 | } 121 | }); 122 | } 123 | 124 | The last thing that `doLogin` does is trigger `_init`, so we come full circle! This time, `_init` will see that the user is logged in, and trigger the `loggedIn` event. You'll probably want to hook your application to this `loggedIn` event, to activate any features which are reserved for registered users. We'll cover linking events in a later section. 125 | 126 | ## Customizing the account widget 127 | 128 | Evently widgets are built out of JSON objects, which makes it easy to replace bits and pieces of them without having to mess with the entire widget. We'll start by customizing what users see when they are logged in. 129 | 130 | $.couch.app(function(app){ 131 | var customizedWidget = $.extend(true, {}, app.ddoc.vendor.couchapp.evently.account, { 132 | loggedIn : { 133 | mustache : 'Hello {{name}} you are logged in! ' + 134 | 'Would you like to logout?' 135 | } 136 | }); 137 | $("#customWelcome").evently(customizedWidget); 138 | }); 139 | 140 | Take a moment to run this example code and login to see how our custom template has replaced just one screen in the widget. The first time I did this I thought it was pretty cool. Hopefully you can think of a lot of powerful stuff you could do with it. The sky is the limit. 141 | 142 | Here's another quick one: 143 | 144 | $.couch.app(function(app){ 145 | var customizedWidget = $.extend(true, {}, app.ddoc.vendor.couchapp.evently.account, { 146 | loggedOut : { 147 | after : "function(){alert('Bye bye');}" 148 | } 149 | }); 150 | $("#afterAlert").evently(customizedWidget); 151 | }); 152 | 153 | For a deeper reference on what the various parts of an Evently widget are named, and how you can use them, see [the Evently docs page](#/topic/evently). 154 | 155 | ## Linking two widgets 156 | 157 | First, lets create a basic widget. This one just has an `_init` handler and a handler called `loggedIn`. There is nothing in this widget definition that will trigger `loggedIn`, unless something else triggers it, there's no way it will run. 158 | 159 | $("#link_target").evently({ 160 | _init : { 161 | mustache : "

    Not much to see here

    " 162 | }, 163 | loggedIn : { 164 | mustache : "

    loggedIn was triggered from another widget, {{name}}.

    ", 165 | data : function(e, r) { 166 | return { name : r.userCtx.name }; 167 | } 168 | } 169 | }); 170 | 171 | Be sure to run the above example code before the next one, otherwise there won't be anything to link to. 172 | 173 | This next block of code demonstrates how to link two widgets together. First we create a normal account widget on the `#link_source` element, then we tell Evently to connect it to the `#link_target` element. Now whenever the `loggedIn` evenr is triggered on the source, it will be triggered on the target. 174 | 175 | $.couch.app(function(app){ 176 | $("#link_source").evently(app.ddoc.vendor.couchapp.evently.account); 177 | // link the source to the target, for the loggedIn event 178 | $.evently.connect($("#link_source"), $("#link_target"), ["loggedIn"]); 179 | }); 180 | 181 | ## Conclusion 182 | 183 | If you are writing a CouchApp that will have users logging and and logging out, you'd do well to use the account widget. It's customizable and linkable. And what's more, it's code that's already written. 184 | 185 | Enjoy! 186 | 187 | -------------------------------------------------------------------------------- /vendor/couchapp/docs/couchapp.md: -------------------------------------------------------------------------------- 1 | # Docs for $.couch.app 2 | 3 | The simplest use of CouchApp in the browser is to get access to information about the database you are running in. 4 | 5 | $.couch.app(function(app) { 6 | $("#dbinfo").evently({ 7 | _init : { 8 | mustache : '

    The db name is {{name}}

    ', 9 | data : app.db 10 | } 11 | }); 12 | }); 13 | 14 | Yay couchapp. 15 | 16 | The `$.couch.app()` function also loads the current design document so that it is available for templates etc. That is how the words you are reading were loaded. This file is included in the CouchApp application library. Let's look at the design doc: 17 | 18 | $.couch.app(function(app) { 19 | $("#ddoc").evently({ 20 | _init : { 21 | mustache : '

    Click to show the full doc source:

    {{ddoc}}
    ', 22 | data : { 23 | ddoc : JSON.stringify(app.ddoc, null, 2).slice(0,100) + '...' 24 | } 25 | }, 26 | click : { 27 | mustache : '

    The full doc source (rerun to hide):

    {{ddoc}}
    ', 28 | data : { 29 | ddoc : JSON.stringify(app.ddoc, null, 2) 30 | } 31 | } 32 | }); 33 | }); 34 | 35 | -------------------------------------------------------------------------------- /vendor/couchapp/docs/docs.md: -------------------------------------------------------------------------------- 1 | # Docs for the docs system. 2 | 3 | You are encouraged to use the couchapp docs system to write documentation for your plugins and applications. Extra bonus points because it's fun. 4 | 5 | Docs automatically make divs based on `$("#foo")` pattern matching. That is, we regex the code looking for the first id we see referenced. Remember ids need to be unique on a page. For doc examples you only get one id. 6 | 7 | Example Code: 8 | 9 | $("#hide_foo").hide("slow"); 10 | 11 | That's all it takes. You only get one div in each example for now. Have fun! -------------------------------------------------------------------------------- /vendor/couchapp/docs/evently.md: -------------------------------------------------------------------------------- 1 | # Evently Docs 2 | 3 | Evently is an declarative framework for evented jQuery applications. You write your code as widgets made up of templates and callbacks, while Evently handles the busywork of linking them together. 4 | 5 | Evently has special handlers for CouchDB views and `_changes` feeds, and could be easily extended for other server-side frameworks. 6 | 7 | ## Hello World 8 | 9 | At it's simplest an Evently widget is a set of events connected to a single DOM element. 10 | 11 | JavaScript: 12 | 13 | $("#hello").evently({ 14 | _init : { 15 | mustache : "

    Hello world

    ", 16 | }, 17 | click : { 18 | mustache : "

    What a crazy world!

    ", 19 | } 20 | }); 21 | 22 | You can also do some more interesting things: 23 | 24 | $("#heyjane").evently({ 25 | _init : { 26 | mustache : '

    Hello Jane, Joan (pick one)

    ', 27 | selectors : { 28 | 'a[href=#joan]' : { 29 | click : 'hiJoan' 30 | }, 31 | 'a[href=#jane]' : { 32 | click : 'hiJane' 33 | } 34 | } 35 | }, 36 | hiJoan : { 37 | mustache : '

    Hello Joan!

    ' 38 | }, 39 | hiJane : { 40 | mustache : "

    Darn, it's Jane...

    ", 41 | after : function() { 42 | setTimeout(function() { 43 | // automatically trigger the "janeRocks" event after 2 seconds. 44 | $("#heyjane").trigger("janeRocks"); 45 | }, 2000); 46 | } 47 | }, 48 | janeRocks : { 49 | render : "append", 50 | mustache : "

    Actually Jane is awesome.

    " 51 | } 52 | }); 53 | 54 | 55 | The imporant thing about this is that the widget is defined by an JavaScript object. This means we can save it as files on our hard drive and `couchapp` will handle saving it as a JSON object for us. 56 | 57 | [screenshot of the above code in textmate's file drawer] 58 | 59 | When we let CouchApp package our evently apps we get to work on them in individual files, instead of as a great big giant mess of JavaScript. This means HTML is HTML, JSON is JSON, and JavaScript is JavaScript. Yay! 60 | 61 | ## Ajax Hello World 62 | 63 | Let's do a little Ajax. We'll just load the version of the CouchDB instance we happen to be serving our HTML from: 64 | 65 | $("#ajax").evently({ 66 | _init : { 67 | mustache : '

    Loading CouchDB server info.

    ', 68 | after : function() { 69 | var widget = $(this); 70 | $.ajax({ 71 | url : '/', 72 | complete : function(req) { 73 | var resp = $.httpData(req, "json"); 74 | widget.trigger("version", [resp]); 75 | } 76 | }) 77 | } 78 | }, 79 | version : { 80 | mustache : "

    Running CouchDB version {{version}}

    ", 81 | data : function(e, resp) { 82 | return resp; 83 | } 84 | } 85 | }); 86 | 87 | Explain `mustache` and `data` 88 | 89 | -- triggering other events 90 | -- selectors 91 | -- create a doc 92 | 93 | ## Evently and CouchApp together 94 | 95 | Evently makes it easy to write decoupled JavaScript code, but as the examples above show, Evently widgets can turn into a lot of JSON to look at all on one screen. Because Evently code is declarative, and each handler and callback stands on its own (instead of being wrapped in a common closure), it can be broken out into individual files. 96 | 97 | CouchApp provides a mechanism for mapping between individual files and JSON structures. In this model a directory structure is mapped to a JSON object. So if you have a directory structure like: 98 | 99 | _init/ 100 | mustache.html 101 | selectors/ 102 | form/ 103 | submit.js 104 | input.name/ 105 | change.js 106 | a.cancel/ 107 | click.txt 108 | cancelled/ 109 | mustache.html 110 | selectors/ 111 | a.continue/ 112 | click.txt 113 | 114 | It will appear within your CouchApp design document as: 115 | 116 | { 117 | _init : { 118 | mustache : "contents of mustache.html", 119 | selectors { 120 | form : { 121 | submit : "function() { ... }" 122 | }, 123 | "input.name" { 124 | change : "function() { ... }" 125 | }, 126 | "a.cancel" { 127 | click : "cancelled" 128 | } 129 | } 130 | }, 131 | cancelled : { 132 | mustache : "contents of mustache.html", 133 | selectors : { 134 | "a.continue" : { 135 | click : "_init" 136 | } 137 | } 138 | } 139 | } 140 | 141 | This makes Evently and CouchApp a natural fit for each other. I swear I didn't plan this when I started writing Evently, it just turned out to be an awesome side effect of trying to stay as close to JSON as possible. 142 | 143 | In the [account widget tutorial](#/topic/account) we see the details of the account widget. What isn't discussed much there, is how the code is edited on your filesystem. 144 | 145 | If you are writing an Evently CouchApp widget you can edit the individual pieces on your filesystem. This has the added advantage of giving you native syntax highlighting for all the code. Instead of editing everything as JSON or JavaScript, the templates can be treated as HTML, the paths as text, etc. 146 | 147 | ## Evently Queries 148 | 149 | Evently understands CouchDB in a couple of very simple ways. If you know CouchDB, you're probably familiar with its Map Reduce views. Evently lets you specify view queries in a declarative way, and even takes care of the Ajax request. All you have to do is write code to handle the returned data. 150 | 151 | -- new rows, etc 152 | 153 | -- run a query 154 | 155 | -- connect to changes 156 | 157 | -- links to example apps 158 | 159 | ## Freeform Asynchronous Actions 160 | 161 | Watch out, you're dangerous! Evently allows you to make any old asyncronous action you want, with the `widget.async` member. The callback is the first argument to the `async` function. Check it out: 162 | 163 | $("#async").evently({ 164 | _init : { 165 | mustache : "

    How many databases on the local host?

    Answer: {{number_of_dbs}}

    Other stuff: {{args}}

    More: {{allArgs}}

    ", 166 | async : function(cb) { 167 | var ag = Array.prototype.slice.call(arguments).map(function(a){return a.toSource ? a.toSource() : a}); 168 | $.couch.allDbs({ 169 | success : function(resp) { 170 | cb(resp.length, ag); 171 | } 172 | }) 173 | }, 174 | data : function(count, args) { 175 | return { 176 | number_of_dbs : count, 177 | args : JSON.stringify(args), 178 | allArgs : JSON.stringify(Array.prototype.slice.call(arguments)) 179 | }; 180 | } 181 | }, 182 | click : { 183 | mustache : "

    What a crazy world!

    ", 184 | } 185 | }); -------------------------------------------------------------------------------- /vendor/couchapp/docs/pathbinder.md: -------------------------------------------------------------------------------- 1 | # Docs about $.pathbinder 2 | 3 | Pathbinder is a tiny framework for triggering events based on paths in URL hash. For example, you might want to render one panel when the user clicks a link to `#/foo` and another when the URL hash changes to `#/bar`. If you've never used URL hashes for application state in an Ajax app before, prepare to be happy. 4 | 5 | There are two big advantages to having the state in the URL-hash. One is that users can bookmark screens they may have reached by navigating within your app. The other is that the back button will continue to work. 6 | 7 | The page you are on has a URL hash of `#/topic/pathbinder` right now. You can follow links to other "pages" within this application, and Pathbinder takes care of triggering the proper events. 8 | 9 | ## A simple example 10 | 11 | $("#basic_path").html('

    click for foo

    '); 12 | $("#basic_path").bind("foo", function() { 13 | $(this).html("

    you went to foo

    "); 14 | }); 15 | $("#basic_path").pathbinder("foo", "/foo"); 16 | 17 | This code sets up the `#basic_path` div with some initial content, including a link to `#/foo`. If you click the link to foo, you'll see the URL change. It is the changed URL which Pathbinder sees and uses to trigger any running code. You can experiment by manually entering the `#/foo` URL hash, instead of clicking the link, and you'll see that it also triggers the `foo` event. 18 | 19 | ## Using path parameters 20 | 21 | Pathbinder was inspired by the path handling in [Sammy.js](http://github.com/aq/sammy.js). Like Sammy, you can use it to pull parameters from the URL-hash. This page can be linked [using a path that has "pathbinder" as a parameter](#/topic/pathbinder). Let's explore how you can pull parameters out of a path. 22 | 23 | $("#param_path").html('

    click for super foo

    '); 24 | $("#param_path").bind("foo", function(e, params) { 25 | $(this).html("

    you went to foo - "+params.id+"

    "); 26 | }); 27 | $("#param_path").pathbinder("foo", "/foo/:id"); 28 | 29 | When you click the link to super foo, you'll see the param is passed through the event. You can also edit the URL to see that "super" is not hard coded and can be replaced with other values. 30 | 31 | ## Pathbinder with Evently 32 | 33 | It should be no suprise that Pathbinder and Evently play well together. The gist of it is that Evently looks for a key called `path` and if it finds it, uses Pathbinder to connect that event handler to the path. Let's try it out: 34 | 35 | $("#evently_path").evently({ 36 | _init : { 37 | path : '/index', 38 | mustache : '

    the index. more cowbell!

    ' 39 | }, 40 | cowbell : { 41 | path : '/cowbell', 42 | mustache : '

    Now that is a lot of cowbell. back to the index

    ' 43 | } 44 | }); 45 | 46 | Note that when you use an Evently path, Evently also takes care to visit the path when the corresponding event is triggered. So running the above example code (which automatically triggers the `_init` event) will set the hash to `#/index`. If you were to trigger the `cowbell` event through non-path means, you'd see that it changes the path to `#/cowbell` anyway. 47 | 48 | ### Too many widgets 49 | 50 | One thing worth noting: there is only one URL hash for any given page, so be aware that if you have multiple widgets competing for the real-estate, they could conflict with each other. Pathbinder won't do anything when presented with a path it doesn't care about (go ahead, try out some non-sense ones on this page). 51 | 52 | This means that if you have a few widgets all using the path, the page should still behave in a useful way. However, this breaks down if you intend people to be able to use the URL hash to link to page state. Since there can be only one URL hash, whichever action they took last will be reflected in the bookmarked URL. For this reason it makes sense to limit yourself to one path-based Evently widget per page. 53 | -------------------------------------------------------------------------------- /vendor/couchapp/docs/profile.md: -------------------------------------------------------------------------------- 1 | # docs for the profile evently widget 2 | 3 | This widget makes it easy to give users a profile for your application. -------------------------------------------------------------------------------- /vendor/couchapp/evently/account/_init.js: -------------------------------------------------------------------------------- 1 | function() { 2 | var elem = $(this); 3 | $.couch.session({ 4 | success : function(r) { 5 | var userCtx = r.userCtx; 6 | if (userCtx.name) { 7 | elem.trigger("loggedIn", [r]); 8 | } else if (userCtx.roles.indexOf("_admin") != -1) { 9 | elem.trigger("adminParty"); 10 | } else { 11 | elem.trigger("loggedOut"); 12 | }; 13 | } 14 | }); 15 | } -------------------------------------------------------------------------------- /vendor/couchapp/evently/account/adminParty.js: -------------------------------------------------------------------------------- 1 | function() { 2 | alert("Admin party! Fix this in Futon before proceeding."); 3 | } -------------------------------------------------------------------------------- /vendor/couchapp/evently/account/doLogin.js: -------------------------------------------------------------------------------- 1 | function(e, name, pass) { 2 | var elem = $(this); 3 | $.couch.login({ 4 | name : name, 5 | password : pass, 6 | success : function(r) { 7 | elem.trigger("_init") 8 | } 9 | }); 10 | } -------------------------------------------------------------------------------- /vendor/couchapp/evently/account/doLogout.js: -------------------------------------------------------------------------------- 1 | function() { 2 | var elem = $(this); 3 | $.couch.logout({ 4 | success : function() { 5 | elem.trigger("_init"); 6 | } 7 | }); 8 | } -------------------------------------------------------------------------------- /vendor/couchapp/evently/account/doSignup.js: -------------------------------------------------------------------------------- 1 | function(e, name, pass) { 2 | var elem = $(this); 3 | $.couch.signup({ 4 | name : name 5 | }, pass, { 6 | success : function() { 7 | elem.trigger("doLogin", [name, pass]); 8 | } 9 | }); 10 | } -------------------------------------------------------------------------------- /vendor/couchapp/evently/account/loggedIn/after.js: -------------------------------------------------------------------------------- 1 | // todo move to template 2 | function(e, r) { 3 | $(this).attr("data-name", r.userCtx.name); 4 | $$(this).userCtx = r.userCtx; 5 | } 6 | -------------------------------------------------------------------------------- /vendor/couchapp/evently/account/loggedIn/data.js: -------------------------------------------------------------------------------- 1 | function(e, r) { 2 | return { 3 | name : r.userCtx.name, 4 | uri_name : encodeURIComponent(r.userCtx.name), 5 | auth_db : encodeURIComponent(r.info.authentication_db) 6 | }; 7 | } -------------------------------------------------------------------------------- /vendor/couchapp/evently/account/loggedIn/mustache.html: -------------------------------------------------------------------------------- 1 | Welcome 2 | {{name}}! 3 | Logout? 4 | -------------------------------------------------------------------------------- /vendor/couchapp/evently/account/loggedIn/selectors.json: -------------------------------------------------------------------------------- 1 | { 2 | "a[href=#logout]" : {"click" : ["doLogout"]} 3 | } -------------------------------------------------------------------------------- /vendor/couchapp/evently/account/loggedOut/mustache.html: -------------------------------------------------------------------------------- 1 | Signup or Login -------------------------------------------------------------------------------- /vendor/couchapp/evently/account/loggedOut/selectors.json: -------------------------------------------------------------------------------- 1 | { 2 | "a[href=#signup]" : {"click" : ["signupForm"]}, 3 | "a[href=#login]" : {"click" : ["loginForm"]} 4 | } -------------------------------------------------------------------------------- /vendor/couchapp/evently/account/loginForm/after.js: -------------------------------------------------------------------------------- 1 | function() { 2 | $("input[name=name]", this).focus(); 3 | } -------------------------------------------------------------------------------- /vendor/couchapp/evently/account/loginForm/mustache.html: -------------------------------------------------------------------------------- 1 |
    2 | 3 | 4 | 5 | or Signup 6 |
    7 | -------------------------------------------------------------------------------- /vendor/couchapp/evently/account/loginForm/selectors/a[href=#signup].json: -------------------------------------------------------------------------------- 1 | {"click" : ["signupForm"]} -------------------------------------------------------------------------------- /vendor/couchapp/evently/account/loginForm/selectors/form/submit.js: -------------------------------------------------------------------------------- 1 | function(e) { 2 | var name = $('input[name=name]', this).val(), 3 | pass = $('input[name=password]', this).val(); 4 | $(this).trigger('doLogin', [name, pass]); 5 | return false; 6 | } -------------------------------------------------------------------------------- /vendor/couchapp/evently/account/signupForm/after.js: -------------------------------------------------------------------------------- 1 | function() { 2 | $("input[name=name]", this).focus(); 3 | } -------------------------------------------------------------------------------- /vendor/couchapp/evently/account/signupForm/mustache.html: -------------------------------------------------------------------------------- 1 |
    2 | 3 | 4 | 5 | or Login 6 |
    7 | -------------------------------------------------------------------------------- /vendor/couchapp/evently/account/signupForm/selectors/a[href=#login].json: -------------------------------------------------------------------------------- 1 | {"click" : ["loginForm"]} -------------------------------------------------------------------------------- /vendor/couchapp/evently/account/signupForm/selectors/form/submit.js: -------------------------------------------------------------------------------- 1 | function(e) { 2 | var name = $('input[name=name]', this).val(), 3 | pass = $('input[name=password]', this).val(); 4 | $(this).trigger('doSignup', [name, pass]); 5 | return false; 6 | } -------------------------------------------------------------------------------- /vendor/couchapp/evently/docs/index/data.js: -------------------------------------------------------------------------------- 1 | function() { 2 | var docs = $$(this).app.ddoc.vendor.couchapp.docs; 3 | var dnames = []; 4 | $.forIn(docs, function(d) { 5 | dnames.push({ 6 | title: d, 7 | href : "#/topic/"+encodeURIComponent(d) 8 | }); 9 | }); 10 | return {docs:dnames}; 11 | }; -------------------------------------------------------------------------------- /vendor/couchapp/evently/docs/index/mustache.html: -------------------------------------------------------------------------------- 1 |
      2 | {{#docs}} 3 |
    • {{title}}
    • 4 | {{/docs}} 5 |
    -------------------------------------------------------------------------------- /vendor/couchapp/evently/docs/index/path.txt: -------------------------------------------------------------------------------- 1 | / -------------------------------------------------------------------------------- /vendor/couchapp/evently/docs/topic/after.js: -------------------------------------------------------------------------------- 1 | function() { 2 | var app = $$(this).app; 3 | var self = $(this); 4 | $("pre", self).each(function() { 5 | var pre = $(this); 6 | var js = pre.text(); 7 | var r = js.match(/\$\(\"\#([^\"]*)\"\)/); 8 | if (r) { 9 | var id = r[1]; 10 | var code_id = 'code-'+id; 11 | pre.wrap('
    '); 12 | $('#'+code_id).evently(app.ddoc.vendor.couchapp.evently.docs.topic.edit, app, [id]); 13 | } 14 | }); 15 | }; 16 | -------------------------------------------------------------------------------- /vendor/couchapp/evently/docs/topic/data.js: -------------------------------------------------------------------------------- 1 | function(e, p) { 2 | var doc = $$(this).app.ddoc.vendor.couchapp.docs[p.id]; 3 | var converter = new Showdown.converter(); 4 | var html = converter.makeHtml(doc); 5 | return { 6 | html : html 7 | }; 8 | }; -------------------------------------------------------------------------------- /vendor/couchapp/evently/docs/topic/edit/_init/fun.js: -------------------------------------------------------------------------------- 1 | function(e, id) { 2 | var editable = $(this); 3 | if ($$(editable)._init_ran) {return false;} 4 | // add edit link 5 | var edit = $('edit code'); 6 | editable.append(edit); 7 | 8 | // add run box 9 | var example = $('
    run #'+id+'
    #'+id+' output will be here
    '); 10 | var s = $("#sidebar"); 11 | var o = s.offset(); 12 | example.offset({ 13 | left: o.left 14 | }); 15 | example.width(s.width()*0.75); 16 | editable.prepend(example); 17 | $$(editable)._init_ran = true; 18 | return false; 19 | } -------------------------------------------------------------------------------- /vendor/couchapp/evently/docs/topic/edit/_init/selectors/a.edit/click.js: -------------------------------------------------------------------------------- 1 | function() { 2 | var pre = $(this).prev('pre'); 3 | var js = pre.text(); 4 | var lines = js.split('\n').length; 5 | var ta = $(''); 6 | ta.text(js); 7 | pre.replace(ta); 8 | return false; 9 | }; 10 | -------------------------------------------------------------------------------- /vendor/couchapp/evently/docs/topic/edit/_init/selectors/a.run/click.js: -------------------------------------------------------------------------------- 1 | function(e) { 2 | try { 3 | function err(y, id) { 4 | $('#'+id).html(['

    Error running #', id, 5 | ' code block:

    ',
     6 |       (y.toSource ? y.toSource() : JSON.stringify(y)),
     7 |       '

    '].join('')); 8 | } 9 | var id = e.data.args[1]; 10 | var example = $("#code-"+id); 11 | var js = $('textarea',example).val() || $('pre',example).text(); 12 | $('#'+id).unbind(); 13 | try { 14 | eval(js); 15 | } catch (y) { 16 | err(y, id); 17 | } 18 | } catch(x) { 19 | err(x, id); 20 | } 21 | return false; 22 | } -------------------------------------------------------------------------------- /vendor/couchapp/evently/docs/topic/mustache.html: -------------------------------------------------------------------------------- 1 |
    {{{html}}}
    -------------------------------------------------------------------------------- /vendor/couchapp/evently/docs/topic/path.txt: -------------------------------------------------------------------------------- 1 | /topic/:id -------------------------------------------------------------------------------- /vendor/couchapp/evently/profile/loggedIn.js: -------------------------------------------------------------------------------- 1 | function(e, r) { 2 | var userCtx = r.userCtx; 3 | var widget = $(this); 4 | // load the profile from the user doc 5 | $.couch.userDb(function(db) { 6 | var userDocId = "org.couchdb.user:"+userCtx.name; 7 | db.openDoc(userDocId, { 8 | success : function(userDoc) { 9 | var profile = userDoc["couch.app.profile"]; 10 | if (profile) { 11 | // we copy the name to the profile so it can be used later 12 | // without publishing the entire userdoc (roles, pass, etc) 13 | profile.name = userDoc.name; 14 | $$(widget).profile = profile; 15 | widget.trigger("profileReady", [profile]); 16 | } else { 17 | widget.trigger("noProfile", [userCtx]); 18 | } 19 | } 20 | }); 21 | }); 22 | } 23 | -------------------------------------------------------------------------------- /vendor/couchapp/evently/profile/loggedOut/after.js: -------------------------------------------------------------------------------- 1 | function() { 2 | $$(this).profile = null; 3 | }; -------------------------------------------------------------------------------- /vendor/couchapp/evently/profile/loggedOut/mustache.html: -------------------------------------------------------------------------------- 1 |

    Please log in to see your profile.

    -------------------------------------------------------------------------------- /vendor/couchapp/evently/profile/noProfile/data.js: -------------------------------------------------------------------------------- 1 | function(e, userCtx) { 2 | return userCtx; 3 | } -------------------------------------------------------------------------------- /vendor/couchapp/evently/profile/noProfile/mustache.html: -------------------------------------------------------------------------------- 1 |
    2 |

    Hello {{name}}, Please setup your user profile.

    3 | 5 | 7 | 9 | 10 | 11 |
    -------------------------------------------------------------------------------- /vendor/couchapp/evently/profile/noProfile/selectors/form/submit.js: -------------------------------------------------------------------------------- 1 | function() { 2 | // TODO this can be cleaned up with docForm? 3 | 4 | var name = $("input[name=userCtxName]",this).val(); 5 | var newProfile = { 6 | rand : Math.random().toString(), 7 | nickname : $("input[name=nickname]",this).val(), 8 | email : $("input[name=email]",this).val(), 9 | url : $("input[name=url]",this).val() 10 | }, widget = $(this); 11 | 12 | // setup gravatar_url 13 | if (typeof hex_md5 == "undefined") { 14 | alert("creating a profile requires md5.js to be loaded in the page"); 15 | return; 16 | } 17 | 18 | newProfile.gravatar_url = 'http://www.gravatar.com/avatar/'+hex_md5(newProfile.email || newProfile.rand)+'.jpg?s=40&d=identicon'; 19 | 20 | // store the user profile on the user account document 21 | $.couch.userDb(function(db) { 22 | var userDocId = "org.couchdb.user:"+name; 23 | db.openDoc(userDocId, { 24 | success : function(userDoc) { 25 | userDoc["couch.app.profile"] = newProfile; 26 | db.saveDoc(userDoc, { 27 | success : function() { 28 | newProfile.name = userDoc.name; 29 | $$(widget).profile = newProfile; 30 | widget.trigger("profileReady", [newProfile]); 31 | } 32 | }); 33 | } 34 | }); 35 | }); 36 | return false; 37 | } -------------------------------------------------------------------------------- /vendor/couchapp/evently/profile/profileReady/after.js: -------------------------------------------------------------------------------- 1 | function(e, p) { 2 | $$(this).profile = p; 3 | }; -------------------------------------------------------------------------------- /vendor/couchapp/evently/profile/profileReady/data.js: -------------------------------------------------------------------------------- 1 | function(e, p) { 2 | return { 3 | nickname : p.nickname, 4 | name : p.name, 5 | avatar_url : p.gravatar_url 6 | }; 7 | } 8 | -------------------------------------------------------------------------------- /vendor/couchapp/evently/profile/profileReady/mustache.html: -------------------------------------------------------------------------------- 1 |
    2 | {{#avatar_url}}{{/avatar_url}} 3 |
    4 | {{nickname}} 5 |
    6 |
    7 |

    Hello {{nickname}}!

    8 |
    -------------------------------------------------------------------------------- /vendor/couchapp/lib/atom.js: -------------------------------------------------------------------------------- 1 | // atom feed generator 2 | // requries E4X support. 3 | 4 | function f(n) { // Format integers to have at least two digits. 5 | return n < 10 ? '0' + n : n; 6 | } 7 | 8 | function rfc3339(date) { 9 | return date.getUTCFullYear() + '-' + 10 | f(date.getUTCMonth() + 1) + '-' + 11 | f(date.getUTCDate()) + 'T' + 12 | f(date.getUTCHours()) + ':' + 13 | f(date.getUTCMinutes()) + ':' + 14 | f(date.getUTCSeconds()) + 'Z'; 15 | }; 16 | 17 | exports.header = function(data) { 18 | var f = ; 19 | f.title = data.title; 20 | f.id = data.feed_id; 21 | f.link.@href = data.feed_link; 22 | f.link.@rel = "self"; 23 | f.generator = "CouchApp on CouchDB"; 24 | f.updated = rfc3339(data.updated); 25 | return f.toXMLString().replace(/\<\/feed\>/,''); 26 | }; 27 | 28 | exports.entry = function(data) { 29 | var entry = ; 30 | entry.id = data.entry_id; 31 | entry.title = data.title; 32 | entry.content = data.content; 33 | entry.content.@type = (data.content_type || 'html'); 34 | entry.updated = rfc3339(data.updated); 35 | entry.author = {data.author}; 36 | entry.link.@href = data.alternate; 37 | entry.link.@rel = "alternate"; 38 | return entry; 39 | } 40 | -------------------------------------------------------------------------------- /vendor/couchapp/lib/cache.js: -------------------------------------------------------------------------------- 1 | exports.get = function(db, docid, setFun, getFun) { 2 | db.openDoc(docid, { 3 | success : function(doc) { 4 | getFun(doc.cache); 5 | }, 6 | error : function() { 7 | setFun(function(cache) { 8 | db.saveDoc({ 9 | _id : docid, 10 | cache : cache 11 | }); 12 | getFun(cache); 13 | }); 14 | } 15 | }); 16 | }; 17 | 18 | exports.clear = function(db, docid) { 19 | db.openDoc(docid, { 20 | success : function(doc) { 21 | db.removeDoc(doc); 22 | }, 23 | error : function() {} 24 | }); 25 | }; 26 | -------------------------------------------------------------------------------- /vendor/couchapp/lib/docform.js: -------------------------------------------------------------------------------- 1 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not 2 | // use this file except in compliance with the License. You may obtain a copy 3 | // of the License at 4 | // 5 | // http://www.apache.org/licenses/LICENSE-2.0 6 | // 7 | // Unless required by applicable law or agreed to in writing, software 8 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 9 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 10 | // License for the specific language governing permissions and limitations under 11 | // the License. 12 | 13 | // turn the form into deep json 14 | // field names like 'author-email' get turned into json like 15 | // {"author":{"email":"quentin@example.com"}} 16 | // acts on doc by reference, so you can safely pass non-form fields through 17 | function formToDeepJSON(form, fields, doc) { 18 | form = $(form); 19 | fields.forEach(function(field) { 20 | var val = form.find("[name="+field+"]").val(); 21 | if (!val) {return;} 22 | var parts = field.split('-'); 23 | var frontObj = doc, frontName = parts.shift(); 24 | while (parts.length > 0) { 25 | frontObj[frontName] = frontObj[frontName] || {}; 26 | frontObj = frontObj[frontName]; 27 | frontName = parts.shift(); 28 | } 29 | frontObj[frontName] = val; 30 | }); 31 | } 32 | 33 | function onSubmit(form, db, doc, opts) { 34 | formToDeepJSON(form, opts.fields, doc); 35 | if (opts.beforeSave) {opts.beforeSave(doc);} 36 | db.saveDoc(localFormDoc, { 37 | success : function(resp) { 38 | if (opts.success) {opts.success(resp, doc);} 39 | } 40 | }); 41 | }; 42 | 43 | function applyFields(form, doc) { 44 | 45 | }; 46 | exports.applyFields = applyFields; 47 | 48 | // docForm applies CouchDB behavior to HTML forms. 49 | // todo make this a couch.app plugin 50 | function docForm(formSelector, opts) { 51 | var localFormDoc = {}; 52 | opts = opts || {}; 53 | opts.fields = opts.fields || []; 54 | 55 | // Apply the behavior 56 | $(formSelector).submit(function(e) { 57 | 58 | 59 | return false; 60 | }); 61 | 62 | // populate form from an existing doc 63 | function docToForm(doc) { 64 | var form = $(formSelector); 65 | // fills in forms 66 | opts.fields.forEach(function(field) { 67 | var parts = field.split('-'); 68 | var run = true, frontObj = doc, frontName = parts.shift(); 69 | while (frontObj && parts.length > 0) { 70 | frontObj = frontObj[frontName]; 71 | frontName = parts.shift(); 72 | } 73 | if (frontObj && frontObj[frontName]) { 74 | form.find("[name="+field+"]").val(frontObj[frontName]); 75 | } 76 | }); 77 | } 78 | 79 | if (opts.id) { 80 | db.openDoc(opts.id, { 81 | success: function(doc) { 82 | if (opts.onLoad) {opts.onLoad(doc);} 83 | localFormDoc = doc; 84 | docToForm(doc); 85 | }}); 86 | } else if (opts.template) { 87 | if (opts.onLoad) {opts.onLoad(opts.template);} 88 | localFormDoc = opts.template; 89 | docToForm(localFormDoc); 90 | } 91 | var instance = { 92 | deleteDoc : function(opts) { 93 | opts = opts || {}; 94 | if (confirm("Really delete this document?")) { 95 | db.removeDoc(localFormDoc, opts); 96 | } 97 | }, 98 | localDoc : function() { 99 | formToDeepJSON(formSelector, opts.fields, localFormDoc); 100 | return localFormDoc; 101 | } 102 | }; 103 | return instance; 104 | } 105 | 106 | 107 | 108 | 109 | -------------------------------------------------------------------------------- /vendor/couchapp/lib/list.js: -------------------------------------------------------------------------------- 1 | // Helpers for writing server-side _list functions in CouchDB 2 | exports.withRows = function(fun) { 3 | var f = function() { 4 | var row = getRow(); 5 | return row && fun(row); 6 | }; 7 | f.iterator = true; 8 | return f; 9 | } 10 | 11 | exports.send = function(chunk) { 12 | send(chunk + "\n") 13 | } -------------------------------------------------------------------------------- /vendor/couchapp/lib/markdown.js: -------------------------------------------------------------------------------- 1 | // 2 | // showdown.js -- A javascript port of Markdown. 3 | // 4 | // Copyright (c) 2007 John Fraser. 5 | // 6 | // Original Markdown Copyright (c) 2004-2005 John Gruber 7 | // 8 | // 9 | // Redistributable under a BSD-style open source license. 10 | // See license.txt for more information. 11 | // 12 | // The full source distribution is at: 13 | // 14 | // A A L 15 | // T C A 16 | // T K B 17 | // 18 | // 19 | // 20 | 21 | // 22 | // Wherever possible, Showdown is a straight, line-by-line port 23 | // of the Perl version of Markdown. 24 | // 25 | // This is not a normal parser design; it's basically just a 26 | // series of string substitutions. It's hard to read and 27 | // maintain this way, but keeping Showdown close to the original 28 | // design makes it easier to port new features. 29 | // 30 | // More importantly, Showdown behaves like markdown.pl in most 31 | // edge cases. So web applications can do client-side preview 32 | // in Javascript, and then build identical HTML on the server. 33 | // 34 | // This port needs the new RegExp functionality of ECMA 262, 35 | // 3rd Edition (i.e. Javascript 1.5). Most modern web browsers 36 | // should do fine. Even with the new regular expression features, 37 | // We do a lot of work to emulate Perl's regex functionality. 38 | // The tricky changes in this file mostly have the "attacklab:" 39 | // label. Major or self-explanatory changes don't. 40 | // 41 | // Smart diff tools like Araxis Merge will be able to match up 42 | // this file with markdown.pl in a useful way. A little tweaking 43 | // helps: in a copy of markdown.pl, replace "#" with "//" and 44 | // replace "$text" with "text". Be sure to ignore whitespace 45 | // and line endings. 46 | // 47 | 48 | 49 | // 50 | // Showdown usage: 51 | // 52 | // var text = "Markdown *rocks*."; 53 | // 54 | // var markdown = require("markdown"); 55 | // var html = markdown.encode(text); 56 | // 57 | // print(html); 58 | // 59 | // Note: move the sample code to the bottom of this 60 | // file before uncommenting it. 61 | // 62 | 63 | 64 | // 65 | // Globals: 66 | // 67 | 68 | // Global hashes, used by various utility routines 69 | var g_urls; 70 | var g_titles; 71 | var g_html_blocks; 72 | 73 | // Used to track when we're inside an ordered or unordered list 74 | // (see _ProcessListItems() for details): 75 | var g_list_level = 0; 76 | 77 | 78 | exports.makeHtml = function(text) { 79 | // 80 | // Main function. The order in which other subs are called here is 81 | // essential. Link and image substitutions need to happen before 82 | // _EscapeSpecialCharsWithinTagAttributes(), so that any *'s or _'s in the 83 | // and tags get encoded. 84 | // 85 | 86 | // Clear the global hashes. If we don't clear these, you get conflicts 87 | // from other articles when generating a page which contains more than 88 | // one article (e.g. an index page that shows the N most recent 89 | // articles): 90 | g_urls = new Array(); 91 | g_titles = new Array(); 92 | g_html_blocks = new Array(); 93 | 94 | // attacklab: Replace ~ with ~T 95 | // This lets us use tilde as an escape char to avoid md5 hashes 96 | // The choice of character is arbitray; anything that isn't 97 | // magic in Markdown will work. 98 | text = text.replace(/~/g,"~T"); 99 | 100 | // attacklab: Replace $ with ~D 101 | // RegExp interprets $ as a special character 102 | // when it's in a replacement string 103 | text = text.replace(/\$/g,"~D"); 104 | 105 | // Standardize line endings 106 | text = text.replace(/\r\n/g,"\n"); // DOS to Unix 107 | text = text.replace(/\r/g,"\n"); // Mac to Unix 108 | 109 | // Make sure text begins and ends with a couple of newlines: 110 | text = "\n\n" + text + "\n\n"; 111 | 112 | // Convert all tabs to spaces. 113 | text = _Detab(text); 114 | 115 | // Strip any lines consisting only of spaces and tabs. 116 | // This makes subsequent regexen easier to write, because we can 117 | // match consecutive blank lines with /\n+/ instead of something 118 | // contorted like /[ \t]*\n+/ . 119 | text = text.replace(/^[ \t]+$/mg,""); 120 | 121 | // Turn block-level HTML blocks into hash entries 122 | text = _HashHTMLBlocks(text); 123 | 124 | // Strip link definitions, store in hashes. 125 | text = _StripLinkDefinitions(text); 126 | 127 | text = _RunBlockGamut(text); 128 | 129 | text = _UnescapeSpecialChars(text); 130 | 131 | // attacklab: Restore dollar signs 132 | text = text.replace(/~D/g,"$$"); 133 | 134 | // attacklab: Restore tildes 135 | text = text.replace(/~T/g,"~"); 136 | return text; 137 | } 138 | 139 | 140 | var _StripLinkDefinitions = function(text) { 141 | // 142 | // Strips link definitions from text, stores the URLs and titles in 143 | // hash references. 144 | // 145 | 146 | // Link defs are in the form: ^[id]: url "optional title" 147 | 148 | /* 149 | var text = text.replace(/ 150 | ^[ ]{0,3}\[(.+)\]: // id = $1 attacklab: g_tab_width - 1 151 | [ \t]* 152 | \n? // maybe *one* newline 153 | [ \t]* 154 | ? // url = $2 155 | [ \t]* 156 | \n? // maybe one newline 157 | [ \t]* 158 | (?: 159 | (\n*) // any lines skipped = $3 attacklab: lookbehind removed 160 | ["(] 161 | (.+?) // title = $4 162 | [")] 163 | [ \t]* 164 | )? // title is optional 165 | (?:\n+|$) 166 | /gm, 167 | function(){...}); 168 | */ 169 | var text = text.replace(/^[ ]{0,3}\[(.+)\]:[ \t]*\n?[ \t]*?[ \t]*\n?[ \t]*(?:(\n*)["(](.+?)[")][ \t]*)?(?:\n+|\Z)/gm, 170 | function (wholeMatch,m1,m2,m3,m4) { 171 | m1 = m1.toLowerCase(); 172 | g_urls[m1] = _EncodeAmpsAndAngles(m2); // Link IDs are case-insensitive 173 | if (m3) { 174 | // Oops, found blank lines, so it's not a title. 175 | // Put back the parenthetical statement we stole. 176 | return m3+m4; 177 | } else if (m4) { 178 | g_titles[m1] = m4.replace(/"/g,"""); 179 | } 180 | 181 | // Completely remove the definition from the text 182 | return ""; 183 | } 184 | ); 185 | 186 | return text; 187 | } 188 | 189 | 190 | var _HashHTMLBlocks = function(text) { 191 | // attacklab: Double up blank lines to reduce lookaround 192 | text = text.replace(/\n/g,"\n\n"); 193 | 194 | // Hashify HTML blocks: 195 | // We only want to do this for block-level HTML tags, such as headers, 196 | // lists, and tables. That's because we still want to wrap

    s around 197 | // "paragraphs" that are wrapped in non-block-level tags, such as anchors, 198 | // phrase emphasis, and spans. The list of tags we're looking for is 199 | // hard-coded: 200 | var block_tags_a = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del" 201 | var block_tags_b = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math" 202 | 203 | // First, look for nested blocks, e.g.: 204 | //

    205 | //
    206 | // tags for inner block must be indented. 207 | //
    208 | //
    209 | // 210 | // The outermost tags must start at the left margin for this to match, and 211 | // the inner nested divs must be indented. 212 | // We need to do this before the next, more liberal match, because the next 213 | // match will start at the first `
    ` and stop at the first `
    `. 214 | 215 | // attacklab: This regex can be expensive when it fails. 216 | /* 217 | var text = text.replace(/ 218 | ( // save in $1 219 | ^ // start of line (with /m) 220 | <($block_tags_a) // start tag = $2 221 | \b // word break 222 | // attacklab: hack around khtml/pcre bug... 223 | [^\r]*?\n // any number of lines, minimally matching 224 | // the matching end tag 225 | [ \t]* // trailing spaces/tabs 226 | (?=\n+) // followed by a newline 227 | ) // attacklab: there are sentinel newlines at end of document 228 | /gm,function(){...}}; 229 | */ 230 | text = text.replace(/^(<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del)\b[^\r]*?\n<\/\2>[ \t]*(?=\n+))/gm,hashElement); 231 | 232 | // 233 | // Now match more liberally, simply from `\n` to `\n` 234 | // 235 | 236 | /* 237 | var text = text.replace(/ 238 | ( // save in $1 239 | ^ // start of line (with /m) 240 | <($block_tags_b) // start tag = $2 241 | \b // word break 242 | // attacklab: hack around khtml/pcre bug... 243 | [^\r]*? // any number of lines, minimally matching 244 | .* // the matching end tag 245 | [ \t]* // trailing spaces/tabs 246 | (?=\n+) // followed by a newline 247 | ) // attacklab: there are sentinel newlines at end of document 248 | /gm,function(){...}}; 249 | */ 250 | text = text.replace(/^(<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math)\b[^\r]*?.*<\/\2>[ \t]*(?=\n+)\n)/gm,hashElement); 251 | 252 | // Special case just for
    . It was easier to make a special case than 253 | // to make the other regex more complicated. 254 | 255 | /* 256 | text = text.replace(/ 257 | ( // save in $1 258 | \n\n // Starting after a blank line 259 | [ ]{0,3} 260 | (<(hr) // start tag = $2 261 | \b // word break 262 | ([^<>])*? // 263 | \/?>) // the matching end tag 264 | [ \t]* 265 | (?=\n{2,}) // followed by a blank line 266 | ) 267 | /g,hashElement); 268 | */ 269 | text = text.replace(/(\n[ ]{0,3}(<(hr)\b([^<>])*?\/?>)[ \t]*(?=\n{2,}))/g,hashElement); 270 | 271 | // Special case for standalone HTML comments: 272 | 273 | /* 274 | text = text.replace(/ 275 | ( // save in $1 276 | \n\n // Starting after a blank line 277 | [ ]{0,3} // attacklab: g_tab_width - 1 278 | 281 | [ \t]* 282 | (?=\n{2,}) // followed by a blank line 283 | ) 284 | /g,hashElement); 285 | */ 286 | text = text.replace(/(\n\n[ ]{0,3}[ \t]*(?=\n{2,}))/g,hashElement); 287 | 288 | // PHP and ASP-style processor instructions ( and <%...%>) 289 | 290 | /* 291 | text = text.replace(/ 292 | (?: 293 | \n\n // Starting after a blank line 294 | ) 295 | ( // save in $1 296 | [ ]{0,3} // attacklab: g_tab_width - 1 297 | (?: 298 | <([?%]) // $2 299 | [^\r]*? 300 | \2> 301 | ) 302 | [ \t]* 303 | (?=\n{2,}) // followed by a blank line 304 | ) 305 | /g,hashElement); 306 | */ 307 | text = text.replace(/(?:\n\n)([ ]{0,3}(?:<([?%])[^\r]*?\2>)[ \t]*(?=\n{2,}))/g,hashElement); 308 | 309 | // attacklab: Undo double lines (see comment at top of this function) 310 | text = text.replace(/\n\n/g,"\n"); 311 | return text; 312 | } 313 | 314 | var hashElement = function(wholeMatch,m1) { 315 | var blockText = m1; 316 | 317 | // Undo double lines 318 | blockText = blockText.replace(/\n\n/g,"\n"); 319 | blockText = blockText.replace(/^\n/,""); 320 | 321 | // strip trailing blank lines 322 | blockText = blockText.replace(/\n+$/g,""); 323 | 324 | // Replace the element text with a marker ("~KxK" where x is its key) 325 | blockText = "\n\n~K" + (g_html_blocks.push(blockText)-1) + "K\n\n"; 326 | 327 | return blockText; 328 | }; 329 | 330 | var _RunBlockGamut = function(text) { 331 | // 332 | // These are all the transformations that form block-level 333 | // tags like paragraphs, headers, and list items. 334 | // 335 | text = _DoHeaders(text); 336 | 337 | // Do Horizontal Rules: 338 | var key = hashBlock("
    "); 339 | text = text.replace(/^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$/gm,key); 340 | text = text.replace(/^[ ]{0,2}([ ]?\-[ ]?){3,}[ \t]*$/gm,key); 341 | text = text.replace(/^[ ]{0,2}([ ]?\_[ ]?){3,}[ \t]*$/gm,key); 342 | 343 | text = _DoLists(text); 344 | text = _DoCodeBlocks(text); 345 | text = _DoBlockQuotes(text); 346 | 347 | // We already ran _HashHTMLBlocks() before, in Markdown(), but that 348 | // was to escape raw HTML in the original Markdown source. This time, 349 | // we're escaping the markup we've just created, so that we don't wrap 350 | //

    tags around block-level tags. 351 | text = _HashHTMLBlocks(text); 352 | text = _FormParagraphs(text); 353 | 354 | return text; 355 | } 356 | 357 | 358 | var _RunSpanGamut = function(text) { 359 | // 360 | // These are all the transformations that occur *within* block-level 361 | // tags like paragraphs, headers, and list items. 362 | // 363 | 364 | text = _DoCodeSpans(text); 365 | text = _EscapeSpecialCharsWithinTagAttributes(text); 366 | text = _EncodeBackslashEscapes(text); 367 | 368 | // Process anchor and image tags. Images must come first, 369 | // because ![foo][f] looks like an anchor. 370 | text = _DoImages(text); 371 | text = _DoAnchors(text); 372 | 373 | // Make links out of things like `` 374 | // Must come after _DoAnchors(), because you can use < and > 375 | // delimiters in inline links like [this](). 376 | text = _DoAutoLinks(text); 377 | text = _EncodeAmpsAndAngles(text); 378 | text = _DoItalicsAndBold(text); 379 | 380 | // Do hard breaks: 381 | text = text.replace(/ +\n/g,"
    \n"); 382 | 383 | return text; 384 | } 385 | 386 | var _EscapeSpecialCharsWithinTagAttributes = function(text) { 387 | // 388 | // Within tags -- meaning between < and > -- encode [\ ` * _] so they 389 | // don't conflict with their use in Markdown for code, italics and strong. 390 | // 391 | 392 | // Build a regex to find HTML tags and comments. See Friedl's 393 | // "Mastering Regular Expressions", 2nd Ed., pp. 200-201. 394 | var regex = /(<[a-z\/!$]("[^"]*"|'[^']*'|[^'">])*>|)/gi; 395 | 396 | text = text.replace(regex, function(wholeMatch) { 397 | var tag = wholeMatch.replace(/(.)<\/?code>(?=.)/g,"$1`"); 398 | tag = escapeCharacters(tag,"\\`*_"); 399 | return tag; 400 | }); 401 | 402 | return text; 403 | } 404 | 405 | var _DoAnchors = function(text) { 406 | // 407 | // Turn Markdown link shortcuts into XHTML
    tags. 408 | // 409 | // 410 | // First, handle reference-style links: [link text] [id] 411 | // 412 | 413 | /* 414 | text = text.replace(/ 415 | ( // wrap whole match in $1 416 | \[ 417 | ( 418 | (?: 419 | \[[^\]]*\] // allow brackets nested one level 420 | | 421 | [^\[] // or anything else 422 | )* 423 | ) 424 | \] 425 | 426 | [ ]? // one optional space 427 | (?:\n[ ]*)? // one optional newline followed by spaces 428 | 429 | \[ 430 | (.*?) // id = $3 431 | \] 432 | )()()()() // pad remaining backreferences 433 | /g,_DoAnchors_callback); 434 | */ 435 | text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g,writeAnchorTag); 436 | 437 | // 438 | // Next, inline-style links: [link text](url "optional title") 439 | // 440 | 441 | /* 442 | text = text.replace(/ 443 | ( // wrap whole match in $1 444 | \[ 445 | ( 446 | (?: 447 | \[[^\]]*\] // allow brackets nested one level 448 | | 449 | [^\[\]] // or anything else 450 | ) 451 | ) 452 | \] 453 | \( // literal paren 454 | [ \t]* 455 | () // no id, so leave $3 empty 456 | ? // href = $4 457 | [ \t]* 458 | ( // $5 459 | (['"]) // quote char = $6 460 | (.*?) // Title = $7 461 | \6 // matching quote 462 | [ \t]* // ignore any spaces/tabs between closing quote and ) 463 | )? // title is optional 464 | \) 465 | ) 466 | /g,writeAnchorTag); 467 | */ 468 | text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\]\([ \t]*()?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,writeAnchorTag); 469 | 470 | // 471 | // Last, handle reference-style shortcuts: [link text] 472 | // These must come last in case you've also got [link test][1] 473 | // or [link test](/foo) 474 | // 475 | 476 | /* 477 | text = text.replace(/ 478 | ( // wrap whole match in $1 479 | \[ 480 | ([^\[\]]+) // link text = $2; can't contain '[' or ']' 481 | \] 482 | )()()()()() // pad rest of backreferences 483 | /g, writeAnchorTag); 484 | */ 485 | text = text.replace(/(\[([^\[\]]+)\])()()()()()/g, writeAnchorTag); 486 | 487 | return text; 488 | } 489 | 490 | var writeAnchorTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) { 491 | if (m7 == undefined) m7 = ""; 492 | var whole_match = m1; 493 | var link_text = m2; 494 | var link_id = m3.toLowerCase(); 495 | var url = m4; 496 | var title = m7; 497 | 498 | if (url == "") { 499 | if (link_id == "") { 500 | // lower-case and turn embedded newlines into spaces 501 | link_id = link_text.toLowerCase().replace(/ ?\n/g," "); 502 | } 503 | url = "#"+link_id; 504 | 505 | if (g_urls[link_id] != undefined) { 506 | url = g_urls[link_id]; 507 | if (g_titles[link_id] != undefined) { 508 | title = g_titles[link_id]; 509 | } 510 | } 511 | else { 512 | if (whole_match.search(/\(\s*\)$/m)>-1) { 513 | // Special case for explicit empty url 514 | url = ""; 515 | } else { 516 | return whole_match; 517 | } 518 | } 519 | } 520 | 521 | url = escapeCharacters(url,"*_"); 522 | var result = ""; 531 | 532 | return result; 533 | } 534 | 535 | 536 | var _DoImages = function(text) { 537 | // 538 | // Turn Markdown image shortcuts into tags. 539 | // 540 | 541 | // 542 | // First, handle reference-style labeled images: ![alt text][id] 543 | // 544 | 545 | /* 546 | text = text.replace(/ 547 | ( // wrap whole match in $1 548 | !\[ 549 | (.*?) // alt text = $2 550 | \] 551 | 552 | [ ]? // one optional space 553 | (?:\n[ ]*)? // one optional newline followed by spaces 554 | 555 | \[ 556 | (.*?) // id = $3 557 | \] 558 | )()()()() // pad rest of backreferences 559 | /g,writeImageTag); 560 | */ 561 | text = text.replace(/(!\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g,writeImageTag); 562 | 563 | // 564 | // Next, handle inline images: ![alt text](url "optional title") 565 | // Don't forget: encode * and _ 566 | 567 | /* 568 | text = text.replace(/ 569 | ( // wrap whole match in $1 570 | !\[ 571 | (.*?) // alt text = $2 572 | \] 573 | \s? // One optional whitespace character 574 | \( // literal paren 575 | [ \t]* 576 | () // no id, so leave $3 empty 577 | ? // src url = $4 578 | [ \t]* 579 | ( // $5 580 | (['"]) // quote char = $6 581 | (.*?) // title = $7 582 | \6 // matching quote 583 | [ \t]* 584 | )? // title is optional 585 | \) 586 | ) 587 | /g,writeImageTag); 588 | */ 589 | text = text.replace(/(!\[(.*?)\]\s?\([ \t]*()?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,writeImageTag); 590 | 591 | return text; 592 | } 593 | 594 | var writeImageTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) { 595 | var whole_match = m1; 596 | var alt_text = m2; 597 | var link_id = m3.toLowerCase(); 598 | var url = m4; 599 | var title = m7; 600 | 601 | if (!title) title = ""; 602 | 603 | if (url == "") { 604 | if (link_id == "") { 605 | // lower-case and turn embedded newlines into spaces 606 | link_id = alt_text.toLowerCase().replace(/ ?\n/g," "); 607 | } 608 | url = "#"+link_id; 609 | 610 | if (g_urls[link_id] != undefined) { 611 | url = g_urls[link_id]; 612 | if (g_titles[link_id] != undefined) { 613 | title = g_titles[link_id]; 614 | } 615 | } 616 | else { 617 | return whole_match; 618 | } 619 | } 620 | 621 | alt_text = alt_text.replace(/"/g,"""); 622 | url = escapeCharacters(url,"*_"); 623 | var result = "\""" + _RunSpanGamut(m1) + "");}); 651 | 652 | text = text.replace(/^(.+)[ \t]*\n-+[ \t]*\n+/gm, 653 | function(matchFound,m1){return hashBlock("

    " + _RunSpanGamut(m1) + "

    ");}); 654 | 655 | // atx-style headers: 656 | // # Header 1 657 | // ## Header 2 658 | // ## Header 2 with closing hashes ## 659 | // ... 660 | // ###### Header 6 661 | // 662 | 663 | /* 664 | text = text.replace(/ 665 | ^(\#{1,6}) // $1 = string of #'s 666 | [ \t]* 667 | (.+?) // $2 = Header text 668 | [ \t]* 669 | \#* // optional closing #'s (not counted) 670 | \n+ 671 | /gm, function() {...}); 672 | */ 673 | 674 | text = text.replace(/^(\#{1,6})[ \t]*(.+?)[ \t]*\#*\n+/gm, 675 | function(wholeMatch,m1,m2) { 676 | var h_level = m1.length; 677 | return hashBlock("" + _RunSpanGamut(m2) + ""); 678 | }); 679 | 680 | return text; 681 | } 682 | 683 | // This declaration keeps Dojo compressor from outputting garbage: 684 | var _ProcessListItems; 685 | 686 | var _DoLists = function(text) { 687 | // 688 | // Form HTML ordered (numbered) and unordered (bulleted) lists. 689 | // 690 | 691 | // attacklab: add sentinel to hack around khtml/safari bug: 692 | // http://bugs.webkit.org/show_bug.cgi?id=11231 693 | text += "~0"; 694 | 695 | // Re-usable pattern to match any entirel ul or ol list: 696 | 697 | /* 698 | var whole_list = / 699 | ( // $1 = whole list 700 | ( // $2 701 | [ ]{0,3} // attacklab: g_tab_width - 1 702 | ([*+-]|\d+[.]) // $3 = first list item marker 703 | [ \t]+ 704 | ) 705 | [^\r]+? 706 | ( // $4 707 | ~0 // sentinel for workaround; should be $ 708 | | 709 | \n{2,} 710 | (?=\S) 711 | (?! // Negative lookahead for another list item marker 712 | [ \t]* 713 | (?:[*+-]|\d+[.])[ \t]+ 714 | ) 715 | ) 716 | )/g 717 | */ 718 | var whole_list = /^(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm; 719 | 720 | if (g_list_level) { 721 | text = text.replace(whole_list,function(wholeMatch,m1,m2) { 722 | var list = m1; 723 | var list_type = (m2.search(/[*+-]/g)>-1) ? "ul" : "ol"; 724 | 725 | // Turn double returns into triple returns, so that we can make a 726 | // paragraph for the last item in a list, if necessary: 727 | list = list.replace(/\n{2,}/g,"\n\n\n");; 728 | var result = _ProcessListItems(list); 729 | 730 | // Trim any trailing whitespace, to put the closing `` 731 | // up on the preceding line, to get it past the current stupid 732 | // HTML block parser. This is a hack to work around the terrible 733 | // hack that is the HTML block parser. 734 | result = result.replace(/\s+$/,""); 735 | result = "<"+list_type+">" + result + "\n"; 736 | return result; 737 | }); 738 | } else { 739 | whole_list = /(\n\n|^\n?)(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/g; 740 | text = text.replace(whole_list,function(wholeMatch,m1,m2,m3) { 741 | var runup = m1; 742 | var list = m2; 743 | 744 | var list_type = (m3.search(/[*+-]/g)>-1) ? "ul" : "ol"; 745 | // Turn double returns into triple returns, so that we can make a 746 | // paragraph for the last item in a list, if necessary: 747 | var list = list.replace(/\n{2,}/g,"\n\n\n");; 748 | var result = _ProcessListItems(list); 749 | result = runup + "<"+list_type+">\n" + result + "\n"; 750 | return result; 751 | }); 752 | } 753 | 754 | // attacklab: strip sentinel 755 | text = text.replace(/~0/,""); 756 | 757 | return text; 758 | } 759 | 760 | _ProcessListItems = function(list_str) { 761 | // 762 | // Process the contents of a single ordered or unordered list, splitting it 763 | // into individual list items. 764 | // 765 | // The $g_list_level global keeps track of when we're inside a list. 766 | // Each time we enter a list, we increment it; when we leave a list, 767 | // we decrement. If it's zero, we're not in a list anymore. 768 | // 769 | // We do this because when we're not inside a list, we want to treat 770 | // something like this: 771 | // 772 | // I recommend upgrading to version 773 | // 8. Oops, now this line is treated 774 | // as a sub-list. 775 | // 776 | // As a single paragraph, despite the fact that the second line starts 777 | // with a digit-period-space sequence. 778 | // 779 | // Whereas when we're inside a list (or sub-list), that line will be 780 | // treated as the start of a sub-list. What a kludge, huh? This is 781 | // an aspect of Markdown's syntax that's hard to parse perfectly 782 | // without resorting to mind-reading. Perhaps the solution is to 783 | // change the syntax rules such that sub-lists must start with a 784 | // starting cardinal number; e.g. "1." or "a.". 785 | 786 | g_list_level++; 787 | 788 | // trim trailing blank lines: 789 | list_str = list_str.replace(/\n{2,}$/,"\n"); 790 | 791 | // attacklab: add sentinel to emulate \z 792 | list_str += "~0"; 793 | 794 | /* 795 | list_str = list_str.replace(/ 796 | (\n)? // leading line = $1 797 | (^[ \t]*) // leading whitespace = $2 798 | ([*+-]|\d+[.]) [ \t]+ // list marker = $3 799 | ([^\r]+? // list item text = $4 800 | (\n{1,2})) 801 | (?= \n* (~0 | \2 ([*+-]|\d+[.]) [ \t]+)) 802 | /gm, function(){...}); 803 | */ 804 | list_str = list_str.replace(/(\n)?(^[ \t]*)([*+-]|\d+[.])[ \t]+([^\r]+?(\n{1,2}))(?=\n*(~0|\2([*+-]|\d+[.])[ \t]+))/gm, 805 | function(wholeMatch,m1,m2,m3,m4){ 806 | var item = m4; 807 | var leading_line = m1; 808 | var leading_space = m2; 809 | 810 | if (leading_line || (item.search(/\n{2,}/)>-1)) { 811 | item = _RunBlockGamut(_Outdent(item)); 812 | } 813 | else { 814 | // Recursion for sub-lists: 815 | item = _DoLists(_Outdent(item)); 816 | item = item.replace(/\n$/,""); // chomp(item) 817 | item = _RunSpanGamut(item); 818 | } 819 | 820 | return "
  • " + item + "
  • \n"; 821 | } 822 | ); 823 | 824 | // attacklab: strip sentinel 825 | list_str = list_str.replace(/~0/g,""); 826 | 827 | g_list_level--; 828 | return list_str; 829 | } 830 | 831 | 832 | var _DoCodeBlocks = function(text) { 833 | // 834 | // Process Markdown `
    ` blocks.
     835 | //  
     836 | 
     837 | 	/*
     838 | 		text = text.replace(text,
     839 | 			/(?:\n\n|^)
     840 | 			(								// $1 = the code block -- one or more lines, starting with a space/tab
     841 | 				(?:
     842 | 					(?:[ ]{4}|\t)			// Lines must start with a tab or a tab-width of spaces - attacklab: g_tab_width
     843 | 					.*\n+
     844 | 				)+
     845 | 			)
     846 | 			(\n*[ ]{0,3}[^ \t\n]|(?=~0))	// attacklab: g_tab_width
     847 | 		/g,function(){...});
     848 | 	*/
     849 | 
     850 | 	// attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug
     851 | 	text += "~0";
     852 | 	
     853 | 	text = text.replace(/(?:\n\n|^)((?:(?:[ ]{4}|\t).*\n+)+)(\n*[ ]{0,3}[^ \t\n]|(?=~0))/g,
     854 | 		function(wholeMatch,m1,m2) {
     855 | 			var codeblock = m1;
     856 | 			var nextChar = m2;
     857 | 		
     858 | 			codeblock = _EncodeCode( _Outdent(codeblock));
     859 | 			codeblock = _Detab(codeblock);
     860 | 			codeblock = codeblock.replace(/^\n+/g,""); // trim leading newlines
     861 | 			codeblock = codeblock.replace(/\n+$/g,""); // trim trailing whitespace
     862 | 
     863 | 			codeblock = "
    " + codeblock + "\n
    "; 864 | 865 | return hashBlock(codeblock) + nextChar; 866 | } 867 | ); 868 | 869 | // attacklab: strip sentinel 870 | text = text.replace(/~0/,""); 871 | 872 | return text; 873 | } 874 | 875 | var hashBlock = function(text) { 876 | text = text.replace(/(^\n+|\n+$)/g,""); 877 | return "\n\n~K" + (g_html_blocks.push(text)-1) + "K\n\n"; 878 | } 879 | 880 | 881 | var _DoCodeSpans = function(text) { 882 | // 883 | // * Backtick quotes are used for spans. 884 | // 885 | // * You can use multiple backticks as the delimiters if you want to 886 | // include literal backticks in the code span. So, this input: 887 | // 888 | // Just type ``foo `bar` baz`` at the prompt. 889 | // 890 | // Will translate to: 891 | // 892 | //

    Just type foo `bar` baz at the prompt.

    893 | // 894 | // There's no arbitrary limit to the number of backticks you 895 | // can use as delimters. If you need three consecutive backticks 896 | // in your code, use four for delimiters, etc. 897 | // 898 | // * You can use spaces to get literal backticks at the edges: 899 | // 900 | // ... type `` `bar` `` ... 901 | // 902 | // Turns to: 903 | // 904 | // ... type `bar` ... 905 | // 906 | 907 | /* 908 | text = text.replace(/ 909 | (^|[^\\]) // Character before opening ` can't be a backslash 910 | (`+) // $2 = Opening run of ` 911 | ( // $3 = The code block 912 | [^\r]*? 913 | [^`] // attacklab: work around lack of lookbehind 914 | ) 915 | \2 // Matching closer 916 | (?!`) 917 | /gm, function(){...}); 918 | */ 919 | 920 | text = text.replace(/(^|[^\\])(`+)([^\r]*?[^`])\2(?!`)/gm, 921 | function(wholeMatch,m1,m2,m3,m4) { 922 | var c = m3; 923 | c = c.replace(/^([ \t]*)/g,""); // leading whitespace 924 | c = c.replace(/[ \t]*$/g,""); // trailing whitespace 925 | c = _EncodeCode(c); 926 | return m1+""+c+""; 927 | }); 928 | 929 | return text; 930 | } 931 | 932 | 933 | var _EncodeCode = function(text) { 934 | // 935 | // Encode/escape certain characters inside Markdown code runs. 936 | // The point is that in code, these characters are literals, 937 | // and lose their special Markdown meanings. 938 | // 939 | // Encode all ampersands; HTML entities are not 940 | // entities within a Markdown code span. 941 | text = text.replace(/&/g,"&"); 942 | 943 | // Do the angle bracket song and dance: 944 | text = text.replace(//g,">"); 946 | 947 | // Now, escape characters that are magic in Markdown: 948 | text = escapeCharacters(text,"\*_{}[]\\",false); 949 | 950 | // jj the line above breaks this: 951 | //--- 952 | 953 | //* Item 954 | 955 | // 1. Subitem 956 | 957 | // special char: * 958 | //--- 959 | 960 | return text; 961 | } 962 | 963 | 964 | var _DoItalicsAndBold = function(text) { 965 | 966 | // must go first: 967 | text = text.replace(/(\*\*|__)(?=\S)([^\r]*?\S[*_]*)\1/g, 968 | "$2"); 969 | 970 | text = text.replace(/(\*|_)(?=\S)([^\r]*?\S)\1/g, 971 | "$2"); 972 | 973 | return text; 974 | } 975 | 976 | 977 | var _DoBlockQuotes = function(text) { 978 | 979 | /* 980 | text = text.replace(/ 981 | ( // Wrap whole match in $1 982 | ( 983 | ^[ \t]*>[ \t]? // '>' at the start of a line 984 | .+\n // rest of the first line 985 | (.+\n)* // subsequent consecutive lines 986 | \n* // blanks 987 | )+ 988 | ) 989 | /gm, function(){...}); 990 | */ 991 | 992 | text = text.replace(/((^[ \t]*>[ \t]?.+\n(.+\n)*\n*)+)/gm, 993 | function(wholeMatch,m1) { 994 | var bq = m1; 995 | 996 | // attacklab: hack around Konqueror 3.5.4 bug: 997 | // "----------bug".replace(/^-/g,"") == "bug" 998 | 999 | bq = bq.replace(/^[ \t]*>[ \t]?/gm,"~0"); // trim one level of quoting 1000 | 1001 | // attacklab: clean up hack 1002 | bq = bq.replace(/~0/g,""); 1003 | 1004 | bq = bq.replace(/^[ \t]+$/gm,""); // trim whitespace-only lines 1005 | bq = _RunBlockGamut(bq); // recurse 1006 | 1007 | bq = bq.replace(/(^|\n)/g,"$1 "); 1008 | // These leading spaces screw with
     content, so we need to fix that:
    1009 | 			bq = bq.replace(
    1010 | 					/(\s*
    [^\r]+?<\/pre>)/gm,
    1011 | 				function(wholeMatch,m1) {
    1012 | 					var pre = m1;
    1013 | 					// attacklab: hack around Konqueror 3.5.4 bug:
    1014 | 					pre = pre.replace(/^  /mg,"~0");
    1015 | 					pre = pre.replace(/~0/g,"");
    1016 | 					return pre;
    1017 | 				});
    1018 | 			
    1019 | 			return hashBlock("
    \n" + bq + "\n
    "); 1020 | }); 1021 | return text; 1022 | } 1023 | 1024 | 1025 | var _FormParagraphs = function(text) { 1026 | // 1027 | // Params: 1028 | // $text - string to process with html

    tags 1029 | // 1030 | 1031 | // Strip leading and trailing lines: 1032 | text = text.replace(/^\n+/g,""); 1033 | text = text.replace(/\n+$/g,""); 1034 | 1035 | var grafs = text.split(/\n{2,}/g); 1036 | var grafsOut = new Array(); 1037 | 1038 | // 1039 | // Wrap

    tags. 1040 | // 1041 | var end = grafs.length; 1042 | for (var i=0; i= 0) { 1047 | grafsOut.push(str); 1048 | } 1049 | else if (str.search(/\S/) >= 0) { 1050 | str = _RunSpanGamut(str); 1051 | str = str.replace(/^([ \t]*)/g,"

    "); 1052 | str += "

    " 1053 | grafsOut.push(str); 1054 | } 1055 | 1056 | } 1057 | 1058 | // 1059 | // Unhashify HTML blocks 1060 | // 1061 | end = grafsOut.length; 1062 | for (var i=0; i= 0) { 1065 | var blockText = g_html_blocks[RegExp.$1]; 1066 | blockText = blockText.replace(/\$/g,"$$$$"); // Escape any dollar signs 1067 | grafsOut[i] = grafsOut[i].replace(/~K\d+K/,blockText); 1068 | } 1069 | } 1070 | 1071 | return grafsOut.join("\n\n"); 1072 | } 1073 | 1074 | 1075 | var _EncodeAmpsAndAngles = function(text) { 1076 | // Smart processing for ampersands and angle brackets that need to be encoded. 1077 | 1078 | // Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin: 1079 | // http://bumppo.net/projects/amputator/ 1080 | text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g,"&"); 1081 | 1082 | // Encode naked <'s 1083 | text = text.replace(/<(?![a-z\/?\$!])/gi,"<"); 1084 | 1085 | return text; 1086 | } 1087 | 1088 | 1089 | var _EncodeBackslashEscapes = function(text) { 1090 | // 1091 | // Parameter: String. 1092 | // Returns: The string, with after processing the following backslash 1093 | // escape sequences. 1094 | // 1095 | 1096 | // attacklab: The polite way to do this is with the new 1097 | // escapeCharacters() function: 1098 | // 1099 | // text = escapeCharacters(text,"\\",true); 1100 | // text = escapeCharacters(text,"`*_{}[]()>#+-.!",true); 1101 | // 1102 | // ...but we're sidestepping its use of the (slow) RegExp constructor 1103 | // as an optimization for Firefox. This function gets called a LOT. 1104 | 1105 | text = text.replace(/\\(\\)/g,escapeCharacters_callback); 1106 | text = text.replace(/\\([`*_{}\[\]()>#+-.!])/g,escapeCharacters_callback); 1107 | return text; 1108 | } 1109 | 1110 | 1111 | var _DoAutoLinks = function(text) { 1112 | 1113 | text = text.replace(/<((https?|ftp|dict):[^'">\s]+)>/gi,"
    $1"); 1114 | 1115 | // Email addresses: 1116 | 1117 | /* 1118 | text = text.replace(/ 1119 | < 1120 | (?:mailto:)? 1121 | ( 1122 | [-.\w]+ 1123 | \@ 1124 | [-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+ 1125 | ) 1126 | > 1127 | /gi, _DoAutoLinks_callback()); 1128 | */ 1129 | text = text.replace(/<(?:mailto:)?([-.\w]+\@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)>/gi, 1130 | function(wholeMatch,m1) { 1131 | return _EncodeEmailAddress( _UnescapeSpecialChars(m1) ); 1132 | } 1133 | ); 1134 | 1135 | return text; 1136 | } 1137 | 1138 | 1139 | var _EncodeEmailAddress = function(addr) { 1140 | // 1141 | // Input: an email address, e.g. "foo@example.com" 1142 | // 1143 | // Output: the email address as a mailto link, with each character 1144 | // of the address encoded as either a decimal or hex entity, in 1145 | // the hopes of foiling most address harvesting spam bots. E.g.: 1146 | // 1147 | // foo 1149 | // @example.com 1150 | // 1151 | // Based on a filter by Matthew Wickline, posted to the BBEdit-Talk 1152 | // mailing list: 1153 | // 1154 | 1155 | // attacklab: why can't javascript speak hex? 1156 | function char2hex(ch) { 1157 | var hexDigits = '0123456789ABCDEF'; 1158 | var dec = ch.charCodeAt(0); 1159 | return(hexDigits.charAt(dec>>4) + hexDigits.charAt(dec&15)); 1160 | } 1161 | 1162 | var encode = [ 1163 | function(ch){return "&#"+ch.charCodeAt(0)+";";}, 1164 | function(ch){return "&#x"+char2hex(ch)+";";}, 1165 | function(ch){return ch;} 1166 | ]; 1167 | 1168 | addr = "mailto:" + addr; 1169 | 1170 | addr = addr.replace(/./g, function(ch) { 1171 | if (ch == "@") { 1172 | // this *must* be encoded. I insist. 1173 | ch = encode[Math.floor(Math.random()*2)](ch); 1174 | } else if (ch !=":") { 1175 | // leave ':' alone (to spot mailto: later) 1176 | var r = Math.random(); 1177 | // roughly 10% raw, 45% hex, 45% dec 1178 | ch = ( 1179 | r > .9 ? encode[2](ch) : 1180 | r > .45 ? encode[1](ch) : 1181 | encode[0](ch) 1182 | ); 1183 | } 1184 | return ch; 1185 | }); 1186 | 1187 | addr = "" + addr + ""; 1188 | addr = addr.replace(/">.+:/g,"\">"); // strip the mailto: from the visible part 1189 | 1190 | return addr; 1191 | } 1192 | 1193 | 1194 | var _UnescapeSpecialChars = function(text) { 1195 | // 1196 | // Swap back in all the special characters we've hidden. 1197 | // 1198 | text = text.replace(/~E(\d+)E/g, 1199 | function(wholeMatch,m1) { 1200 | var charCodeToReplace = parseInt(m1); 1201 | return String.fromCharCode(charCodeToReplace); 1202 | } 1203 | ); 1204 | return text; 1205 | } 1206 | 1207 | 1208 | var _Outdent = function(text) { 1209 | // 1210 | // Remove one level of line-leading tabs or spaces 1211 | // 1212 | 1213 | // attacklab: hack around Konqueror 3.5.4 bug: 1214 | // "----------bug".replace(/^-/g,"") == "bug" 1215 | 1216 | text = text.replace(/^(\t|[ ]{1,4})/gm,"~0"); // attacklab: g_tab_width 1217 | 1218 | // attacklab: clean up hack 1219 | text = text.replace(/~0/g,"") 1220 | 1221 | return text; 1222 | } 1223 | 1224 | var _Detab = function(text) { 1225 | // attacklab: Detab's completely rewritten for speed. 1226 | // In perl we could fix it by anchoring the regexp with \G. 1227 | // In javascript we're less fortunate. 1228 | 1229 | // expand first n-1 tabs 1230 | text = text.replace(/\t(?=\t)/g," "); // attacklab: g_tab_width 1231 | 1232 | // replace the nth with two sentinels 1233 | text = text.replace(/\t/g,"~A~B"); 1234 | 1235 | // use the sentinel to anchor our regex so it doesn't explode 1236 | text = text.replace(/~B(.+?)~A/g, 1237 | function(wholeMatch,m1,m2) { 1238 | var leadingText = m1; 1239 | var numSpaces = 4 - leadingText.length % 4; // attacklab: g_tab_width 1240 | 1241 | // there *must* be a better way to do this: 1242 | for (var i=0; i