[TASK] Add jQuery couchdb helper.

This commit is contained in:
Jan Philipp Timme 2013-09-12 20:38:39 +02:00
parent 5306f5ed5b
commit bb58998a30
10 changed files with 2236 additions and 4 deletions

View File

@ -4,13 +4,20 @@
<title>Dashboard Test</title> <title>Dashboard Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="robots" content="noindex,nofollow" /> <meta name="robots" content="noindex,nofollow" />
<!-- stylesheets -->
<link rel="stylesheet" type="text/css" href="style/main.css" /> <link rel="stylesheet" type="text/css" href="style/main.css" />
<!-- jQuery -->
<script type="text/javascript" src="js/jquery-2.0.3.min.js"></script>
<!-- jQuery ui smoothness theme -->
<link rel="stylesheet" type="text/css" href="jquery-ui-1.10.3.custom/css/smoothness/jquery-ui-1.10.3.custom.min.css" /> <link rel="stylesheet" type="text/css" href="jquery-ui-1.10.3.custom/css/smoothness/jquery-ui-1.10.3.custom.min.css" />
<!-- jQuery ui --> <!-- scripts -->
<script type="text/javascript" src="js/jquery-2.0.3.min.js"></script>
<script type="text/javascript" src="jquery-ui-1.10.3.custom/js/jquery-ui-1.10.3.custom.min.js"></script> <script type="text/javascript" src="jquery-ui-1.10.3.custom/js/jquery-ui-1.10.3.custom.min.js"></script>
<script type="text/javascript" src="js/couchapp/md5.js"></script>
<script type="text/javascript" src="js/couchapp/jquery.couch.js"></script>
<script type="text/javascript" src="js/couchapp/jquery.couch.app.js"></script>
<script type="text/javascript" src="js/couchapp/jquery.couch.app.util.js"></script>
<script type="text/javascript" src="js/couchapp/jquery.couchForm.js"></script>
<script type="text/javascript" src="js/couchapp/jquery.couchLogin.js"></script>
<script type="text/javascript" src="js/couchapp/jquery.couchProfile.js"></script>
<script type="text/javascript" src="js/couchapp/jquery.mustache.js"></script>
</head> </head>
<body> <body>
<div id="wallpaper"></div> <div id="wallpaper"></div>

View File

@ -0,0 +1,235 @@
// 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) {
db.view(name+'/'+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 File

@ -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;
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,43 @@
// I think this should go in jquery.couch.js
(function($) {
$.fn.couchForm = function(opts) {
opts = opts || {};
if (!opts.db) {
opts.db = $.couch.db(document.location.pathname.split('/')[1]);
}
var form = $(this);
form.submit(function(e) {
e.preventDefault();
var doc = form.serializeObject();
if (opts.beforeSave) {
doc = opts.beforeSave(doc);
}
opts.db.saveDoc(doc, {
success : function() {
if (opts.success) {
opts.success(doc);
}
form[0].reset();
}
});
return false;
});
};
// friendly helper http://tinyurl.com/6aow6yn
$.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;
};
})(jQuery);

View File

@ -0,0 +1,83 @@
// Copyright Chris Anderson 2011
// Apache 2.0 License
// jquery.couchLogin.js
//
// Example Usage (loggedIn and loggedOut callbacks are optional):
// $("#mylogindiv").couchLogin({
// loggedIn : function(userCtx) {
// alert("hello "+userCtx.name);
// },
// loggedOut : function() {
// alert("bye bye");
// }
// });
(function($) {
$.fn.couchLogin = function(opts) {
var elem = $(this);
opts = opts || {};
function initWidget() {
$.couch.session({
success : function(session) {
var userCtx = session.userCtx;
if (userCtx.name) {
elem.empty();
elem.append(loggedIn(session));
if (opts.loggedIn) {opts.loggedIn(session)}
} else if (userCtx.roles.indexOf("_admin") != -1) {
elem.html(templates.adminParty);
} else {
elem.html(templates.loggedOut);
if (opts.loggedOut) {opts.loggedOut()}
};
}
});
};
initWidget();
function doLogin(name, pass) {
$.couch.login({name:name, password:pass, success:initWidget});
};
elem.delegate("a[href=#signup]", "click", function() {
elem.html(templates.signupForm);
elem.find('input[name="name"]').focus();
return false;
});
elem.delegate("a[href=#login]", "click", function() {
elem.html(templates.loginForm);
elem.find('input[name="name"]').focus();
return false;
});
elem.delegate("a[href=#logout]", "click", function() {
$.couch.logout({success : initWidget});
return false;
});
elem.delegate("form.login", "submit", function() {
doLogin($('input[name=name]', this).val(),
$('input[name=password]', this).val());
return false;
});
elem.delegate("form.signup", "submit", function() {
var name = $('input[name=name]', this).val(),
pass = $('input[name=password]', this).val();
$.couch.signup({name : name}, pass, {
success : function() {doLogin(name, pass)}
});
return false;
});
}
var templates = {
adminParty : '<p><strong>Admin party, everyone is admin!</strong> Fix this in <a href="/_utils/index.html">Futon</a> before proceeding.</p>',
loggedOut : '<a href="#signup">Signup</a> or <a href="#login">Login</a>',
loginForm : '<form class="login"><label for="name">Name</label> <input type="text" name="name" value="" autocapitalize="off" autocorrect="off"><label for="password">Password</label> <input type="password" name="password" value=""><input type="submit" value="Login"><a href="#signup">or Signup</a></form>',
signupForm : '<form class="signup"><label for="name">Name</label> <input type="text" name="name" value="" autocapitalize="off" autocorrect="off"><label for="password">Password</label> <input type="password" name="password" value=""><input type="submit" value="Signup"><a href="#login">or Login</a></form>'
};
function loggedIn(r) {
var auth_db = encodeURIComponent(r.info.authentication_db)
, uri_name = encodeURIComponent(r.userCtx.name)
, span = $('<span>Welcome <a target="_new" href="/_utils/document.html?'
+ auth_db +'/org.couchdb.user%3A' + uri_name
+ '" class="name"></a>! <a href="#logout">Logout?</a></span>');
$('a.name', span).text(r.userCtx.name); // you can get the user name here
return span;
}
})(jQuery);

View File

@ -0,0 +1,85 @@
// Copyright Chris Anderson 2011
// Apache 2.0 License
// jquery.couchProfile.js
// depends on md5,
// jquery.couchLogin.js and requires.js
//
// Example Usage (loggedIn and loggedOut callbacks are optional):
// $("#myprofilediv").couchProfile({
// profileReady : function(profile) {
// alert("hello, do you look like this? "+profile.gravatar_url);
// }
// });
(function($) {
$.couchProfile = {};
$.couchProfile.templates = {
profileReady : '<div class="avatar">{{#gravatar_url}}<img src="{{gravatar_url}}"/>{{/gravatar_url}}<div class="name">{{nickname}}</div></div><p>Hello {{nickname}}!</p><div style="clear:left;"></div>',
newProfile : '<form><p>Hello {{name}}, Please setup your user profile.</p><label for="nickname">Nickname <input type="text" name="nickname" value=""></label><label for="email">Email (<em>for <a href="http://gravatar.com">Gravatar</a></em>) <input type="text" name="email" value=""></label><label for="url">URL <input type="text" name="url" value=""></label><input type="submit" value="Go &rarr;"><input type="hidden" name="userCtxName" value="{{name}}" id="userCtxName"></form>'
};
$.fn.couchProfile = function(session, opts) {
opts = opts || {};
var templates = $.couchProfile.templates;
var userCtx = session.userCtx;
var widget = $(this);
// load the profile from the user doc
var db = $.couch.db(session.info.authentication_db);
var userDocId = "org.couchdb.user:"+userCtx.name;
db.openDoc(userDocId, {
success : function(userDoc) {
var profile = userDoc["couch.app.profile"];
if (profile) {
profile.name = userDoc.name;
profileReady(profile);
} else {
newProfile(userCtx)
}
}
});
function profileReady(profile) {
widget.html($.mustache(templates.profileReady, profile));
if (opts.profileReady) {opts.profileReady(profile)};
};
function storeProfileOnUserDoc(newProfile) {
// store the user profile on the user account document
$.couch.userDb(function(db) {
var userDocId = "org.couchdb.user:"+userCtx.name;
db.openDoc(userDocId, {
success : function(userDoc) {
userDoc["couch.app.profile"] = newProfile;
db.saveDoc(userDoc, {
success : function() {
newProfile.name = userDoc.name;
profileReady(newProfile);
}
});
}
});
});
};
function newProfile(userCtx) {
widget.html($.mustache(templates.newProfile, userCtx));
widget.find("form").submit(function(e) {
e.preventDefault();
var form = this;
var name = $("input[name=userCtxName]",form).val();
var newProfile = {
rand : Math.random().toString(),
nickname : $("input[name=nickname]",form).val(),
email : $("input[name=email]",form).val(),
url : $("input[name=url]",form).val()
};
// setup gravatar_url if md5.js is loaded
if (hex_md5) {
newProfile.gravatar_url = 'http://www.gravatar.com/avatar/'+hex_md5(newProfile.email || newProfile.rand)+'.jpg?s=40&d=identicon';
}
storeProfileOnUserDoc(newProfile);
return false;
});
};
}
})(jQuery);

View File

@ -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");
}
},
set_delimiters: function(delimiters) {
var dels = delimiters.split(" ");
this.otag = this.escape_regex(dels[0]);
this.ctag = this.escape_regex(dels[1]);
},
escape_regex: function(text) {
// thank you Simon Willison
if(!arguments.callee.sRE) {
var specials = [
'/', '.', '*', '+', '?', '|',
'(', ')', '[', ']', '{', '}', '\\'
];
arguments.callee.sRE = new RegExp(
'(\\' + specials.join('|\\') + ')', 'g'
);
}
return text.replace(arguments.callee.sRE, '\\$1');
},
/*
find `name` in current `context`. That is find me a value
from the view object
*/
find: function(name, context) {
name = this.trim(name);
// Checks whether a value is thruthy or false or 0
function is_kinda_truthy(bool) {
return bool === false || bool === 0 || bool;
}
var value;
if(is_kinda_truthy(context[name])) {
value = context[name];
} else if(is_kinda_truthy(this.context[name])) {
value = this.context[name];
}
if(typeof value === "function") {
return value.apply(context);
}
if(value !== undefined) {
return value;
}
// silently ignore unkown variables
return "";
},
// Utility methods
/* includes tag */
includes: function(needle, haystack) {
return haystack.indexOf(this.otag + needle) != -1;
},
/*
Does away with nasty characters
*/
escape: function(s) {
s = String(s === null ? "" : s);
return s.replace(/&(?!\w+;)|["<>\\]/g, function(s) {
switch(s) {
case "&": return "&amp;";
case "\\": return "\\\\";
case '"': return '\"';
case "<": return "&lt;";
case ">": return "&gt;";
default: return s;
}
});
},
// by @langalex, support for arrays of strings
create_context: function(_context) {
if(this.is_object(_context)) {
return _context;
} else {
var iterator = ".";
if(this.pragmas["IMPLICIT-ITERATOR"]) {
iterator = this.pragmas["IMPLICIT-ITERATOR"].iterator;
}
var ctx = {};
ctx[iterator] = _context;
return ctx;
}
},
is_object: function(a) {
return a && typeof a == "object";
},
is_array: function(a) {
return Object.prototype.toString.call(a) === '[object Array]';
},
/*
Gets rid of leading and trailing whitespace
*/
trim: function(s) {
return s.replace(/^\s*|\s*$/g, "");
},
/*
Why, why, why? Because IE. Cry, cry cry.
*/
map: function(array, fn) {
if (typeof array.map == "function") {
return array.map(fn);
} else {
var r = [];
var l = array.length;
for(var i = 0; i < l; i++) {
r.push(fn(array[i]));
}
return r;
}
}
};
return({
name: "mustache.js",
version: "0.3.1-dev",
/*
Turns a template and view into HTML
*/
to_html: function(template, view, partials, send_fun) {
var renderer = new Renderer();
if(send_fun) {
renderer.send = send_fun;
}
renderer.render(template, view, partials);
if(!send_fun) {
return renderer.buffer.join("\n");
}
},
escape : function(text) {
return new Renderer().escape(text);
}
});
}();
$.mustache = function(template, view, partials) {
return Mustache.to_html(template, view, partials);
};
$.mustache.escape = function(text) {
return Mustache.escape(text);
};
})(jQuery);

View File

@ -0,0 +1,263 @@
/*
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*/
/*
* Configurable variables. You may need to tweak these to be compatible with
* the server-side, but the defaults work in most cases.
*/
var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */
var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */
var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */
/*
* These are the functions you'll usually want to call
* They take string arguments and return either hex or base-64 encoded strings
*/
function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));}
function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));}
function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));}
function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); }
function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); }
function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); }
/*
* Perform a simple self-test to see if the VM is working
*/
function md5_vm_test()
{
return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
}
/*
* Calculate the MD5 of an array of little-endian words, and a bit length
keep
*/
function core_md5(x, len)
{
/* append padding */
x[len >> 5] |= 0x80 << ((len) % 32);
x[(((len + 64) >>> 9) << 4) + 14] = len;
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
for(var i = 0; i < x.length; i += 16)
{
var olda = a;
var oldb = b;
var oldc = c;
var oldd = d;
a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819);
b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);
c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682);
d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329);
a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
c = md5_gg(c, d, a, b, x[i+11], 14, 643717713);
b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);
d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);
a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);
b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562);
b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);
c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174);
d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);
a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
c = md5_hh(c, d, a, b, x[i+15], 16, 530742520);
b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);
c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);
d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649);
a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);
b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
}
return Array(a, b, c, d);
}
/*
* These functions implement the four basic operations the algorithm uses.
*/
function md5_cmn(q, a, b, x, s, t)
{
return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t)
{
return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t)
{
return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t)
{
return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t)
{
return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}
/*
* Calculate the HMAC-MD5, of a key and some data
*/
function core_hmac_md5(key, data)
{
var bkey = str2binl(key);
if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz);
var ipad = Array(16), opad = Array(16);
for(var i = 0; i < 16; i++)
{
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5C5C5C5C;
}
var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
return core_md5(opad.concat(hash), 512 + 128);
}
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function safe_add(x, y)
{
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
function bit_rol(num, cnt)
{
return (num << cnt) | (num >>> (32 - cnt));
}
/*
* Convert a string to an array of little-endian words
* If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
keep
*/
function str2binl(str)
{
var bin = Array();
var mask = (1 << chrsz) - 1;
for(var i = 0; i < str.length * chrsz; i += chrsz)
bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
return bin;
}
/*
* Convert an array of little-endian words to a string
*/
function binl2str(bin)
{
var str = "";
var mask = (1 << chrsz) - 1;
for(var i = 0; i < bin.length * 32; i += chrsz)
str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);
return str;
}
/*
* Convert an array of little-endian words to a hex string.
keep
*/
function binl2hex(binarray)
{
var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
var str = "";
for(var i = 0; i < binarray.length * 4; i++)
{
str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF);
}
return str;
}
/*
* Convert an array of little-endian words to a base-64 string
*/
function binl2b64(binarray)
{
var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var str = "";
for(var i = 0; i < binarray.length * 4; i += 3)
{
var triplet = (((binarray[i >> 2] >> 8 * ( i %4)) & 0xFF) << 16)
| (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )
| ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
for(var j = 0; j < 4; j++)
{
if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
}
}
return str;
}
if (typeof exports != "undefined") {
exports.hex = hex_md5;
}

File diff suppressed because one or more lines are too long