Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

new launch page to make it easier to find/develop your apps

  • Loading branch information...
commit 7a9cbef5782bb280c0c8f487c83366389a33bf44 1 parent 7cf13ee
@mschoch mschoch authored
Showing with 12,084 additions and 4 deletions.
  1. BIN  assets/welcome.couch
  2. +1 −0  res/xml/phonegap.xml
  3. +19 −4 src/com/couchbase/callback/AndroidCouchbaseCallback.java
  4. +7 −0 welcome/.couchappignore
  5. +1 −0  welcome/.couchapprc
  6. +11 −0 welcome/.project
  7. +1 −0  welcome/README.md
  8. +53 −0 welcome/_attachments/index.html
  9. +80 −0 welcome/_attachments/style/main.css
  10. +1 −0  welcome/_id
  11. +4 −0 welcome/couchapp.json
  12. +3 −0  welcome/evently/couchapps/_init.js
  13. +6 −0 welcome/evently/couchapps/refresh/after.js
  14. +26 −0 welcome/evently/couchapps/refresh/async.js
  15. +11 −0 welcome/evently/items/_changes/data.js
  16. +18 −0 welcome/evently/items/_changes/mustache.html
  17. +5 −0 welcome/evently/items/_changes/query.json
  18. +14 −0 welcome/evently/profile/profileReady/mustache.html
  19. +12 −0 welcome/evently/profile/profileReady/selectors/form/submit.js
  20. +1 −0  welcome/language
  21. +239 −0 welcome/vendor/couchapp/_attachments/jquery.couch.app.js
  22. +90 −0 welcome/vendor/couchapp/_attachments/jquery.couch.app.util.js
  23. +1,097 −0 welcome/vendor/couchapp/_attachments/jquery.couch.js
  24. +399 −0 welcome/vendor/couchapp/_attachments/jquery.evently.js
  25. +6,240 −0 welcome/vendor/couchapp/_attachments/jquery.js
  26. +346 −0 welcome/vendor/couchapp/_attachments/jquery.mustache.js
  27. +174 −0 welcome/vendor/couchapp/_attachments/jquery.pathbinder.js
  28. +482 −0 welcome/vendor/couchapp/_attachments/json2.js
  29. +17 −0 welcome/vendor/couchapp/_attachments/loader.js
  30. +202 −0 welcome/vendor/couchapp/_attachments/sha1.js
  31. +22 −0 welcome/vendor/couchapp/evently/README.md
  32. +16 −0 welcome/vendor/couchapp/evently/account/_init.js
  33. +1 −0  welcome/vendor/couchapp/evently/account/adminParty/mustache.html
  34. +10 −0 welcome/vendor/couchapp/evently/account/doLogin.js
  35. +8 −0 welcome/vendor/couchapp/evently/account/doLogout.js
  36. +10 −0 welcome/vendor/couchapp/evently/account/doSignup.js
  37. +4 −0 welcome/vendor/couchapp/evently/account/loggedIn/after.js
  38. +7 −0 welcome/vendor/couchapp/evently/account/loggedIn/data.js
  39. +4 −0 welcome/vendor/couchapp/evently/account/loggedIn/mustache.html
  40. +3 −0  welcome/vendor/couchapp/evently/account/loggedIn/selectors.json
  41. +1 −0  welcome/vendor/couchapp/evently/account/loggedOut/mustache.html
  42. +4 −0 welcome/vendor/couchapp/evently/account/loggedOut/selectors.json
  43. +3 −0  welcome/vendor/couchapp/evently/account/loginForm/after.js
  44. +6 −0 welcome/vendor/couchapp/evently/account/loginForm/mustache.html
  45. +6 −0 welcome/vendor/couchapp/evently/account/loginForm/selectors/form/submit.js
  46. +3 −0  welcome/vendor/couchapp/evently/account/signupForm/after.js
  47. +6 −0 welcome/vendor/couchapp/evently/account/signupForm/mustache.html
  48. +6 −0 welcome/vendor/couchapp/evently/account/signupForm/selectors/form/submit.js
  49. +21 −0 welcome/vendor/couchapp/evently/profile/loggedIn.js
  50. +3 −0  welcome/vendor/couchapp/evently/profile/loggedOut/after.js
  51. +1 −0  welcome/vendor/couchapp/evently/profile/loggedOut/mustache.html
  52. +3 −0  welcome/vendor/couchapp/evently/profile/noProfile/data.js
  53. +11 −0 welcome/vendor/couchapp/evently/profile/noProfile/mustache.html
  54. +36 −0 welcome/vendor/couchapp/evently/profile/noProfile/selectors/form/submit.js
  55. +3 −0  welcome/vendor/couchapp/evently/profile/profileReady/after.js
  56. +3 −0  welcome/vendor/couchapp/evently/profile/profileReady/data.js
  57. +8 −0 welcome/vendor/couchapp/evently/profile/profileReady/mustache.html
  58. +39 −0 welcome/vendor/couchapp/lib/atom.js
  59. +25 −0 welcome/vendor/couchapp/lib/cache.js
  60. +20 −0 welcome/vendor/couchapp/lib/code.js
  61. +121 −0 welcome/vendor/couchapp/lib/docform.js
  62. +18 −0 welcome/vendor/couchapp/lib/linkup.js
  63. +13 −0 welcome/vendor/couchapp/lib/list.js
  64. +1,300 −0 welcome/vendor/couchapp/lib/markdown.js
  65. +261 −0 welcome/vendor/couchapp/lib/md5.js
  66. +339 −0 welcome/vendor/couchapp/lib/mustache.js
  67. +87 −0 welcome/vendor/couchapp/lib/path.js
  68. +8 −0 welcome/vendor/couchapp/lib/redirect.js
  69. +21 −0 welcome/vendor/couchapp/lib/utils.js
  70. +53 −0 welcome/vendor/couchapp/lib/validate.js
  71. +5 −0 welcome/vendor/couchapp/metadata.json
  72. +5 −0 welcome/views/recent-items/map.js
View
BIN  assets/welcome.couch
Binary file not shown
View
1  res/xml/phonegap.xml
@@ -1,5 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<phonegap>
<access origin="http://127.0.0.1*"/>
+ <access origin="http://0.0.0.0*"/>
<log level="DEBUG"/>
</phonegap>
View
23 src/com/couchbase/callback/AndroidCouchbaseCallback.java
@@ -35,10 +35,16 @@
{
public static final String TAG = AndroidCouchbaseCallback.class.getName();
public static final String COUCHBASE_DATABASE_SUFFIX = ".couch";
+ public static final String WELCOME_DATABASE = "welcome";
+ public static final String DEFAULT_ATTACHMENT = "/index.html";
private CouchbaseMobile couchbaseMobile;
private ServiceConnection couchbaseService;
private String couchappDatabase;
+ protected boolean installWelcomeDatabase() {
+ return true;
+ }
+
protected boolean showSplashScreen() {
return true;
}
@@ -56,13 +62,17 @@ protected String getDesignDocName() {
}
protected String getAttachmentPath() {
- return "/index.html";
+ return DEFAULT_ATTACHMENT;
}
protected String getCouchAppURL(String host, int port) {
return "http://" + host + ":" + port + "/" + getDatabaseName() + "/_design/" + getDesignDocName() + getAttachmentPath();
}
+ protected String getWelcomeAppURL(String host, int port) {
+ return "http://" + host + ":" + port + "/" + WELCOME_DATABASE + "/_design/" + WELCOME_DATABASE + DEFAULT_ATTACHMENT;
+ }
+
protected void couchbaseStarted(String host, int port) {
}
@@ -86,6 +96,10 @@ public void onCreate(Bundle savedInstanceState)
couchbaseMobile = new CouchbaseMobile(getBaseContext(), couchCallbackHandler);
try {
+ if(installWelcomeDatabase()) {
+ couchbaseMobile.installDatabase(WELCOME_DATABASE + COUCHBASE_DATABASE_SUFFIX);
+ }
+
// look for a .couch file in the assets folder
couchappDatabase = getDatabaseName();
if(couchappDatabase != null) {
@@ -101,7 +115,8 @@ public void onCreate(Bundle savedInstanceState)
}
/**
- * Look for the first .couch file that can be found in the assets folder
+ * Look for the first .couch file that is not named "welcome.couch"
+ * that can be found in the assets folder
*
* @return the name of the database (without the .couch extension)
* @throws IOException
@@ -117,7 +132,7 @@ public String findCouchApp() {
}
if(assets != null) {
for (String asset : assets) {
- if(asset.endsWith(COUCHBASE_DATABASE_SUFFIX)) {
+ if(!asset.startsWith(WELCOME_DATABASE) && asset.endsWith(COUCHBASE_DATABASE_SUFFIX)) {
result = asset.substring(0, asset.length() - COUCHBASE_DATABASE_SUFFIX.length());
break;
}
@@ -155,7 +170,7 @@ public void couchbaseStarted(String host, int port) {
AndroidCouchbaseCallback.this.loadUrl(getCouchAppURL(host, port));
}
else {
- AndroidCouchbaseCallback.this.loadUrl("file:///android_asset/www/couchapp.html");
+ AndroidCouchbaseCallback.this.loadUrl(getWelcomeAppURL(host, port));
}
AndroidCouchbaseCallback.this.couchbaseStarted(host, port);
View
7 welcome/.couchappignore
@@ -0,0 +1,7 @@
+[
+ // filenames matching these regexps will not be pushed to the database
+ // uncomment to activate; separate entries with ","
+ // ".*~$"
+ // ".*\\.swp$"
+ // ".*\\.bak$"
+]
View
1  welcome/.couchapprc
@@ -0,0 +1 @@
+{}
View
11 welcome/.project
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>callbackwelcome</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ </buildSpec>
+ <natures>
+ </natures>
+</projectDescription>
View
1  welcome/README.md
@@ -0,0 +1 @@
+## This couchapp is the source for the welcome page
View
53 welcome/_attachments/index.html
@@ -0,0 +1,53 @@
+<!DOCTYPE html>
+<html>
+ <head>
+ <title>Couchbase Mobile with Callback</title>
+ <link rel="stylesheet" href="style/main.css" type="text/css">
+ </head>
+ <body>
+ <h1>Welcome to Couchbase Mobile with Callback!</h1>
+
+ <p>These instructions are divided into two sections, the first describes the development mode. In this mode you can continually couchapp push your changes in for test. The second describes distribution mode where you package your application for distribution.</p>
+
+ <h3>Development</h3>
+ <ol>
+ <li>Forward Couchbase Mobile from your device/emulator to your development machine. <pre>adb forward tcp:8984 tcp:<span id="couchbasePort">PORT</span></pre></li>
+ <li>From within your couchapp project directory run: <pre>couchapp push http://localhost:8984/couchapp<pre></li>
+ <li>Refresh the list of CouchApps below and navigate to your applicaiton</li>
+ </ol>
+
+ <h5>Installed CouchApps (<a href="javascript:void(0)" onclick="refreshTable();">refresh</a>)</h5>
+ <table cellspacing=0>
+ <thead>
+ <tr>
+ <th>Database</th>
+ <th>Application</th>
+ </tr>
+ </thead>
+ <tbody id="couchappTableBody">
+ <tr id="noapps"><td colspan="2">No Couchapps Found</td></tr>
+ </tbody>
+ </table>
+
+ <h3>Distribution</h3>
+ <ol>
+ <li>Compact your database. <pre>curl -X POST -H "Content-Type: application/json" http://localhost:8984/couchapp/_compact</pre></li>
+ <li>From within the Android project, copy the Couchbase Mobile database to the assets folder. <pre>adb pull /mnt/sdcard/Android/data/com.couchbase.callback/db/couchapp.couch assets</pre></li>
+ <li>Repackage your application for distribution. <pre>ant debug</pre></li>
+ </ol>
+
+ </body>
+ <script src="vendor/couchapp/loader.js"></script>
+ <script type="text/javascript" charset="utf-8">
+
+ $('#couchbasePort').replace(window.location.port);
+
+ function refreshTable() {
+ $("#couchappTableBody").trigger('refresh');
+ }
+
+ $.couch.app(function(app) {
+ $("#couchappTableBody").evently("couchapps", app);
+ });
+ </script>
+</html>
View
80 welcome/_attachments/style/main.css
@@ -0,0 +1,80 @@
+/* add styles here */
+
+body {
+ font:1em Helvetica, sans-serif;
+ padding:4px;
+}
+
+h1 {
+ margin-top:0;
+}
+
+#account {
+ float:right;
+}
+
+#profile {
+ border:4px solid #edd;
+ background:#fee;
+ padding:8px;
+ margin-bottom:8px;
+}
+
+#items {
+ border:4px solid #dde;
+ background:#eef;
+ padding:8px;
+ width:60%;
+ float:left;
+}
+
+#sidebar {
+ border:4px solid #dfd;
+ padding:8px;
+ float:right;
+ width:30%;
+}
+
+#items li {
+ border:4px solid #f5f5ff;
+ background:#fff;
+ padding:8px;
+ margin:4px 0;
+}
+
+form {
+ padding:4px;
+ margin:6px;
+ background-color:#ddd;
+}
+
+div.avatar {
+ padding:2px;
+ padding-bottom:0;
+ margin-right:4px;
+ float:left;
+ font-size:0.78em;
+ width : 60px;
+ height : 60px;
+ text-align: center;
+}
+
+div.avatar .name {
+ padding-top:2px;
+}
+
+div.avatar img {
+ margin:0 auto;
+ padding:0;
+ width : 40px;
+ height : 40px;
+}
+
+#items ul {
+ list-style: none;
+}
+
+table, th, td
+{
+border: 1px solid black;
+}
View
1  welcome/_id
@@ -0,0 +1 @@
+_design/welcome
View
4 welcome/couchapp.json
@@ -0,0 +1,4 @@
+{
+ "name": "Name of your CouchApp",
+ "description": "CouchApp"
+}
View
3  welcome/evently/couchapps/_init.js
@@ -0,0 +1,3 @@
+function() {
+ $(this).trigger('refresh');
+}
View
6 welcome/evently/couchapps/refresh/after.js
@@ -0,0 +1,6 @@
+function(e, r) {
+ if(e.db != 'welcome') {
+ $('#noapps').remove();
+ $(this).append('<tr><td>' + e.db + '</td><td><a href="' + e.appPath + '">' + e.appName + '</a></td></tr>');
+ }
+};
View
26 welcome/evently/couchapps/refresh/async.js
@@ -0,0 +1,26 @@
+function(cb) {
+
+ $(this).empty();
+ $(this).append('<tr id="noapps"><td colspan="2">No Couchapps Found</td></tr>');
+
+ $.couch.allDbs({
+ success : function(dbs) {
+
+ dbs.forEach( function(db) {
+
+ $.couch.db(db).allApps({
+ eachApp: function(appName, appPath, ddoc) {
+ var app = new Object;
+ app.db = db;
+ app.appName = appName;
+ app.appPath = appPath;
+ app.ddoc = ddoc;
+ cb(app);
+ }
+ });
+
+ });
+ }
+ });
+
+}
View
11 welcome/evently/items/_changes/data.js
@@ -0,0 +1,11 @@
+function(data) {
+ // $.log(data)
+ var p;
+ return {
+ items : data.rows.map(function(r) {
+ p = (r.value && r.value.profile) || {};
+ p.message = r.value && r.value.message;
+ return p;
+ })
+ }
+};
View
18 welcome/evently/items/_changes/mustache.html
@@ -0,0 +1,18 @@
+<p>Customize this format here: <tt>ddoc.evently.items._changes.mustache</tt></p>
+<h3>Recent Messages</h3>
+<ul>
+ {{#items}}
+ <li>
+ <div class="avatar">
+ {{#gravatar_url}}<img src="{{gravatar_url}}" alt="{{name}}"/>{{/gravatar_url}}
+ <div class="name">
+ {{nickname}}
+ </div>
+ </div>
+ <p>{{message}}</p>
+ <div style="clear:left;"></div>
+ </li>
+ {{/items}}
+</ul>
+<p><em>Protip:</em> If you setup continuous replication between this database and a remote one, this list will reflect remote changes in near real-time.</p>
+<p>This would be a good place to add pagination.</p>
View
5 welcome/evently/items/_changes/query.json
@@ -0,0 +1,5 @@
+{
+ "view" : "recent-items",
+ "descending" : "true",
+ "limit" : 50
+}
View
14 welcome/evently/profile/profileReady/mustache.html
@@ -0,0 +1,14 @@
+<p>Most applications will customize this template (<tt>ddoc.evently.profile.profileReady.mustache</tt>) for user input.</p>
+
+<div class="avatar">
+ {{#gravatar_url}}<img src="{{gravatar_url}}"/>{{/gravatar_url}}
+ <div class="name">
+ {{name}}
+ </div>
+</div>
+
+<form>
+ <label>New message from {{nickname}}: <input type="text" name="message" size=60 value=""></label>
+</form>
+
+<div style="clear:left;"></div>
View
12 welcome/evently/profile/profileReady/selectors/form/submit.js
@@ -0,0 +1,12 @@
+function() {
+ var form = $(this);
+ var fdoc = form.serializeObject();
+ fdoc.created_at = new Date();
+ fdoc.profile = $$("#profile").profile;
+ $$(this).app.db.saveDoc(fdoc, {
+ success : function() {
+ form[0].reset();
+ }
+ });
+ return false;
+};
View
1  welcome/language
@@ -0,0 +1 @@
+javascript
View
239 welcome/vendor/couchapp/_attachments/jquery.couch.app.js
@@ -0,0 +1,239 @@
+// Licensed under the Apache License, Version 2.0 (the "License"); you may not
+// use this file except in compliance with the License. You may obtain a copy
+// of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations under
+// the License.
+
+// Usage: The passed in function is called when the page is ready.
+// CouchApp passes in the app object, which takes care of linking to
+// the proper database, and provides access to the CouchApp helpers.
+// $.couch.app(function(app) {
+// app.db.view(...)
+// ...
+// });
+
+(function($) {
+
+ function Design(db, name, code) {
+ this.doc_id = "_design/"+name;
+ if (code) {
+ this.code_path = this.doc_id + "/" + code;
+ } else {
+ this.code_path = this.doc_id;
+ }
+ this.view = function(view, opts) {
+ if (view.indexOf('/') === -1) {
+ db.view(name+'/'+view, opts);
+ } else {
+ db.view(view, opts);
+ }
+ };
+ this.list = function(list, view, opts) {
+ db.list(name+'/'+list, view, opts);
+ };
+ }
+
+ function docForm() { alert("docForm has been moved to vendor/couchapp/lib/docForm.js, use app.require to load") };
+
+ function resolveModule(path, names, parents, current) {
+ parents = parents || [];
+ if (names.length === 0) {
+ if (typeof current != "string") {
+ throw ["error","invalid_require_path",
+ 'Must require a JavaScript string, not: '+(typeof current)];
+ }
+ return [current, parents];
+ }
+ var n = names.shift();
+ if (n == '..') {
+ parents.pop();
+ var pp = parents.pop();
+ if (!pp) {
+ throw ["error", "invalid_require_path", path];
+ }
+ return resolveModule(path, names, parents, pp);
+ } else if (n == '.') {
+ var p = parents.pop();
+ if (!p) {
+ throw ["error", "invalid_require_path", path];
+ }
+ return resolveModule(path, names, parents, p);
+ } else {
+ parents = [];
+ }
+ if (!current[n]) {
+ throw ["error", "invalid_require_path", path];
+ }
+ parents.push(current);
+ return resolveModule(path, names, parents, current[n]);
+ }
+
+ function makeRequire(ddoc) {
+ var moduleCache = [];
+ function getCachedModule(name, parents) {
+ var key, i, len = moduleCache.length;
+ for (i=0;i<len;++i) {
+ key = moduleCache[i].key;
+ if (key[0] === name && key[1] === parents) {
+ return moduleCache[i].module;
+ }
+ }
+ return null;
+ }
+ function setCachedModule(name, parents, module) {
+ moduleCache.push({ key: [name, parents], module: module });
+ }
+ var require = function (name, parents) {
+ var cachedModule = getCachedModule(name, parents);
+ if (cachedModule !== null) {
+ return cachedModule;
+ }
+ var exports = {};
+ var resolved = resolveModule(name, name.split('/'), parents, ddoc);
+ var source = resolved[0];
+ parents = resolved[1];
+ var s = "var func = function (exports, require) { " + source + " };";
+ try {
+ eval(s);
+ func.apply(ddoc, [exports, function(name) {return require(name, parents)}]);
+ } catch(e) {
+ throw ["error","compilation_error","Module require('"+name+"') raised error "+e.toSource()];
+ }
+ setCachedModule(name, parents, exports);
+ return exports;
+ }
+ return require;
+ };
+
+ function mockReq() {
+ var p = document.location.pathname.split('/'),
+ qs = document.location.search.replace(/^\?/,'').split('&'),
+ q = {};
+ qs.forEach(function(param) {
+ var ps = param.split('='),
+ k = decodeURIComponent(ps[0]),
+ v = decodeURIComponent(ps[1]);
+ if (["startkey", "endkey", "key"].indexOf(k) != -1) {
+ q[k] = JSON.parse(v);
+ } else {
+ q[k] = v;
+ }
+ });
+ p.shift();
+ return {
+ path : p,
+ query : q
+ };
+ };
+
+ $.couch.app = $.couch.app || function(appFun, opts) {
+ opts = opts || {};
+ var urlPrefix = (opts.urlPrefix || ""),
+ index = urlPrefix.split('/').length,
+ fragments = unescape(document.location.href).split('/'),
+ dbname = opts.db || fragments[index + 2],
+ dname = opts.design || fragments[index + 4];
+ $.couch.urlPrefix = urlPrefix;
+ var db = $.couch.db(dbname),
+ design = new Design(db, dname, opts.load_path);
+ var appExports = $.extend({
+ db : db,
+ design : design,
+ view : design.view,
+ list : design.list,
+ docForm : docForm, // deprecated
+ req : mockReq()
+ }, $.couch.app.app);
+ function handleDDoc(ddoc) {
+ if (ddoc) {
+ appExports.ddoc = ddoc;
+ appExports.require = makeRequire(ddoc);
+ }
+ appFun.apply(appExports, [appExports]);
+ }
+ if (opts.ddoc) {
+ // allow the ddoc to be embedded in the html
+ // to avoid a second http request
+ $.couch.app.ddocs[design.doc_id] = opts.ddoc;
+ }
+ if ($.couch.app.ddocs[design.doc_id]) {
+ $(function() {handleDDoc($.couch.app.ddocs[design.doc_id])});
+ } else {
+ // only open 1 connection for this ddoc
+ if ($.couch.app.ddoc_handlers[design.doc_id]) {
+ // we are already fetching, just wait
+ $.couch.app.ddoc_handlers[design.doc_id].push(handleDDoc);
+ } else {
+ $.couch.app.ddoc_handlers[design.doc_id] = [handleDDoc];
+ // use getDbProperty to bypass %2F encoding on _show/app
+ db.getDbProperty(design.code_path, {
+ success : function(doc) {
+ $.couch.app.ddocs[design.doc_id] = doc;
+ $.couch.app.ddoc_handlers[design.doc_id].forEach(function(h) {
+ $(function() {h(doc)});
+ });
+ $.couch.app.ddoc_handlers[design.doc_id] = null;
+ },
+ error : function() {
+ $.couch.app.ddoc_handlers[design.doc_id].forEach(function(h) {
+ $(function() {h()});
+ });
+ $.couch.app.ddoc_handlers[design.doc_id] = null;
+ }
+ });
+ }
+ }
+ };
+ $.couch.app.ddocs = {};
+ $.couch.app.ddoc_handlers = {};
+ // legacy support. $.CouchApp is deprecated, please use $.couch.app
+ $.CouchApp = $.couch.app;
+})(jQuery);
+
+// JavaScript 1.6 compatibility functions that are missing from IE7/IE8
+
+if (!Array.prototype.forEach)
+{
+ Array.prototype.forEach = function(fun /*, thisp*/)
+ {
+ var len = this.length >>> 0;
+ if (typeof fun != "function")
+ throw new TypeError();
+
+ var thisp = arguments[1];
+ for (var i = 0; i < len; i++)
+ {
+ if (i in this)
+ fun.call(thisp, this[i], i, this);
+ }
+ };
+}
+
+if (!Array.prototype.indexOf)
+{
+ Array.prototype.indexOf = function(elt)
+ {
+ var len = this.length >>> 0;
+
+ var from = Number(arguments[1]) || 0;
+ from = (from < 0)
+ ? Math.ceil(from)
+ : Math.floor(from);
+ if (from < 0)
+ from += len;
+
+ for (; from < len; from++)
+ {
+ if (from in this &&
+ this[from] === elt)
+ return from;
+ }
+ return -1;
+ };
+}
View
90 welcome/vendor/couchapp/_attachments/jquery.couch.app.util.js
@@ -0,0 +1,90 @@
+$.log = function(m) {
+ if (window && window.console && window.console.log) {
+ window.console.log(arguments.length == 1 ? m : arguments);
+ }
+};
+
+// http://stackoverflow.com/questions/1184624/serialize-form-to-json-with-jquery/1186309#1186309
+$.fn.serializeObject = function() {
+ var o = {};
+ var a = this.serializeArray();
+ $.each(a, function() {
+ if (o[this.name]) {
+ if (!o[this.name].push) {
+ o[this.name] = [o[this.name]];
+ }
+ o[this.name].push(this.value || '');
+ } else {
+ o[this.name] = this.value || '';
+ }
+ });
+ return o;
+};
+
+// todo remove this crap
+function escapeHTML(st) {
+ return(
+ st && st.replace(/&/g,'&amp;').
+ replace(/>/g,'&gt;').
+ replace(/</g,'&lt;').
+ replace(/"/g,'&quot;')
+ );
+};
+
+function safeHTML(st, len) {
+ return st ? escapeHTML(st.substring(0,len)) : '';
+}
+
+// todo this should take a replacement template
+$.linkify = function(body) {
+ return body.replace(/((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi,function(a) {
+ return '<a target="_blank" href="'+a+'">'+a+'</a>';
+ }).replace(/\@([\w\-]+)/g,function(user,name) {
+ return '<a href="#/mentions/'+encodeURIComponent(name.toLowerCase())+'">'+user+'</a>';
+ }).replace(/\#([\w\-\.]+)/g,function(word,tag) {
+ return '<a href="#/tags/'+encodeURIComponent(tag.toLowerCase())+'">'+word+'</a>';
+ });
+};
+
+$.fn.prettyDate = function() {
+ $(this).each(function() {
+ var string, title = $(this).attr("title");
+ if (title) {
+ string = $.prettyDate(title);
+ } else {
+ string = $.prettyDate($(this).text());
+ }
+ $(this).text(string);
+ });
+};
+
+$.prettyDate = function(time){
+
+ var date = new Date(time.replace(/-/g,"/").replace("T", " ").replace("Z", " +0000").replace(/(\d*\:\d*:\d*)\.\d*/g,"$1")),
+ diff = (((new Date()).getTime() - date.getTime()) / 1000),
+ day_diff = Math.floor(diff / 86400);
+
+ if (isNaN(day_diff)) return time;
+
+ return day_diff < 1 && (
+ diff < 60 && "just now" ||
+ diff < 120 && "1 minute ago" ||
+ diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
+ diff < 7200 && "1 hour ago" ||
+ diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
+ day_diff == 1 && "yesterday" ||
+ day_diff < 21 && day_diff + " days ago" ||
+ day_diff < 45 && Math.ceil( day_diff / 7 ) + " weeks ago" ||
+ time;
+ // day_diff < 730 && Math.ceil( day_diff / 31 ) + " months ago" ||
+ // Math.ceil( day_diff / 365 ) + " years ago";
+};
+
+$.argsToArray = function(args) {
+ if (!args.callee) return args;
+ var array = [];
+ for (var i=0; i < args.length; i++) {
+ array.push(args[i]);
+ };
+ return array;
+}
View
1,097 welcome/vendor/couchapp/_attachments/jquery.couch.js
@@ -0,0 +1,1097 @@
+// Licensed under the Apache License, Version 2.0 (the "License"); you may not
+// use this file except in compliance with the License. You may obtain a copy of
+// the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations under
+// the License.
+
+/**
+ * @namespace
+ * $.couch is used to communicate with a CouchDB server, the server methods can
+ * be called directly without creating an instance. Typically all methods are
+ * passed an <code>options</code> object which defines a success callback which
+ * is called with the data returned from the http request to CouchDB, you can
+ * find the other settings that can be used in the <code>options</code> object
+ * from <a href="http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings">
+ * jQuery.ajax settings</a>
+ * <pre><code>$.couch.activeTasks({
+ * success: function (data) {
+ * console.log(data);
+ * }
+ * });</code></pre>
+ * Outputs (for example):
+ * <pre><code>[
+ * {
+ * "pid" : "<0.11599.0>",
+ * "status" : "Copied 0 of 18369 changes (0%)",
+ * "task" : "recipes",
+ * "type" : "Database Compaction"
+ * }
+ *]</code></pre>
+ */
+(function($) {
+
+ $.couch = $.couch || {};
+ /** @lends $.couch */
+
+ /**
+ * @private
+ */
+ function encodeDocId(docID) {
+ var parts = docID.split("/");
+ if (parts[0] == "_design") {
+ parts.shift();
+ return "_design/" + encodeURIComponent(parts.join('/'));
+ }
+ return encodeURIComponent(docID);
+ }
+
+ /**
+ * @private
+ */
+
+ var uuidCache = [];
+
+ $.extend($.couch, {
+ urlPrefix: '',
+
+ /**
+ * You can obtain a list of active tasks by using the /_active_tasks URL.
+ * The result is a JSON array of the currently running tasks, with each task
+ * being described with a single object.
+ * @see <a href="http://techzone.couchbase.com/sites/default/files/uploads/
+ * all/documentation/couchbase-api-misc.html#couchbase-api-misc_active-task
+ * s_get">docs for /_active_tasks</a>
+ * @param {ajaxSettings} options <a href="http://api.jquery.com/jQuery.ajax
+ * /#jQuery-ajax-settings">jQuery ajax settings</a>
+ */
+ activeTasks: function(options) {
+ ajax(
+ {url: this.urlPrefix + "/_active_tasks"},
+ options,
+ "Active task status could not be retrieved"
+ );
+ },
+
+ /**
+ * Returns a list of all the databases in the CouchDB instance
+ * @see <a href="http://techzone.couchbase.com/sites/default/files/uploads/
+ * all/documentation/couchbase-api-misc.html#couchbase-api-misc_active-task
+ * s_get">docs for /_all_dbs</a>
+ * @param {ajaxSettings} options <a href="http://api.jquery.com/jQuery.ajax
+ * /#jQuery-ajax-settings">jQuery ajax settings</a>
+ */
+ allDbs: function(options) {
+ ajax(
+ {url: this.urlPrefix + "/_all_dbs"},
+ options,
+ "An error occurred retrieving the list of all databases"
+ );
+ },
+
+ /**
+ * View and edit the CouchDB configuration, called with just the options
+ * parameter the entire config is returned, you can be more specific by
+ * passing the section and option parameters, if you specify a value that
+ * value will be stored in the configuration.
+ * @see <a href="http://techzone.couchbase.com/sites/default/files/uploads/
+ * all/documentation/couchbase-api-config.html#couchbase-api-config_config
+ * -section-key_put">docs for /_config</a>
+ * @param {ajaxSettings} options
+ * <a href="http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings">
+ * jQuery ajax settings</a>
+ * @param {String} [section] the section of the config
+ * @param {String} [option] the particular config option
+ * @param {String} [value] value to be set
+ */
+ config: function(options, section, option, value) {
+ var req = {url: this.urlPrefix + "/_config/"};
+ if (section) {
+ req.url += encodeURIComponent(section) + "/";
+ if (option) {
+ req.url += encodeURIComponent(option);
+ }
+ }
+ if (value === null) {
+ req.type = "DELETE";
+ } else if (value !== undefined) {
+ req.type = "PUT";
+ req.data = toJSON(value);
+ req.contentType = "application/json";
+ req.processData = false
+ }
+
+ ajax(req, options,
+ "An error occurred retrieving/updating the server configuration"
+ );
+ },
+
+ /**
+ * Returns the session information for the currently logged in user.
+ * @param {ajaxSettings} options
+ * <a href="http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings">
+ * jQuery ajax settings</a>
+ */
+ session: function(options) {
+ options = options || {};
+ $.ajax({
+ type: "GET", url: this.urlPrefix + "/_session",
+ beforeSend: function(xhr) {
+ xhr.setRequestHeader('Accept', 'application/json');
+ },
+ complete: function(req) {
+ var resp = $.parseJSON(req.responseText);
+ if (req.status == 200) {
+ if (options.success) options.success(resp);
+ } else if (options.error) {
+ options.error(req.status, resp.error, resp.reason);
+ } else {
+ alert("An error occurred getting session info: " + resp.reason);
+ }
+ }
+ });
+ },
+
+ /**
+ * @private
+ */
+ userDb : function(callback) {
+ $.couch.session({
+ success : function(resp) {
+ var userDb = $.couch.db(resp.info.authentication_db);
+ callback(userDb);
+ }
+ });
+ },
+
+ /**
+ * Create a new user on the CouchDB server, <code>user_doc</code> is an
+ * object with a <code>name</code> field and other information you want
+ * to store relating to that user, for example
+ * <code>{"name": "daleharvey"}</code>
+ * @param {Object} user_doc Users details
+ * @param {String} password Users password
+ * @param {ajaxSettings} options
+ * <a href="http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings">
+ * jQuery ajax settings</a>
+ */
+ signup: function(user_doc, password, options) {
+ options = options || {};
+ // prepare user doc based on name and password
+ user_doc = this.prepareUserDoc(user_doc, password);
+ $.couch.userDb(function(db) {
+ db.saveDoc(user_doc, options);
+ });
+ },
+
+ /**
+ * Populates a user doc with a new password.
+ * @param {Object} user_doc User details
+ * @param {String} new_password New Password
+ */
+ prepareUserDoc: function(user_doc, new_password) {
+ if (typeof hex_sha1 == "undefined") {
+ alert("creating a user doc requires sha1.js to be loaded in the page");
+ return;
+ }
+ var user_prefix = "org.couchdb.user:";
+ user_doc._id = user_doc._id || user_prefix + user_doc.name;
+ if (new_password) {
+ // handle the password crypto
+ user_doc.salt = $.couch.newUUID();
+ user_doc.password_sha = hex_sha1(new_password + user_doc.salt);
+ }
+ user_doc.type = "user";
+ if (!user_doc.roles) {
+ user_doc.roles = [];
+ }
+ return user_doc;
+ },
+
+ /**
+ * Authenticate against CouchDB, the <code>options</code> parameter is
+ *expected to have <code>name</code> and <code>password</code> fields.
+ * @param {ajaxSettings} options
+ * <a href="http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings">
+ * jQuery ajax settings</a>
+ */
+ login: function(options) {
+ options = options || {};
+ $.ajax({
+ type: "POST", url: this.urlPrefix + "/_session", dataType: "json",
+ data: {name: options.name, password: options.password},
+ beforeSend: function(xhr) {
+ xhr.setRequestHeader('Accept', 'application/json');
+ },
+ complete: function(req) {
+ var resp = $.parseJSON(req.responseText);
+ if (req.status == 200) {
+ if (options.success) options.success(resp);
+ } else if (options.error) {
+ options.error(req.status, resp.error, resp.reason);
+ } else {
+ alert("An error occurred logging in: " + resp.reason);
+ }
+ }
+ });
+ },
+
+
+ /**
+ * Delete your current CouchDB user session
+ * @param {ajaxSettings} options
+ * <a href="http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings">
+ * jQuery ajax settings</a>
+ */
+ logout: function(options) {
+ options = options || {};
+ $.ajax({
+ type: "DELETE", url: this.urlPrefix + "/_session", dataType: "json",
+ username : "_", password : "_",
+ beforeSend: function(xhr) {
+ xhr.setRequestHeader('Accept', 'application/json');
+ },
+ complete: function(req) {
+ var resp = $.parseJSON(req.responseText);
+ if (req.status == 200) {
+ if (options.success) options.success(resp);
+ } else if (options.error) {
+ options.error(req.status, resp.error, resp.reason);
+ } else {
+ alert("An error occurred logging out: " + resp.reason);
+ }
+ }
+ });
+ },
+
+ /**
+ * @namespace
+ * $.couch.db is used to communicate with a specific CouchDB database
+ * <pre><code>var $db = $.couch.db("mydatabase");
+ *$db.allApps({
+ * success: function (data) {
+ * ... process data ...
+ * }
+ *});
+ * </code></pre>
+ */
+ db: function(name, db_opts) {
+ db_opts = db_opts || {};
+ var rawDocs = {};
+ function maybeApplyVersion(doc) {
+ if (doc._id && doc._rev && rawDocs[doc._id] &&
+ rawDocs[doc._id].rev == doc._rev) {
+ // todo: can we use commonjs require here?
+ if (typeof Base64 == "undefined") {
+ alert("please include /_utils/script/base64.js in the page for " +
+ "base64 support");
+ return false;
+ } else {
+ doc._attachments = doc._attachments || {};
+ doc._attachments["rev-"+doc._rev.split("-")[0]] = {
+ content_type :"application/json",
+ data : Base64.encode(rawDocs[doc._id].raw)
+ };
+ return true;
+ }
+ }
+ };
+ return /** @lends $.couch.db */{
+ name: name,
+ uri: this.urlPrefix + "/" + encodeURIComponent(name) + "/",
+
+ /**
+ * Request compaction of the specified database.
+ * @see <a href="http://techzone.couchbase.com/sites/default/files/
+ * uploads/all/documentation/couchbase-api-db.html#couchbase-api-db_
+ * db-compact_post">docs for /db/_compact</a>
+ * @param {ajaxSettings} options
+ * <a href="http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings">
+ * jQuery ajax settings</a>
+ */
+ compact: function(options) {
+ $.extend(options, {successStatus: 202});
+ ajax({
+ type: "POST", url: this.uri + "_compact",
+ data: "", processData: false
+ },
+ options,
+ "The database could not be compacted"
+ );
+ },
+
+ /**
+ * Cleans up the cached view output on disk for a given view.
+ * @see <a href="http://techzone.couchbase.com/sites/default/files/
+ * uploads/all/documentation/couchbase-api-db.html#couchbase-api-db
+ * _db-view-cleanup_post">docs for /db/_compact</a>
+ * @param {ajaxSettings} options <a href="http://api.jquery.com/
+ * jQuery.ajax/#jQuery-ajax-settings">jQuery ajax settings</a>
+ */
+ viewCleanup: function(options) {
+ $.extend(options, {successStatus: 202});
+ ajax({
+ type: "POST", url: this.uri + "_view_cleanup",
+ data: "", processData: false
+ },
+ options,
+ "The views could not be cleaned up"
+ );
+ },
+
+ /**
+ * Compacts the view indexes associated with the specified design
+ * document. You can use this in place of the full database compaction
+ * if you know a specific set of view indexes have been affected by a
+ * recent database change.
+ * @see <a href="http://techzone.couchbase.com/sites/default/files/upl
+ * oads/all/documentation/couchbase-api-db.html#couchbase-api-db_db-
+ * compact-design-doc_post">docs for /db/_compact/design-doc</a>
+ * @param {String} groupname Name of design-doc to compact
+ * @param {ajaxSettings} options <a href="http://api.jquery.com/
+ * jQuery.ajax/#jQuery-ajax-settings">jQuery ajax settings</a>
+ */
+ compactView: function(groupname, options) {
+ $.extend(options, {successStatus: 202});
+ ajax({
+ type: "POST", url: this.uri + "_compact/" + groupname,
+ data: "", processData: false
+ },
+ options,
+ "The view could not be compacted"
+ );
+ },
+
+ /**
+ * Create a new database
+ * @see <a href="http://techzone.couchbase.com/sites/default/files/
+ * uploads/all/documentation/couchbase-api-db.html#couchbase-api-db_
+ * db_put">docs for PUT /db/</a>
+ * @param {ajaxSettings} options <a href="http://api.jquery.com/
+ * jQuery.ajax/#jQuery-ajax-settings">jQuery ajax settings</a>
+ */
+ create: function(options) {
+ $.extend(options, {successStatus: 201});
+ ajax({
+ type: "PUT", url: this.uri, contentType: "application/json",
+ data: "", processData: false
+ },
+ options,
+ "The database could not be created"
+ );
+ },
+
+ /**
+ * Deletes the specified database, and all the documents and
+ * attachments contained within it.
+ * @see <a href="http://techzone.couchbase.com/sites/default/files/
+ * uploads/all/documentation/couchbase-api-db.html#couchbase-api-db_
+ * db_delete">docs for DELETE /db/</a>
+ * @param {ajaxSettings} options <a href="http://api.jquery.com/
+ * jQuery.ajax/#jQuery-ajax-settings">jQuery ajax settings</a>
+ */
+ drop: function(options) {
+ ajax(
+ {type: "DELETE", url: this.uri},
+ options,
+ "The database could not be deleted"
+ );
+ },
+
+ /**
+ * Gets information about the specified database.
+ * @see <a href="http://techzone.couchbase.com/sites/default/files/
+ * uploads/all/documentation/couchbase-api-db.html#couchbase-api-db
+ * _db_get">docs for GET /db/</a>
+ * @param {ajaxSettings} options <a href="http://api.jquery.com/
+ * jQuery.ajax/#jQuery-ajax-settings">jQuery ajax settings</a>
+ */
+ info: function(options) {
+ ajax(
+ {url: this.uri},
+ options,
+ "Database information could not be retrieved"
+ );
+ },
+
+ /**
+ * @namespace
+ * $.couch.db.changes provides an API for subscribing to the changes
+ * feed
+ * <pre><code>var $changes = $.couch.db("mydatabase").changes();
+ *$changes.onChange = function (data) {
+ * ... process data ...
+ * }
+ * $changes.stop();
+ * </code></pre>
+ */
+ changes: function(since, options) {
+
+ options = options || {};
+ // set up the promise object within a closure for this handler
+ var timeout = 100, db = this, active = true,
+ listeners = [],
+ promise = /** @lends $.couch.db.changes */ {
+ /**
+ * Add a listener callback
+ * @see <a href="http://techzone.couchbase.com/sites/default/
+ * files/uploads/all/documentation/couchbase-api-db.html#couch
+ * base-api-db_db-changes_get">docs for /db/_changes</a>
+ * @param {Function} fun Callback function to run when
+ * notified of changes.
+ */
+ onChange : function(fun) {
+ listeners.push(fun);
+ },
+ /**
+ * Stop subscribing to the changes feed
+ */
+ stop : function() {
+ active = false;
+ }
+ };
+ // call each listener when there is a change
+ function triggerListeners(resp) {
+ $.each(listeners, function() {
+ this(resp);
+ });
+ };
+ // when there is a change, call any listeners, then check for
+ // another change
+ options.success = function(resp) {
+ timeout = 100;
+ if (active) {
+ since = resp.last_seq;
+ triggerListeners(resp);
+ getChangesSince();
+ };
+ };
+ options.error = function() {
+ if (active) {
+ setTimeout(getChangesSince, timeout);
+ timeout = timeout * 2;
+ }
+ };
+ // actually make the changes request
+ function getChangesSince() {
+ var opts = $.extend({heartbeat : 10 * 1000}, options, {
+ feed : "longpoll",
+ since : since
+ });
+ ajax(
+ {url: db.uri + "_changes"+encodeOptions(opts)},
+ options,
+ "Error connecting to "+db.uri+"/_changes."
+ );
+ }
+ // start the first request
+ if (since) {
+ getChangesSince();
+ } else {
+ db.info({
+ success : function(info) {
+ since = info.update_seq;
+ getChangesSince();
+ }
+ });
+ }
+ return promise;
+ },
+
+ /**
+ * Fetch all the docs in this db, you can specify an array of keys to
+ * fetch by passing the <code>keys</code> field in the
+ * <code>options</code>
+ * parameter.
+ * @see <a href="http://techzone.couchbase.com/sites/default/files/
+ * uploads/all/documentation/couchbase-api-db.html#couchbase-api-db_
+ * db-all-docs_get">docs for /db/all_docs/</a>
+ * @param {ajaxSettings} options <a href="http://api.jquery.com/
+ * jQuery.ajax/#jQuery-ajax-settings">jQuery ajax settings</a>
+ */
+ allDocs: function(options) {
+ var type = "GET";
+ var data = null;
+ if (options["keys"]) {
+ type = "POST";
+ var keys = options["keys"];
+ delete options["keys"];
+ data = toJSON({ "keys": keys });
+ }
+ ajax({
+ type: type,
+ data: data,
+ url: this.uri + "_all_docs" + encodeOptions(options)
+ },
+ options,
+ "An error occurred retrieving a list of all documents"
+ );
+ },
+
+ /**
+ * Fetch all the design docs in this db
+ * @param {ajaxSettings} options <a href="http://api.jquery.com/
+ * jQuery.ajax/#jQuery-ajax-settings">jQuery ajax settings</a>
+ */
+ allDesignDocs: function(options) {
+ this.allDocs($.extend(
+ {startkey:"_design", endkey:"_design0"}, options));
+ },
+
+ /**
+ * Fetch all the design docs with an index.html, <code>options</code>
+ * parameter expects an <code>eachApp</code> field which is a callback
+ * called on each app found.
+ * @param {ajaxSettings} options <a href="http://api.jquery.com/
+ * jQuery.ajax/#jQuery-ajax-settings">jQuery ajax settings</a>
+ */
+ allApps: function(options) {
+ options = options || {};
+ var self = this;
+ if (options.eachApp) {
+ this.allDesignDocs({
+ success: function(resp) {
+ $.each(resp.rows, function() {
+ self.openDoc(this.id, {
+ success: function(ddoc) {
+ var index, appPath, appName = ddoc._id.split('/');
+ appName.shift();
+ appName = appName.join('/');
+ index = ddoc.couchapp && ddoc.couchapp.index;
+ if (index) {
+ appPath = ['', name, ddoc._id, index].join('/');
+ } else if (ddoc._attachments &&
+ ddoc._attachments["index.html"]) {
+ appPath = ['', name, ddoc._id, "index.html"].join('/');
+ }
+ if (appPath) options.eachApp(appName, appPath, ddoc);
+ }
+ });
+ });
+ }
+ });
+ } else {
+ alert("Please provide an eachApp function for allApps()");
+ }
+ },
+
+ /**
+ * Returns the specified doc from the specified db.
+ * @see <a href="http://techzone.couchbase.com/sites/default/files/
+ * uploads/all/documentation/couchbase-api-dbdoc.html#couchbase-api-
+ * dbdoc_db-doc_get">docs for GET /db/doc</a>
+ * @param {String} docId id of document to fetch
+ * @param {ajaxSettings} options <a href="http://api.jquery.com/
+ * jQuery.ajax/#jQuery-ajax-settings">jQuery ajax settings</a>
+ * @param {ajaxSettings} ajaxOptions <a href="http://api.jquery.com/
+ * jQuery.ajax/#jQuery-ajax-settings">jQuery ajax settings</a>
+ */
+ openDoc: function(docId, options, ajaxOptions) {
+ options = options || {};
+ if (db_opts.attachPrevRev || options.attachPrevRev) {
+ $.extend(options, {
+ beforeSuccess : function(req, doc) {
+ rawDocs[doc._id] = {
+ rev : doc._rev,
+ raw : req.responseText
+ };
+ }
+ });
+ } else {
+ $.extend(options, {
+ beforeSuccess : function(req, doc) {
+ if (doc["jquery.couch.attachPrevRev"]) {
+ rawDocs[doc._id] = {
+ rev : doc._rev,
+ raw : req.responseText
+ };
+ }
+ }
+ });
+ }
+ ajax({url: this.uri + encodeDocId(docId) + encodeOptions(options)},
+ options,
+ "The document could not be retrieved",
+ ajaxOptions
+ );
+ },
+
+ /**
+ * Create a new document in the specified database, using the supplied
+ * JSON document structure. If the JSON structure includes the _id
+ * field, then the document will be created with the specified document
+ * ID. If the _id field is not specified, a new unique ID will be
+ * generated.
+ * @see <a href="http://techzone.couchbase.com/sites/default/files/
+ * uploads/all/documentation/couchbase-api-dbdoc.html#couchbase-api-
+ * dbdoc_db_post">docs for GET /db/doc</a>
+ * @param {String} doc document to save
+ * @param {ajaxSettings} options <a href="http://api.jquery.com/
+ * jQuery.ajax/#jQuery-ajax-settings">jQuery ajax settings</a>
+ */
+ saveDoc: function(doc, options) {
+ options = options || {};
+ var db = this;
+ var beforeSend = fullCommit(options);
+ if (doc._id === undefined) {
+ var method = "POST";
+ var uri = this.uri;
+ } else {
+ var method = "PUT";
+ var uri = this.uri + encodeDocId(doc._id);
+ }
+ var versioned = maybeApplyVersion(doc);
+ $.ajax({
+ type: method, url: uri + encodeOptions(options),
+ contentType: "application/json",
+ dataType: "json", data: toJSON(doc),
+ beforeSend : beforeSend,
+ complete: function(req) {
+ var resp = $.parseJSON(req.responseText);
+ if (req.status == 200 || req.status == 201 || req.status == 202) {
+ doc._id = resp.id;
+ doc._rev = resp.rev;
+ if (versioned) {
+ db.openDoc(doc._id, {
+ attachPrevRev : true,
+ success : function(d) {
+ doc._attachments = d._attachments;
+ if (options.success) options.success(resp);
+ }
+ });
+ } else {
+ if (options.success) options.success(resp);
+ }
+ } else if (options.error) {
+ options.error(req.status, resp.error, resp.reason);
+ } else {
+ alert("The document could not be saved: " + resp.reason);
+ }
+ }
+ });
+ },
+
+ /**
+ * Save a list of documents
+ * @see <a href="http://techzone.couchbase.com/sites/default/files/
+ * uploads/all/documentation/couchbase-api-db.html#couchbase-api-db_
+ * db-bulk-docs_post">docs for /db/_bulk_docs</a>
+ * @param {Object[]} docs List of documents to save
+ * @param {ajaxSettings} options <a href="http://api.jquery.com/
+ * jQuery.ajax/#jQuery-ajax-settings">jQuery ajax settings</a>
+ */
+ bulkSave: function(docs, options) {
+ var beforeSend = fullCommit(options);
+ $.extend(options, {successStatus: 201, beforeSend : beforeSend});
+ ajax({
+ type: "POST",
+ url: this.uri + "_bulk_docs" + encodeOptions(options),
+ contentType: "application/json", data: toJSON(docs)
+ },
+ options,
+ "The documents could not be saved"
+ );
+ },
+
+ /**
+ * Deletes the specified document from the database. You must supply
+ * the current (latest) revision and <code>id</code> of the document
+ * to delete eg <code>removeDoc({_id:"mydoc", _rev: "1-2345"})</code>
+ * @see <a href="http://techzone.couchbase.com/sites/default/files/
+ * uploads/all/documentation/couchbase-api-dbdoc.html#couchbase-api
+ * -dbdoc_db-doc_delete">docs for DELETE /db/doc</a>
+ * @param {Object} doc Document to delete
+ * @param {ajaxSettings} options <a href="http://api.jquery.com/
+ * jQuery.ajax/#jQuery-ajax-settings">jQuery ajax settings</a>
+ */
+ removeDoc: function(doc, options) {
+ ajax({
+ type: "DELETE",
+ url: this.uri +
+ encodeDocId(doc._id) +
+ encodeOptions({rev: doc._rev})
+ },
+ options,
+ "The document could not be deleted"
+ );
+ },
+
+ /**
+ * Remove a set of documents
+ * @see <a href="http://techzone.couchbase.com/sites/default/files/
+ * uploads/all/documentation/couchbase-api-db.html#couchbase-api-db_
+ * db-bulk-docs_post">docs for /db/_bulk_docs</a>
+ * @param {String[]} docs List of document id's to remove
+ * @param {ajaxSettings} options <a href="http://api.jquery.com/
+ * jQuery.ajax/#jQuery-ajax-settings">jQuery ajax settings</a>
+ */
+ bulkRemove: function(docs, options){
+ docs.docs = $.each(
+ docs.docs, function(i, doc){
+ doc._deleted = true;
+ }
+ );
+ $.extend(options, {successStatus: 201});
+ ajax({
+ type: "POST",
+ url: this.uri + "_bulk_docs" + encodeOptions(options),
+ data: toJSON(docs)
+ },
+ options,
+ "The documents could not be deleted"
+ );
+ },
+
+ /**
+ * The COPY command (which is non-standard HTTP) copies an existing
+ * document to a new or existing document.
+ * @see <a href="http://techzone.couchbase.com/sites/default/files/
+ * uploads/all/documentation/couchbase-api-dbdoc.html#couchbase-api-
+ * dbdoc_db-doc_copy">docs for COPY /db/doc</a>
+ * @param {String[]} docId document id to copy
+ * @param {ajaxSettings} options <a href="http://api.jquery.com/
+ * jQuery.ajax/#jQuery-ajax-settings">jQuery ajax settings</a>
+ * @param {ajaxSettings} options <a href="http://api.jquery.com/
+ * jQuery.ajax/#jQuery-ajax-settings">jQuery ajax settings</a>
+ */
+ copyDoc: function(docId, options, ajaxOptions) {
+ ajaxOptions = $.extend(ajaxOptions, {
+ complete: function(req) {
+ var resp = $.parseJSON(req.responseText);
+ if (req.status == 201) {
+ if (options.success) options.success(resp);
+ } else if (options.error) {
+ options.error(req.status, resp.error, resp.reason);
+ } else {
+ alert("The document could not be copied: " + resp.reason);
+ }
+ }
+ });
+ ajax({
+ type: "COPY",
+ url: this.uri + encodeDocId(docId)
+ },
+ options,
+ "The document could not be copied",
+ ajaxOptions
+ );
+ },
+
+ /**
+ * Creates (and executes) a temporary view based on the view function
+ * supplied in the JSON request.
+ * @see <a href="http://techzone.couchbase.com/sites/default/files/
+ * uploads/all/documentation/couchbase-api-db.html#couchbase-api-db
+ * _db-temp-view_post">docs for /db/_temp_view</a>
+ * @param {Function} mapFun Map function
+ * @param {Function} reduceFun Reduce function
+ * @param {Function} language Language the map / reduce funs are
+ * implemented in
+ * @param {ajaxSettings} options <a href="http://api.jquery.com/
+ * jQuery.ajax/#jQuery-ajax-settings">jQuery ajax settings</a>
+ */
+ query: function(mapFun, reduceFun, language, options) {
+ language = language || "javascript";
+ if (typeof(mapFun) !== "string") {
+ mapFun = mapFun.toSource ? mapFun.toSource()
+ : "(" + mapFun.toString() + ")";
+ }
+ var body = {language: language, map: mapFun};
+ if (reduceFun != null) {
+ if (typeof(reduceFun) !== "string")
+ reduceFun = reduceFun.toSource ? reduceFun.toSource()
+ : "(" + reduceFun.toString() + ")";
+ body.reduce = reduceFun;
+ }
+ ajax({
+ type: "POST",
+ url: this.uri + "_temp_view" + encodeOptions(options),
+ contentType: "application/json", data: toJSON(body)
+ },
+ options,
+ "An error occurred querying the database"
+ );
+ },
+
+ /**
+ * Fetch a _list view output, you can specify a list of
+ * <code>keys</code> in the options object to recieve only those keys.
+ * @see <a href="http://techzone.couchbase.com/sites/default/files/
+ * uploads/all/documentation/couchbase-api-design.html#couchbase-api
+ * -design_db-design-designdoc-list-listname-viewname_get">
+ * docs for /db/_design/design-doc/_list/l1/v1</a>
+ * @param {String} list Listname in the form of ddoc/listname
+ * @param {String} view View to run list against
+ * @param {options} CouchDB <a href="http://wiki.apache.org/couchdb/
+ * HTTP_view_API">View Options</a>
+ * @param {ajaxSettings} options <a href="http://api.jquery.com/
+ * jQuery.ajax/#jQuery-ajax-settings">jQuery ajax settings</a>
+ */
+ list: function(list, view, options, ajaxOptions) {
+ var list = list.split('/');
+ var options = options || {};
+ var type = 'GET';
+ var data = null;
+ if (options['keys']) {
+ type = 'POST';
+ var keys = options['keys'];
+ delete options['keys'];
+ data = toJSON({'keys': keys });
+ }
+ ajax({
+ type: type,
+ data: data,
+ url: this.uri + '_design/' + list[0] +
+ '/_list/' + list[1] + '/' + view + encodeOptions(options)
+ },
+ ajaxOptions, 'An error occured accessing the list'
+ );
+ },
+
+ /**
+ * Executes the specified view-name from the specified design-doc
+ * design document, you can specify a list of <code>keys</code>
+ * in the options object to recieve only those keys.
+ * @see <a href="http://techzone.couchbase.com/sites/default/files/
+ * uploads/all/documentation/couchbase-api-design.html#couchbase-api-
+ * design_db-design-designdoc-view-viewname_get">docs for /db/
+ * _design/design-doc/_list/l1/v1</a>
+ * @param {String} name View to run list against
+ * @param {ajaxSettings} options <a href="http://api.jquery.com/
+ * jQuery.ajax/#jQuery-ajax-settings">jQuery ajax settings</a>
+ */
+ view: function(name, options) {
+ var name = name.split('/');
+ var options = options || {};
+ var type = "GET";
+ var data= null;
+ if (options["keys"]) {
+ type = "POST";
+ var keys = options["keys"];
+ delete options["keys"];
+ data = toJSON({ "keys": keys });
+ }
+ ajax({
+ type: type,
+ data: data,
+ url: this.uri + "_design/" + name[0] +
+ "/_view/" + name[1] + encodeOptions(options)
+ },
+ options, "An error occurred accessing the view"
+ );
+ },
+
+ /**
+ * Fetch an arbitrary CouchDB database property
+ * @see <a href="http://techzone.couchbase.com/sites/default/files/
+ * uploads/all/documentation/couchbase-api.html">docs for /db/_prop</a>
+ * @param {String} propName Propery name to fetch
+ * @param {ajaxSettings} options <a href="http://api.jquery.com/
+ * jQuery.ajax/#jQuery-ajax-settings">jQuery ajax settings</a>
+ * @param {ajaxSettings} ajaxOptions <a href="http://api.jquery.com/
+ * jQuery.ajax/#jQuery-ajax-settings">jQuery ajax settings</a>
+ */
+ getDbProperty: function(propName, options, ajaxOptions) {
+ ajax({url: this.uri + propName + encodeOptions(options)},
+ options,
+ "The property could not be retrieved",
+ ajaxOptions
+ );
+ },
+
+ /**
+ * Set an arbitrary CouchDB database property
+ * @see <a href="http://techzone.couchbase.com/sites/default/files/
+ * uploads/all/documentation/couchbase-api.html">docs for /db/_prop</a>
+ * @param {String} propName Propery name to fetch
+ * @param {String} propValue Propery value to set
+ * @param {ajaxSettings} options <a href="http://api.jquery.com/
+ * jQuery.ajax/#jQuery-ajax-settings">jQuery ajax settings</a>
+ * @param {ajaxSettings} ajaxOptions <a href="http://api.jquery.com/
+ * jQuery.ajax/#jQuery-ajax-settings">jQuery ajax settings</a>
+ */
+ setDbProperty: function(propName, propValue, options, ajaxOptions) {
+ ajax({
+ type: "PUT",
+ url: this.uri + propName + encodeOptions(options),
+ data : JSON.stringify(propValue)
+ },
+ options,
+ "The property could not be updated",
+ ajaxOptions
+ );
+ }
+ };
+ },
+
+ encodeDocId: encodeDocId,
+
+ /**
+ * Accessing the root of a CouchDB instance returns meta information about
+ * the instance. The response is a JSON structure containing information
+ * about the server, including a welcome message and the version of the
+ * server.
+ * @see <a href="http://techzone.couchbase.com/sites/default/files/uploads/
+ * all/documentation/couchbase-api-misc.html#couchbase-api-misc_root_get">
+ * docs for GET /</a>
+ * @param {ajaxSettings} options <a href="http://api.jquery.com/
+ * jQuery.ajax/#jQuery-ajax-settings">jQuery ajax settings</a>
+ */
+ info: function(options) {
+ ajax(
+ {url: this.urlPrefix + "/"},
+ options,
+ "Server information could not be retrieved"
+ );
+ },
+
+ /**
+ * Request, configure, or stop, a replication operation.
+ * @see <a href="http://techzone.couchbase.com/sites/default/files/
+ * uploads/all/documentation/couchbase-api-misc.html#couchbase-api-
+ * misc_replicate_post">docs for POST /_replicate</a>
+ * @param {String} source Path or url to source database
+ * @param {String} target Path or url to target database
+ * @param {ajaxSettings} ajaxOptions <a href="http://api.jquery.com/
+ * jQuery.ajax/#jQuery-ajax-settings">jQuery ajax settings</a>
+ * @param {Object} repOpts Additional replication options
+ */
+ replicate: function(source, target, ajaxOptions, repOpts) {
+ repOpts = $.extend({source: source, target: target}, repOpts);
+ if (repOpts.continuous && !repOpts.cancel) {
+ ajaxOptions.successStatus = 202;
+ }
+ ajax({
+ type: "POST", url: this.urlPrefix + "/_replicate",
+ data: JSON.stringify(repOpts),
+ contentType: "application/json"
+ },
+ ajaxOptions,
+ "Replication failed"
+ );
+ },
+
+ /**
+ * Fetch a new UUID
+ * @see <a href="http://techzone.couchbase.com/sites/default/files/
+ * uploads/all/documentation/couchbase-api-misc.html#couchbase-api-
+ * misc_uuids_get">docs for /_uuids</a>
+ * @param {Int} cacheNum Number of uuids to keep cached for future use
+ */
+ newUUID: function(cacheNum) {
+ if (cacheNum === undefined) {
+ cacheNum = 1;
+ }
+ if (!uuidCache.length) {
+ ajax({url: this.urlPrefix + "/_uuids", data: {count: cacheNum}, async:
+ false}, {
+ success: function(resp) {
+ uuidCache = resp.uuids;
+ }
+ },
+ "Failed to retrieve UUID batch."
+ );
+ }
+ return uuidCache.shift();
+ }
+ });
+
+ /**
+ * @private
+ */
+ function ajax(obj, options, errorMessage, ajaxOptions) {
+
+ var defaultAjaxOpts = {
+ contentType: "application/json",
+ headers:{"Accept": "application/json"}
+ };
+
+ options = $.extend({successStatus: 200}, options);
+ ajaxOptions = $.extend(defaultAjaxOpts, ajaxOptions);
+ errorMessage = errorMessage || "Unknown error";
+ $.ajax($.extend($.extend({
+ type: "GET", dataType: "json", cache : !$.browser.msie,
+ beforeSend: function(xhr){
+ if(ajaxOptions && ajaxOptions.headers){
+ for (var header in ajaxOptions.headers){
+ xhr.setRequestHeader(header, ajaxOptions.headers[header]);
+ }
+ }
+ },
+ complete: function(req) {
+ try {
+ var resp = $.parseJSON(req.responseText);
+ } catch(e) {
+ if (options.error) {
+ options.error(req.status, req, e);
+ } else {
+ alert(errorMessage + ": " + e);
+ }
+ return;
+ }
+ if (options.ajaxStart) {
+ options.ajaxStart(resp);
+ }
+ if (req.status == options.successStatus) {
+ if (options.beforeSuccess) options.beforeSuccess(req, resp);
+ if (options.success) options.success(resp);
+ } else if (options.error) {
+ options.error(req.status, resp && resp.error ||
+ errorMessage, resp && resp.reason || "no response");
+ } else {
+ alert(errorMessage + ": " + resp.reason);
+ }
+ }
+ }, obj), ajaxOptions));
+ }
+
+ /**
+ * @private
+ */
+ function fullCommit(options) {
+ var options = options || {};
+ if (typeof options.ensure_full_commit !== "undefined") {
+ var commit = options.ensure_full_commit;
+ delete options.ensure_full_commit;
+ return function(xhr) {
+ xhr.setRequestHeader('Accept', 'application/json');
+ xhr.setRequestHeader("X-Couch-Full-Commit", commit.toString());
+ };
+ }
+ };
+
+ /**
+ * @private
+ */
+ // Convert a options object to an url query string.
+ // ex: {key:'value',key2:'value2'} becomes '?key="value"&key2="value2"'
+ function encodeOptions(options) {
+ var buf = [];
+ if (typeof(options) === "object" && options !== null) {
+ for (var name in options) {
+ if ($.inArray(name,
+ ["error", "success", "beforeSuccess", "ajaxStart"]) >= 0)
+ continue;
+ var value = options[name];
+ if ($.inArray(name, ["key", "startkey", "endkey"]) >= 0) {
+ value = toJSON(value);
+ }
+ buf.push(encodeURIComponent(name) + "=" + encodeURIComponent(value));
+ }
+ }
+ return buf.length ? "?" + buf.join("&") : "";
+ }
+
+ /**
+ * @private
+ */
+ function toJSON(obj) {
+ return obj !== null ? JSON.stringify(obj) : null;
+ }
+
+})(jQuery);
View
399 welcome/vendor/couchapp/_attachments/jquery.evently.js
@@ -0,0 +1,399 @@
+// $$ inspired by @wycats: http://yehudakatz.com/2009/04/20/evented-programming-with-jquery/
+function $$(node) {
+ var data = $(node).data("$$");
+ if (data) {
+ return data;
+ } else {
+ data = {};
+ $(node).data("$$", data);
+ return data;
+ }
+};
+
+(function($) {
+ // utility functions used in the implementation
+
+ function forIn(obj, fun) {
+ var name;
+ for (name in obj) {
+ if (obj.hasOwnProperty(name)) {
+ fun(name, obj[name]);
+ }
+ }
+ };
+ $.forIn = forIn;
+ function funViaString(fun, hint) {
+ if (fun && fun.match && fun.match(/^function/)) {
+ eval("var f = "+fun);
+ if (typeof f == "function") {
+ return function() {
+ try {
+ return f.apply(this, arguments);
+ } catch(e) {
+ // IF YOU SEE AN ERROR HERE IT HAPPENED WHEN WE TRIED TO RUN YOUR FUNCTION
+ $.log({"message": "Error in evently function.", "error": e,
+ "src" : fun, "hint":hint});
+ throw(e);
+ }
+ };
+ }
+ }
+ return fun;
+ };
+
+ function runIfFun(me, fun, args) {
+ // if the field is a function, call it, bound to the widget
+ var f = funViaString(fun, me);
+ if (typeof f == "function") {
+ return f.apply(me, args);
+ } else {
+ return fun;
+ }
+ }
+
+ $.evently = {
+ connect : function(source, target, events) {
+ events.forEach(function(ev) {
+ $(source).bind(ev, function() {
+ var args = $.makeArray(arguments);
+ // remove the original event to keep from stacking args extra deep
+ // it would be nice if jquery had a way to pass the original
+ // event to the trigger method.
+ args.shift();
+ $(target).trigger(ev, args);
+ return false;
+ });
+ });
+ },
+ paths : [],
+ changesDBs : {},
+ changesOpts : {}
+ };
+
+ function extractFrom(name, evs) {
+ return evs[name];
+ };
+
+ function extractEvents(name, ddoc) {
+ // extract events from ddoc.evently and ddoc.vendor.*.evently
+ var events = [true, {}]
+ , vendor = ddoc.vendor || {}
+ , evently = ddoc.evently || {}
+ ;
+ $.forIn(vendor, function(k, v) {
+ if (v.evently && v.evently[name]) {
+ events.push(v.evently[name]);
+ }
+ });
+ if (evently[name]) {events.push(evently[name]);}
+ return $.extend.apply(null, events);
+ }
+
+ function extractPartials(ddoc) {
+ var partials = [true, {}]
+ , vendor = ddoc.vendor || {}
+ , evently = ddoc.evently || {}
+ ;
+ $.forIn(vendor, function(k, v) {
+ if (v.evently && v.evently._partials) {
+ partials.push(v.evently._partials);
+ }
+ });
+ if (evently._partials) {partials.push(evently._partials);}
+ return $.extend.apply(null, partials);
+ };
+
+ function applyCommon(events) {
+ if (events._common) {
+ $.forIn(events, function(k, v) {
+ events[k] = $.extend(true, {}, events._common, v);
+ });
+ delete events._common;
+ return events;
+ } else {
+ return events;
+ }
+ }
+
+ $.fn.evently = function(events, app, args) {
+ var elem = $(this);
+ // store the app on the element for later use
+ if (app) {
+ $$(elem).app = app;
+ }
+
+ if (typeof events == "string") {
+ events = extractEvents(events, app.ddoc);
+ }
+ events = applyCommon(events);
+ $$(elem).evently = events;
+ if (app && app.ddoc) {
+ $$(elem).partials = extractPartials(app.ddoc);
+ }
+ // setup the handlers onto elem
+ forIn(events, function(name, h) {
+ eventlyHandler(elem, name, h, args);
+ });
+
+ if (events._init) {
+ elem.trigger("_init", args);
+ }
+
+ if (app && events._changes) {
+ $("body").bind("evently-changes-"+app.db.name, function() {
+ elem.trigger("_changes");
+ });
+ followChanges(app);
+ elem.trigger("_changes");
+ }
+ };
+
+ // eventlyHandler applies the user's handler (h) to the
+ // elem, bound to trigger based on name.
+ function eventlyHandler(elem, name, h, args) {
+ if ($.evently.log) {
+ elem.bind(name, function() {
+ $.log(elem, name);
+ });
+ }
+ if (h.path) {
+ elem.pathbinder(name, h.path);
+ }
+ var f = funViaString(h, name);
+ if (typeof f == "function") {
+ elem.bind(name, {args:args}, f);
+ } else if (typeof f == "string") {
+ elem.bind(name, {args:args}, function() {
+ $(this).trigger(f, arguments);
+ return false;
+ });
+ } else if ($.isArray(h)) {
+ // handle arrays recursively
+ for (var i=0; i < h.length; i++) {
+ eventlyHandler(elem, name, h[i], args);
+ }
+ } else {
+ // an object is using the evently / mustache template system
+ if (h.fun) {
+ throw("e.fun has been removed, please rename to e.before")
+ }
+ // templates, selectors, etc are intepreted
+ // when our named event is triggered.
+ elem.bind(name, {args:args}, function() {
+ renderElement($(this), h, arguments);
+ return false;
+ });
+ }
+ };
+
+ $.fn.replace = function(elem) {
+ // $.log("Replace", this)
+ $(this).empty().append(elem);
+ };
+
+ // todo: ability to call this
+ // to render and "prepend/append/etc" a new element to the host element (me)
+ // as well as call this in a way that replaces the host elements content
+ // this would be easy if there is a simple way to get at the element we just appended
+ // (as html) so that we can attache the selectors
+ function renderElement(me, h, args, qrun, arun) {
+ // if there's a query object we run the query,
+ // and then call the data function with the response.
+ if (h.before && (!qrun || !arun)) {
+ funViaString(h.before, me).apply(me, args);
+ }
+ if (h.async && !arun) {
+ runAsync(me, h, args)
+ } else if (h.query && !qrun) {
+ // $.log("query before renderElement", arguments)
+ runQuery(me, h, args)
+ } else {
+ // $.log("renderElement")
+ // $.log(me, h, args, qrun)
+ // otherwise we just render the template with the current args
+ var selectors = runIfFun(me, h.selectors, args);
+ var act = (h.render || "replace").replace(/\s/g,"");
+ var app = $$(me).app;
+ if (h.mustache) {
+ // $.log("rendering", h.mustache)
+ var newElem = mustachioed(me, h, args);
+ me[act](newElem);
+ }
+ if (selectors) {
+ if (act == "replace") {
+ var s = me;
+ } else {
+ var s = newElem;
+ }
+ forIn(selectors, function(selector, handlers) {
+ // $.log("selector", selector);
+ // $.log("selected", $(selector, s));
+ $(selector, s).evently(handlers, app, args);
+ // $.log("applied", selector);
+ });
+ }
+ if (h.after) {
+ runIfFun(me, h.after, args);
+ }
+ }
+ };
+
+ // todo this should return the new element
+ function mustachioed(me, h, args) {
+ var partials = $$(me).partials;
+ return $($.mustache(
+ runIfFun(me, h.mustache, args),
+ runIfFun(me, h.data, args),
+ runIfFun(me, $.extend(true, partials, h.partials), args)));
+ };
+
+ function runAsync(me, h, args) {
+ // the callback is the first argument
+ funViaString(h.async, me).apply(me, [function() {
+ renderElement(me, h,
+ $.argsToArray(arguments).concat($.argsToArray(args)), false, true);
+ }].concat($.argsToArray(args)));
+ };
+
+
+ function runQuery(me, h, args) {
+ // $.log("runQuery: args", args)
+ var app = $$(me).app;
+ var qu = runIfFun(me, h.query, args);
+ var qType = qu.type;
+ var viewName = qu.view;
+ var userSuccess = qu.success;
+ // $.log("qType", qType)
+
+ var q = {};
+ forIn(qu, function(k, v) {
+ if (["type", "view"].indexOf(k) == -1) {
+ q[k] = v;
+ }
+ });
+
+ if (qType == "newRows") {
+ q.success = function(resp) {
+ // $.log("runQuery newRows success", resp.rows.length, me, resp)
+ resp.rows.reverse().forEach(function(row) {
+ renderElement(me, h, [row].concat($.argsToArray(args)), true)
+ });
+ if (userSuccess) userSuccess(resp);
+ };
+ newRows(me, app, viewName, q);
+ } else {
+ q.success = function(resp) {
+ // $.log("runQuery success", resp)
+ renderElement(me, h, [resp].concat($.argsToArray(args)), true);
+ userSuccess && userSuccess(resp);
+ };
+ // $.log(app)
+ app.view(viewName, q);
+ }
+ }
+
+ // this is for the items handler
+ // var lastViewId, highKey, inFlight;
+ // this needs to key per elem
+ function newRows(elem, app, view, opts) {
+ // $.log("newRows", arguments);
+ // on success we'll set the top key
+ var thisViewId, successCallback = opts.success, full = false;
+ function successFun(resp) {
+ // $.log("newRows success", resp)
+ $$(elem).inFlight = false;
+ var JSONhighKey = JSON.stringify($$(elem).highKey);
+ resp.rows = resp.rows.filter(function(r) {
+ return JSON.stringify(r.key) != JSONhighKey;
+ });
+ if (resp.rows.length > 0) {
+ if (opts.descending) {
+ $$(elem).highKey = resp.rows[0].key;
+ } else {
+ $$(elem).highKey = resp.rows[resp.rows.length -1].key;
+ }
+ };
+ if (successCallback) {successCallback(resp, full)};
+ };
+ opts.success = successFun;
+
+ if (opts.descending) {
+ thisViewId = view + (opts.startkey ? JSON.stringify(opts.startkey) : "");
+ } else {
+ thisViewId = view + (opts.endkey ? JSON.stringify(opts.endkey) : "");
+ }
+ // $.log(["thisViewId",thisViewId])
+ // for query we'll set keys
+ if (thisViewId == $$(elem).lastViewId) {
+ // we only want the rows newer than changesKey
+ var hk = $$(elem).highKey;
+ if (hk !== undefined) {
+ if (opts.descending) {
+ opts.endkey = hk;
+ // opts.inclusive_end = false;
+ } else {
+ opts.startkey = hk;
+ }
+ }
+ // $.log("add view rows", opts)
+ if (!$$(elem).inFlight) {
+ $$(elem).inFlight = true;
+ app.view(view, opts);
+ }
+ } else {
+ // full refresh
+ // $.log("new view stuff")
+ full = true;
+ $$(elem).lastViewId = thisViewId;
+ $$(elem).highKey = undefined;
+ $$(elem).inFlight = true;
+ app.view(view, opts);
+ }
+ };
+
+ // only start one changes listener per db
+ function followChanges(app) {
+ var dbName = app.db.name, changeEvent = function(resp) {
+ $("body").trigger("evently-changes-"+dbName, [resp]);
+ };
+ if (!$.evently.changesDBs[dbName]) {
+ if (app.db.changes) {
+ // new api in jquery.couch.js 1.0
+ app.db.changes(null, $.evently.changesOpts).onChange(changeEvent);
+ } else {
+ // in case you are still on CouchDB 0.11 ;) deprecated.
+ connectToChanges(app, changeEvent);
+ }
+ $.evently.changesDBs[dbName] = true;
+ }
+ }
+ $.evently.followChanges = followChanges;
+ // deprecated. use db.changes() from jquery.couch.js
+ // this does not have an api for closing changes request.
+ function connectToChanges(app, fun, update_seq) {
+ function changesReq(seq) {
+ var url = app.db.uri+"_changes?heartbeat=10000&feed=longpoll&since="+seq;
+ if ($.evently.changesOpts.include_docs) {
+ url = url + "&include_docs=true";
+ }
+ $.ajax({
+ url: url,
+ contentType: "application/json",
+ dataType: "json",
+ complete: function(req) {
+ var resp = $.httpData(req, "json");
+ fun(resp);
+ connectToChanges(app, fun, resp.last_seq);
+ }
+ });
+ };
+ if (update_seq) {
+ changesReq(update_seq);
+ } else {
+ app.db.info({success: function(db_info) {
+ changesReq(db_info.update_seq);
+ }});
+ }
+ };
+
+})(jQuery);
View
6,240 welcome/vendor/couchapp/_attachments/jquery.js
6,240 additions, 0 deletions not shown
View
346 welcome/vendor/couchapp/_attachments/jquery.mustache.js
@@ -0,0 +1,346 @@
+/*
+Shameless port of a shameless port
+@defunkt => @janl => @aq
+
+See http://github.com/defunkt/mustache for more info.
+*/
+
+;(function($) {
+
+/*
+ mustache.js — Logic-less templates in JavaScript
+
+ See http://mustache.github.com/ for more info.
+*/
+
+var Mustache = function() {
+ var Renderer = function() {};
+
+ Renderer.prototype = {
+ otag: "{{",
+ ctag: "}}",
+ pragmas: {},
+ buffer: [],
+ pragmas_implemented: {
+ "IMPLICIT-ITERATOR": true
+ },
+ context: {},
+
+ render: function(template, context, partials, in_recursion) {
+ // reset buffer & set context
+ if(!in_recursion) {
+ this.context = context;
+ this.buffer = []; // TODO: make this non-lazy
+ }
+
+ // fail fast
+ if(!this.includes("", template)) {
+ if(in_recursion) {
+ return template;
+ } else {
+ this.send(template);
+ return;
+ }
+ }
+
+ template = this.render_pragmas(template);
+ var html = this.render_section(template, context, partials);
+ if(in_recursion) {
+ return this.render_tags(html, context, partials, in_recursion);
+ }
+
+ this.render_tags(html, context, partials, in_recursion);
+ },
+
+ /*
+ Sends parsed lines
+ */
+ send: function(line) {
+ if(line != "") {
+ this.buffer.push(line);
+ }
+ },
+
+ /*
+ Looks for %PRAGMAS
+ */
+ render_pragmas: function(template) {
+ // no pragmas
+ if(!this.includes("%", template)) {
+ return template;
+ }
+
+ var that = this;
+ var regex = new RegExp(this.otag + "%([\\w-]+) ?([\\w]+=[\\w]+)?" +
+ this.ctag);
+ return template.replace(regex, function(match, pragma, options) {
+ if(!that.pragmas_implemented[pragma]) {
+ throw({message:
+ "This implementation of mustache doesn't understand the '" +
+ pragma + "' pragma"});
+ }
+ that.pragmas[pragma] = {};
+ if(options) {
+ var opts = options.split("=");
+ that.pragmas[pragma][opts[0]] = opts[1];
+ }
+ return "";
+ // ignore unknown pragmas silently
+ });
+ },
+
+ /*
+ Tries to find a partial in the curent scope and render it
+ */
+ render_partial: function(name, context, partials) {
+ name = this.trim(name);
+ if(!partials || partials[name] === undefined) {
+ throw({message: "unknown_partial '" + name + "'"});
+ }
+ if(typeof(context[name]) != "object") {
+ return this.render(partials[name], context, partials, true);
+ }
+ return this.render(partials[name], context[name], partials, true);
+ },
+
+ /*
+ Renders inverted (^) and normal (#) sections
+ */
+ render_section: function(template, context, partials) {
+ if(!this.includes("#", template) && !this.includes("^", template)) {
+ return template;
+ }
+
+ var that = this;
+ // CSW - Added "+?" so it finds the tighest bound, not the widest
+ var regex = new RegExp(this.otag + "(\\^|\\#)\\s*(.+)\\s*" + this.ctag +
+ "\n*([\\s\\S]+?)" + this.otag + "\\/\\s*\\2\\s*" + this.ctag +
+ "\\s*", "mg");
+
+ // for each {{#foo}}{{/foo}} section do...
+ return template.replace(regex, function(match, type, name, content) {
+ var value = that.find(name, context);
+ if(type == "^") { // inverted section
+ if(!value || that.is_array(value) && value.length === 0) {
+ // false or empty list, render it
+ return that.render(content, context, partials, true);
+ } else {
+ return "";
+ }
+ } else if(type == "#") { // normal section
+ if(that.is_array(value)) { // Enumerable, Let's loop!
+ return that.map(value, function(row) {
+ return that.render(content, that.create_context(row),
+ partials, true);
+ }).join("");
+ } else if(that.is_object(value)) { // Object, Use it as subcontext!
+ return that.render(content, that.create_context(value),
+ partials, true);
+ } else if(typeof value === "function") {
+ // higher order section
+ return value.call(context, content, function(text) {
+ return that.render(text, context, partials, true);
+ });
+ } else if(value) { // boolean section
+ return that.render(content, context, partials, true);
+ } else {
+ return "";
+ }
+ }
+ });
+ },
+
+ /*
+ Replace {{foo}} and friends with values from our view
+ */
+ render_tags: function(template, context, partials, in_recursion) {
+ // tit for tat
+ var that = this;
+
+ var new_regex = function() {
+ return new RegExp(that.otag + "(=|!|>|\\{|%)?([^\\/#\\^]+?)\\1?" +
+ that.ctag + "+", "g");
+ };
+
+ var regex = new_regex();
+ var tag_replace_callback = function(match, operator, name) {
+ switch(operator) {
+ case "!": // ignore comments
+ return "";
+ case "=": // set new delimiters, rebuild the replace regexp
+ that.set_delimiters(name);
+ regex = new_regex();
+ return "";
+ case ">": // render partial
+ return that.render_partial(name, context, partials);
+ case "{": // the triple mustache is unescaped
+ return that.find(name, context);
+ default: // escape the value
+ return that.escape(that.find(name, context));
+ }
+ };
+ var lines = template.split("\n");
+ for(var i = 0; i < lines.length; i++) {
+ lines[i] = lines[i].replace(regex, tag_replace_callback, this);
+ if(!in_recursion) {
+ this.send(lines[i]);
+ }
+ }
+
+ if(in_recursion) {
+ return lines.join("\n");
+ }