19 |
├── _id ├── .gitignore ├── _attachments ├── style │ └── main.css ├── script │ └── app.js ├── account.html ├── ajax_hello.html └── index.html ├── vendor └── couchapp │ ├── evently │ ├── docs │ │ ├── index │ │ │ ├── path.txt │ │ │ ├── mustache.html │ │ │ └── data.js │ │ └── topic │ │ │ ├── path.txt │ │ │ ├── mustache.html │ │ │ ├── data.js │ │ │ ├── edit │ │ │ └── _init │ │ │ │ ├── selectors │ │ │ │ ├── a.edit │ │ │ │ │ └── click.js │ │ │ │ └── a.run │ │ │ │ │ └── click.js │ │ │ │ └── fun.js │ │ │ └── after.js │ ├── account │ │ ├── loginForm │ │ │ ├── selectors │ │ │ │ ├── a[href=#signup].json │ │ │ │ └── form │ │ │ │ │ └── submit.js │ │ │ ├── after.js │ │ │ └── mustache.html │ │ ├── signupForm │ │ │ ├── selectors │ │ │ │ ├── a[href=#login].json │ │ │ │ └── form │ │ │ │ │ └── submit.js │ │ │ ├── after.js │ │ │ └── mustache.html │ │ ├── loggedIn │ │ │ ├── selectors.json │ │ │ ├── after.js │ │ │ ├── mustache.html │ │ │ └── data.js │ │ ├── loggedOut │ │ │ ├── mustache.html │ │ │ └── selectors.json │ │ ├── adminParty.js │ │ ├── doLogout.js │ │ ├── doLogin.js │ │ ├── doSignup.js │ │ └── _init.js │ └── profile │ │ ├── loggedOut │ │ ├── mustache.html │ │ └── after.js │ │ ├── noProfile │ │ ├── data.js │ │ ├── mustache.html │ │ └── selectors │ │ │ └── form │ │ │ └── submit.js │ │ ├── profileReady │ │ ├── after.js │ │ ├── data.js │ │ └── mustache.html │ │ └── loggedIn.js │ ├── metadata.json │ ├── docs │ ├── profile.md │ ├── docs.md │ ├── couchapp.md │ ├── pathbinder.md │ ├── evently.md │ └── account.md │ ├── README.md │ ├── lib │ ├── redirect.js │ ├── list.js │ ├── cache.js │ ├── atom.js │ ├── path.js │ ├── docform.js │ └── markdown.js │ └── _attachments │ ├── docs.js │ ├── docs.css │ ├── docs.html │ ├── jquery.couch.app.util.js │ ├── jquery.pathbinder.js │ ├── jquery.mustache.js │ ├── jquery.couch.app.js │ └── jquery.evently.js ├── evently └── hello │ └── _init │ └── mustache.html └── couchapp.json /_id: -------------------------------------------------------------------------------- 1 | _design/evently_demo -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .couchapprc 2 | -------------------------------------------------------------------------------- /_attachments/style/main.css: -------------------------------------------------------------------------------- 1 | /* add styles here */ -------------------------------------------------------------------------------- /vendor/couchapp/evently/docs/index/path.txt: -------------------------------------------------------------------------------- 1 | / -------------------------------------------------------------------------------- /evently/hello/_init/mustache.html: -------------------------------------------------------------------------------- 1 |
hello
2 | -------------------------------------------------------------------------------- /vendor/couchapp/evently/docs/topic/path.txt: -------------------------------------------------------------------------------- 1 | /topic/:id -------------------------------------------------------------------------------- /vendor/couchapp/evently/docs/topic/mustache.html: -------------------------------------------------------------------------------- 1 |Please log in to see your profile.
-------------------------------------------------------------------------------- /vendor/couchapp/evently/profile/loggedOut/after.js: -------------------------------------------------------------------------------- 1 | function() { 2 | $$(this).profile = null; 3 | }; -------------------------------------------------------------------------------- /vendor/couchapp/evently/profile/noProfile/data.js: -------------------------------------------------------------------------------- 1 | function(e, userCtx) { 2 | return userCtx; 3 | } -------------------------------------------------------------------------------- /vendor/couchapp/evently/profile/profileReady/after.js: -------------------------------------------------------------------------------- 1 | function(e, p) { 2 | $$(this).profile = p; 3 | }; -------------------------------------------------------------------------------- /vendor/couchapp/metadata.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "couchapp", 3 | "description": "official couchapp vendor" 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/loginForm/after.js: -------------------------------------------------------------------------------- 1 | function() { 2 | $("input[name=name]", this).focus(); 3 | } -------------------------------------------------------------------------------- /vendor/couchapp/evently/account/signupForm/after.js: -------------------------------------------------------------------------------- 1 | function() { 2 | $("input[name=name]", this).focus(); 3 | } -------------------------------------------------------------------------------- /vendor/couchapp/evently/account/adminParty.js: -------------------------------------------------------------------------------- 1 | function() { 2 | alert("Admin party! Fix this in Futon before proceeding."); 3 | } -------------------------------------------------------------------------------- /vendor/couchapp/evently/docs/index/mustache.html: -------------------------------------------------------------------------------- 1 |Hello {{nickname}}!
8 | -------------------------------------------------------------------------------- /vendor/couchapp/evently/account/loginForm/mustache.html: -------------------------------------------------------------------------------- 1 | 7 | -------------------------------------------------------------------------------- /vendor/couchapp/evently/account/signupForm/mustache.html: -------------------------------------------------------------------------------- 1 | 7 | -------------------------------------------------------------------------------- /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/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/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/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/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/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/evently/profile/noProfile/mustache.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /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/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/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 = $('
Loading CouchDB Server info.
', 9 | after: function() { 10 | var widget = $(this); 11 | $.ajax({ 12 | url : '/', 13 | complete: function(req) { 14 | var resp = $.httpData(req, "json"); 15 | widget.trigger("version", [resp]); 16 | } 17 | }) 18 | } 19 | }, 20 | version: { 21 | mustache: "Running CouchDB version {{version}}
", 22 | data: function(e, resp) { 23 | return resp; 24 | } 25 | } 26 | }); 27 | }); 28 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /_attachments/account.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |This is a placeholder page
10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /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/_attachments/docs.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 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(''); 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/_attachments/jquery.pathbinder.js: -------------------------------------------------------------------------------- 1 | (function($) { 2 | // functions for handling the path 3 | // thanks sammy.js 4 | var PATH_REPLACER = "([^\/]+)", 5 | PATH_NAME_MATCHER = /:([\w\d]+)/g, 6 | QUERY_STRING_MATCHER = /\?([^#]*)$/, 7 | SPLAT_MATCHER = /(\*)/, 8 | SPLAT_REPLACER = "(.+)", 9 | _currentPath, 10 | _lastPath, 11 | _pathInterval; 12 | 13 | function hashChanged() { 14 | _currentPath = getPath(); 15 | // if path is actually changed from what we thought it was, then react 16 | if (_lastPath != _currentPath) { 17 | return triggerOnPath(_currentPath); 18 | } 19 | } 20 | 21 | $.pathbinder = { 22 | changeFuns : [], 23 | paths : [], 24 | begin : function(defaultPath) { 25 | // this should trigger the defaultPath if there's not a path in the URL 26 | // otherwise it should trigger the URL's path 27 | $(function() { 28 | var loadPath = getPath(); 29 | if (loadPath) { 30 | triggerOnPath(loadPath); 31 | } else { 32 | goPath(defaultPath); 33 | triggerOnPath(defaultPath); 34 | } 35 | }) 36 | }, 37 | go : function(path) { 38 | goPath(path); 39 | triggerOnPath(path); 40 | }, 41 | onChange : function (fun) { 42 | $.pathbinder.changeFuns.push(fun); 43 | } 44 | }; 45 | 46 | function pollPath(every) { 47 | function hashCheck() { 48 | _currentPath = getPath(); 49 | // path changed if _currentPath != _lastPath 50 | if (_lastPath != _currentPath) { 51 | setTimeout(function() { 52 | $(window).trigger('hashchange'); 53 | }, 1); 54 | } 55 | }; 56 | hashCheck(); 57 | _pathInterval = setInterval(hashCheck, every); 58 | $(window).bind('unload', function() { 59 | clearInterval(_pathInterval); 60 | }); 61 | } 62 | 63 | function triggerOnPath(path) { 64 | $.pathbinder.changeFuns.forEach(function(fun) {fun(path)}); 65 | var pathSpec, path_params, params = {}, param_name, param; 66 | for (var i=0; i < $.pathbinder.paths.length; i++) { 67 | pathSpec = $.pathbinder.paths[i]; 68 | $.log("pathSpec", pathSpec); 69 | if ((path_params = pathSpec.matcher.exec(path)) !== null) { 70 | $.log("path_params", path_params); 71 | path_params.shift(); 72 | for (var j=0; j < path_params.length; j++) { 73 | param_name = pathSpec.param_names[j]; 74 | param = decodeURIComponent(path_params[j]); 75 | if (param_name) { 76 | params[param_name] = param; 77 | } else { 78 | if (!params.splat) params.splat = []; 79 | params.splat.push(param); 80 | } 81 | }; 82 | // $.log("path trigger for "+path); 83 | pathSpec.callback(params); 84 | // return true; // removed this to allow for multi match 85 | } 86 | }; 87 | }; 88 | 89 | // bind the event 90 | $(function() { 91 | if ('onhashchange' in window) { 92 | // we have a native event 93 | } else { 94 | pollPath(10); 95 | } 96 | // setTimeout(hashChanged,50); 97 | $(window).bind('hashchange', hashChanged); 98 | }); 99 | 100 | function registerPath(pathSpec) { 101 | $.pathbinder.paths.push(pathSpec); 102 | }; 103 | 104 | function setPath(pathSpec, params) { 105 | var newPath = $.mustache(pathSpec.template, params); 106 | goPath(newPath); 107 | }; 108 | 109 | function goPath(newPath) { 110 | window.location = '#'+newPath; 111 | _lastPath = getPath(); 112 | }; 113 | 114 | function getPath() { 115 | var matches = window.location.toString().match(/^[^#]*(#.+)$/); 116 | return matches ? matches[1] : ''; 117 | }; 118 | 119 | function makePathSpec(path, callback) { 120 | var param_names = []; 121 | var template = ""; 122 | 123 | PATH_NAME_MATCHER.lastIndex = 0; 124 | 125 | while ((path_match = PATH_NAME_MATCHER.exec(path)) !== null) { 126 | param_names.push(path_match[1]); 127 | } 128 | 129 | return { 130 | param_names : param_names, 131 | matcher : new RegExp(path.replace( 132 | PATH_NAME_MATCHER, PATH_REPLACER).replace( 133 | SPLAT_MATCHER, SPLAT_REPLACER) + "$"), 134 | template : path.replace(PATH_NAME_MATCHER, function(a, b) { 135 | return '{{'+b+'}}'; 136 | }).replace(SPLAT_MATCHER, '{{splat}}'), 137 | callback : callback 138 | }; 139 | }; 140 | 141 | $.fn.pathbinder = function(name, path) { 142 | var self = $(this); 143 | var pathSpec = makePathSpec(path, function(params) { 144 | // $.log("path cb", name, path, self) 145 | self.trigger(name, [params]); 146 | }); 147 | self.bind(name, function(ev, params) { 148 | // set the path when triggered 149 | // $.log("set path", name, pathSpec) 150 | setPath(pathSpec, params); 151 | }); 152 | // trigger when the path matches 153 | registerPath(pathSpec); 154 | }; 155 | })(jQuery); 156 | -------------------------------------------------------------------------------- /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 : '', 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/_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{{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/_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/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 | //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 | //
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 ` Just type 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 ");
1052 | str += "
\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 = "" + link_text + "";
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: 
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 | (\S+?)>? // 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]*()(\S+?)>?[ \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 = "
";
635 |
636 | return result;
637 | }
638 |
639 |
640 | var _DoHeaders = function(text) {
641 |
642 | // Setext-style headers:
643 | // Header 1
644 | // ========
645 | //
646 | // Header 2
647 | // --------
648 | //
649 | text = text.replace(/^(.+)[ \t]*\n=+[ \t]*\n+/gm,
650 | function(wholeMatch,m1){return hashBlock("
" + _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("` 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 = "
";
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 " + codeblock + "\n 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 | // foo `bar` baz at the prompt.`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