updated all available javascript libraries to latest versions

pull/872/merge
Justin Richer 2015-07-10 16:01:41 -04:00
parent 99fbda3d13
commit 658b5e1456
12 changed files with 20947 additions and 9116 deletions

View File

@ -35,7 +35,7 @@
<!-- Load jQuery up here so that we can use in-page functions --> <!-- Load jQuery up here so that we can use in-page functions -->
<script type="text/javascript" src="resources/js/lib/jquery.js"></script> <script type="text/javascript" src="resources/js/lib/jquery.js"></script>
<script type="text/javascript" charset="UTF-8" src="resources/js/lib/moment-with-locales.js"></script> <script type="text/javascript" charset="UTF-8" src="resources/js/lib/moment-with-locales.js"></script>
<script type="text/javascript" src="resources/js/lib/i18next-1.7.7.js"></script> <script type="text/javascript" src="resources/js/lib/i18next.js"></script>
<script type="text/javascript"> <script type="text/javascript">
$.i18n.init({ $.i18n.init({
fallbackLng: "en", fallbackLng: "en",

View File

@ -20,6 +20,15 @@
(function(Backbone) { (function(Backbone) {
// Require Underscore and Backbone if there's a `require` function.
// This makes `backbone.validations` work on the server or when using
// `browserify`.
if (typeof require !== 'undefined') {
_ = require('underscore');
Backbone = require('backbone');
}
// Premade Validators // Premade Validators
Backbone.Validations = {}; Backbone.Validations = {};
@ -28,8 +37,8 @@ var validators = {
return model[methodName](attributeName, valueToSet); return model[methodName](attributeName, valueToSet);
}, },
"required" : function(attributeName, model, valueToSet) { "required" : function(isRequired, attributeName, model, valueToSet) {
if (_.isNull(valueToSet) || _.isUndefined(valueToSet) || valueToSet === "") { if (isRequired && (_.isNull(valueToSet) || _.isUndefined(valueToSet) || valueToSet === "")) {
return "required"; return "required";
} else { } else {
return false; return false;
@ -60,6 +69,18 @@ var validators = {
return isNaN(valueToSet) ? 'number' : undefined; return isNaN(valueToSet) ? 'number' : undefined;
}, },
"Array": function(type, attributeName, model, valueToSet) {
return _.isArray(valueToSet) ? undefined : 'Array';
},
"Boolean": function(type, attributeName, model, valueToSet) {
return _.isBoolean(valueToSet) ? undefined : 'Boolean';
},
"String": function(type, attributeName, model, valueToSet) {
return _.isString(valueToSet) ? undefined : 'String';
},
"digits": function (type, attributeName, model, valueToSet) { "digits": function (type, attributeName, model, valueToSet) {
var isBeingSet = !_.isUndefined(valueToSet); var isBeingSet = !_.isUndefined(valueToSet);
return (!/^\d+$/.test(valueToSet) && isBeingSet) ? 'digits' : undefined; return (!/^\d+$/.test(valueToSet) && isBeingSet) ? 'digits' : undefined;
@ -97,6 +118,12 @@ var validators = {
if (_.isString(valueToSet)) { if (_.isString(valueToSet)) {
if (valueToSet.length > maxlength) { return "maxlength"; } if (valueToSet.length > maxlength) { return "maxlength"; }
} }
},
"arrayElem": function(validator, attributeName, model, valueToSet) {
if (_.isArray(valueToSet) && !_.all(valueToSet, validator)) {
return "validElem";
} else return false;
} }
}; };
@ -183,13 +210,7 @@ function createValidator(attributeName, type, description) {
if (!validator) { throw "Improper validation type '"+type+"'" ; } if (!validator) { throw "Improper validation type '"+type+"'" ; }
if (type !== "required") { // doesn't need the description return _.bind(validator, null, description, attributeName);
validator = _.bind(validator, null, description, attributeName);
} else {
validator = _.bind(validator, null, attributeName);
}
return validator;
} }
function createAttributeValidator(attributeName, attributeDescription) { function createAttributeValidator(attributeName, attributeDescription) {
@ -239,22 +260,16 @@ function createValidators(modelValidations) {
return attributeValidators; return attributeValidators;
} }
var oldPerformValidation = Backbone.Model.prototype._performValidation; var oldValidate = Backbone.Model.prototype._validate;
function newPerformValidation(attrs, options) { function newPerformValidation(attrs, options) {
if (options.silent || !this.validate) return true; var result = oldValidate.apply(this, arguments);
var errors = this.validate(attrs);
if (errors) { if(!result){
if (options.error) { _.each(this.validationError, function(error, name) {
options.error(this, errors, options); this.trigger('invalid:' + name, this, this.validationError, options);
} else {
this.trigger('error', this, errors, options);
_.each(errors, function(error, name) {
this.trigger('error:' + name, this, errors, options);
}, this); }, this);
} }
return false; return result;
}
return true;
} }
// save the old backbone // save the old backbone
@ -285,4 +300,4 @@ Backbone.Validations.Model.noConflict = function() {
Backbone.Model = oldModel; Backbone.Model = oldModel;
}; };
}(Backbone)); }(typeof Backbone === 'undefined' ? null : Backbone));

View File

@ -2,7 +2,7 @@
* @preserve * @preserve
* bootpag - jQuery plugin for dynamic pagination * bootpag - jQuery plugin for dynamic pagination
* *
* Copyright (c) 2013 botmonster@7items.com * Copyright (c) 2015 botmonster@7items.com
* *
* Licensed under the MIT license: * Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php * http://www.opensource.org/licenses/mit-license.php
@ -10,7 +10,7 @@
* Project home: * Project home:
* http://botmonster.com/jquery-bootpag/ * http://botmonster.com/jquery-bootpag/
* *
* Version: 1.0.5 * Version: 1.0.7
* *
*/ */
(function($, window) { (function($, window) {
@ -26,7 +26,17 @@
href: 'javascript:void(0);', href: 'javascript:void(0);',
hrefVariable: '{{number}}', hrefVariable: '{{number}}',
next: '&raquo;', next: '&raquo;',
prev: '&laquo;' prev: '&laquo;',
firstLastUse: false,
first: '<span aria-hidden="true">&larr;</span>',
last: '<span aria-hidden="true">&rarr;</span>',
wrapClass: 'pagination',
activeClass: 'active',
disabledClass: 'disabled',
nextClass: 'next',
prevClass: 'prev',
lastClass: 'last',
firstClass: 'first'
}, },
$owner.data('settings') || {}, $owner.data('settings') || {},
options || {}); options || {});
@ -35,26 +45,38 @@
return this; return this;
if(!$.isNumeric(settings.maxVisible) && !settings.maxVisible){ if(!$.isNumeric(settings.maxVisible) && !settings.maxVisible){
settings.maxVisible = settings.total; settings.maxVisible = parseInt(settings.total, 10);
} }
$owner.data('settings', settings); $owner.data('settings', settings);
function renderPage($bootpag, page){ function renderPage($bootpag, page){
page = parseInt(page, 10);
var lp, var lp,
maxV = settings.maxVisible == 0 ? 1 : settings.maxVisible, maxV = settings.maxVisible == 0 ? 1 : settings.maxVisible,
step = settings.maxVisible == 1 ? 0 : 1, step = settings.maxVisible == 1 ? 0 : 1,
vis = Math.floor((page - 1) / maxV) * maxV, vis = Math.floor((page - 1) / maxV) * maxV,
$page = $bootpag.find('li'); $page = $bootpag.find('li');
settings.page = page = page < 0 ? 0 : page > settings.total ? settings.total : page; settings.page = page = page < 0 ? 0 : page > settings.total ? settings.total : page;
$page.removeClass('disabled'); $page.removeClass(settings.activeClass);
lp = page - 1 < 1 ? 1 : lp = page - 1 < 1 ? 1 :
settings.leaps && page - 1 >= settings.maxVisible ? settings.leaps && page - 1 >= settings.maxVisible ?
Math.floor((page - 1) / maxV) * maxV : page - 1; Math.floor((page - 1) / maxV) * maxV : page - 1;
if(settings.firstLastUse) {
$page $page
.first() .first()
.toggleClass('disabled', page === 1) .toggleClass(settings.disabledClass, page === 1);
}
var lfirst = $page.first();
if(settings.firstLastUse) {
lfirst = lfirst.next();
}
lfirst
.toggleClass(settings.disabledClass, page === 1)
.attr('data-lp', lp) .attr('data-lp', lp)
.find('a').attr('href', href(lp)); .find('a').attr('href', href(lp));
@ -64,16 +86,30 @@
settings.leaps && page + 1 < settings.total - settings.maxVisible ? settings.leaps && page + 1 < settings.total - settings.maxVisible ?
vis + settings.maxVisible + step: page + 1; vis + settings.maxVisible + step: page + 1;
var llast = $page.last();
if(settings.firstLastUse) {
llast = llast.prev();
}
llast
.toggleClass(settings.disabledClass, page === settings.total)
.attr('data-lp', lp)
.find('a').attr('href', href(lp));
$page $page
.last() .last()
.toggleClass('disabled', page === settings.total) .toggleClass(settings.disabledClass, page === settings.total);
.attr('data-lp', lp)
.find('a').attr('href', href(lp));;
var $currPage = $page.filter('[data-lp='+page+']'); var $currPage = $page.filter('[data-lp='+page+']');
if(!$currPage.not('.next,.prev').length){
var clist = "." + [settings.nextClass,
settings.prevClass,
settings.firstClass,
settings.lastClass].join(",.");
if(!$currPage.not(clist).length){
var d = page <= vis ? -settings.maxVisible : 0; var d = page <= vis ? -settings.maxVisible : 0;
$page.not('.next,.prev').each(function(index){ $page.not(clist).each(function(index){
lp = index + 1 + vis + d; lp = index + 1 + vis + d;
$(this) $(this)
.attr('data-lp', lp) .attr('data-lp', lp)
@ -82,7 +118,7 @@
}); });
$currPage = $page.filter('[data-lp='+page+']'); $currPage = $page.filter('[data-lp='+page+']');
} }
$currPage.addClass('disabled'); $currPage.not(clist).addClass(settings.activeClass);
$owner.data('settings', settings); $owner.data('settings', settings);
} }
@ -94,31 +130,46 @@
return this.each(function(){ return this.each(function(){
var $bootpag, lp, me = $(this), var $bootpag, lp, me = $(this),
p = ['<ul class="pagination bootpag">']; p = ['<ul class="', settings.wrapClass, ' bootpag">'];
if(settings.firstLastUse){
p = p.concat(['<li data-lp="1" class="', settings.firstClass,
'"><a href="', href(1), '">', settings.first, '</a></li>']);
}
if(settings.prev){ if(settings.prev){
p.push('<li data-lp="1" class="prev"><a href="'+href(1)+'">'+settings.prev+'</a></li>'); p = p.concat(['<li data-lp="1" class="', settings.prevClass,
'"><a href="', href(1), '">', settings.prev, '</a></li>']);
} }
for(var c = 1; c <= Math.min(settings.total, settings.maxVisible); c++){ for(var c = 1; c <= Math.min(settings.total, settings.maxVisible); c++){
p.push('<li data-lp="'+c+'"><a href="'+href(c)+'">'+c+'</a></li>'); p = p.concat(['<li data-lp="', c, '"><a href="', href(c), '">', c, '</a></li>']);
} }
if(settings.next){ if(settings.next){
lp = settings.leaps && settings.total > settings.maxVisible lp = settings.leaps && settings.total > settings.maxVisible
? Math.min(settings.maxVisible + 1, settings.total) : 2; ? Math.min(settings.maxVisible + 1, settings.total) : 2;
p.push('<li data-lp="'+lp+'" class="next"><a href="'+href(lp)+'">'+settings.next+'</a></li>'); p = p.concat(['<li data-lp="', lp, '" class="',
settings.nextClass, '"><a href="', href(lp),
'">', settings.next, '</a></li>']);
}
if(settings.firstLastUse){
p = p.concat(['<li data-lp="', settings.total, '" class="last"><a href="',
href(settings.total),'">', settings.last, '</a></li>']);
} }
p.push('</ul>'); p.push('</ul>');
me.find('ul.bootpag').remove(); me.find('ul.bootpag').remove();
me.append(p.join('')); me.append(p.join(''));
$bootpag = me.find('ul.bootpag'); $bootpag = me.find('ul.bootpag');
me.find('li').click(function paginationClick(){ me.find('li').click(function paginationClick(){
var me = $(this); var me = $(this);
if(me.hasClass('disabled')){ if(me.hasClass(settings.disabledClass) || me.hasClass(settings.activeClass)){
return; return;
} }
var page = parseInt(me.attr('data-lp'), 10); var page = parseInt(me.attr('data-lp'), 10);
renderPage($bootpag, page); $owner.find('ul.bootpag').each(function(){
renderPage($(this), page);
});
$owner.trigger('page', page); $owner.trigger('page', page);
}); });
renderPage($bootpag, settings.page); renderPage($bootpag, settings.page);

View File

@ -1,8 +1,322 @@
/* /**
HTML5 Shiv v3.7.0 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed * @preserve HTML5 Shiv 3.7.2 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed
*/ */
(function(l,f){function m(){var a=e.elements;return"string"==typeof a?a.split(" "):a}function i(a){var b=n[a[o]];b||(b={},h++,a[o]=h,n[h]=b);return b}function p(a,b,c){b||(b=f);if(g)return b.createElement(a);c||(c=i(b));b=c.cache[a]?c.cache[a].cloneNode():r.test(a)?(c.cache[a]=c.createElem(a)).cloneNode():c.createElem(a);return b.canHaveChildren&&!s.test(a)?c.frag.appendChild(b):b}function t(a,b){if(!b.cache)b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag(); ;(function(window, document) {
a.createElement=function(c){return!e.shivMethods?b.createElem(c):p(c,a,b)};a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+m().join().replace(/[\w\-]+/g,function(a){b.createElem(a);b.frag.createElement(a);return'c("'+a+'")'})+");return n}")(e,b.frag)}function q(a){a||(a=f);var b=i(a);if(e.shivCSS&&!j&&!b.hasCSS){var c,d=a;c=d.createElement("p");d=d.getElementsByTagName("head")[0]||d.documentElement;c.innerHTML="x<style>article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}template{display:none}</style>"; /*jshint evil:true */
c=d.insertBefore(c.lastChild,d.firstChild);b.hasCSS=!!c}g||t(a,b);return a}var k=l.html5||{},s=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,r=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,j,o="_html5shiv",h=0,n={},g;(function(){try{var a=f.createElement("a");a.innerHTML="<xyz></xyz>";j="hidden"in a;var b;if(!(b=1==a.childNodes.length)){f.createElement("a");var c=f.createDocumentFragment();b="undefined"==typeof c.cloneNode|| /** version */
"undefined"==typeof c.createDocumentFragment||"undefined"==typeof c.createElement}g=b}catch(d){g=j=!0}})();var e={elements:k.elements||"abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output progress section summary template time video",version:"3.7.0",shivCSS:!1!==k.shivCSS,supportsUnknownElements:g,shivMethods:!1!==k.shivMethods,type:"default",shivDocument:q,createElement:p,createDocumentFragment:function(a,b){a||(a=f); var version = '3.7.2';
if(g)return a.createDocumentFragment();for(var b=b||i(a),c=b.frag.cloneNode(),d=0,e=m(),h=e.length;d<h;d++)c.createElement(e[d]);return c}};l.html5=e;q(f)})(this,document);
/** Preset options */
var options = window.html5 || {};
/** Used to skip problem elements */
var reSkip = /^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i;
/** Not all elements can be cloned in IE **/
var saveClones = /^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i;
/** Detect whether the browser supports default html5 styles */
var supportsHtml5Styles;
/** Name of the expando, to work with multiple documents or to re-shiv one document */
var expando = '_html5shiv';
/** The id for the the documents expando */
var expanID = 0;
/** Cached data for each document */
var expandoData = {};
/** Detect whether the browser supports unknown elements */
var supportsUnknownElements;
(function() {
try {
var a = document.createElement('a');
a.innerHTML = '<xyz></xyz>';
//if the hidden property is implemented we can assume, that the browser supports basic HTML5 Styles
supportsHtml5Styles = ('hidden' in a);
supportsUnknownElements = a.childNodes.length == 1 || (function() {
// assign a false positive if unable to shiv
(document.createElement)('a');
var frag = document.createDocumentFragment();
return (
typeof frag.cloneNode == 'undefined' ||
typeof frag.createDocumentFragment == 'undefined' ||
typeof frag.createElement == 'undefined'
);
}());
} catch(e) {
// assign a false positive if detection fails => unable to shiv
supportsHtml5Styles = true;
supportsUnknownElements = true;
}
}());
/*--------------------------------------------------------------------------*/
/**
* Creates a style sheet with the given CSS text and adds it to the document.
* @private
* @param {Document} ownerDocument The document.
* @param {String} cssText The CSS text.
* @returns {StyleSheet} The style element.
*/
function addStyleSheet(ownerDocument, cssText) {
var p = ownerDocument.createElement('p'),
parent = ownerDocument.getElementsByTagName('head')[0] || ownerDocument.documentElement;
p.innerHTML = 'x<style>' + cssText + '</style>';
return parent.insertBefore(p.lastChild, parent.firstChild);
}
/**
* Returns the value of `html5.elements` as an array.
* @private
* @returns {Array} An array of shived element node names.
*/
function getElements() {
var elements = html5.elements;
return typeof elements == 'string' ? elements.split(' ') : elements;
}
/**
* Extends the built-in list of html5 elements
* @memberOf html5
* @param {String|Array} newElements whitespace separated list or array of new element names to shiv
* @param {Document} ownerDocument The context document.
*/
function addElements(newElements, ownerDocument) {
var elements = html5.elements;
if(typeof elements != 'string'){
elements = elements.join(' ');
}
if(typeof newElements != 'string'){
newElements = newElements.join(' ');
}
html5.elements = elements +' '+ newElements;
shivDocument(ownerDocument);
}
/**
* Returns the data associated to the given document
* @private
* @param {Document} ownerDocument The document.
* @returns {Object} An object of data.
*/
function getExpandoData(ownerDocument) {
var data = expandoData[ownerDocument[expando]];
if (!data) {
data = {};
expanID++;
ownerDocument[expando] = expanID;
expandoData[expanID] = data;
}
return data;
}
/**
* returns a shived element for the given nodeName and document
* @memberOf html5
* @param {String} nodeName name of the element
* @param {Document} ownerDocument The context document.
* @returns {Object} The shived element.
*/
function createElement(nodeName, ownerDocument, data){
if (!ownerDocument) {
ownerDocument = document;
}
if(supportsUnknownElements){
return ownerDocument.createElement(nodeName);
}
if (!data) {
data = getExpandoData(ownerDocument);
}
var node;
if (data.cache[nodeName]) {
node = data.cache[nodeName].cloneNode();
} else if (saveClones.test(nodeName)) {
node = (data.cache[nodeName] = data.createElem(nodeName)).cloneNode();
} else {
node = data.createElem(nodeName);
}
// Avoid adding some elements to fragments in IE < 9 because
// * Attributes like `name` or `type` cannot be set/changed once an element
// is inserted into a document/fragment
// * Link elements with `src` attributes that are inaccessible, as with
// a 403 response, will cause the tab/window to crash
// * Script elements appended to fragments will execute when their `src`
// or `text` property is set
return node.canHaveChildren && !reSkip.test(nodeName) && !node.tagUrn ? data.frag.appendChild(node) : node;
}
/**
* returns a shived DocumentFragment for the given document
* @memberOf html5
* @param {Document} ownerDocument The context document.
* @returns {Object} The shived DocumentFragment.
*/
function createDocumentFragment(ownerDocument, data){
if (!ownerDocument) {
ownerDocument = document;
}
if(supportsUnknownElements){
return ownerDocument.createDocumentFragment();
}
data = data || getExpandoData(ownerDocument);
var clone = data.frag.cloneNode(),
i = 0,
elems = getElements(),
l = elems.length;
for(;i<l;i++){
clone.createElement(elems[i]);
}
return clone;
}
/**
* Shivs the `createElement` and `createDocumentFragment` methods of the document.
* @private
* @param {Document|DocumentFragment} ownerDocument The document.
* @param {Object} data of the document.
*/
function shivMethods(ownerDocument, data) {
if (!data.cache) {
data.cache = {};
data.createElem = ownerDocument.createElement;
data.createFrag = ownerDocument.createDocumentFragment;
data.frag = data.createFrag();
}
ownerDocument.createElement = function(nodeName) {
//abort shiv
if (!html5.shivMethods) {
return data.createElem(nodeName);
}
return createElement(nodeName, ownerDocument, data);
};
ownerDocument.createDocumentFragment = Function('h,f', 'return function(){' +
'var n=f.cloneNode(),c=n.createElement;' +
'h.shivMethods&&(' +
// unroll the `createElement` calls
getElements().join().replace(/[\w\-:]+/g, function(nodeName) {
data.createElem(nodeName);
data.frag.createElement(nodeName);
return 'c("' + nodeName + '")';
}) +
');return n}'
)(html5, data.frag);
}
/*--------------------------------------------------------------------------*/
/**
* Shivs the given document.
* @memberOf html5
* @param {Document} ownerDocument The document to shiv.
* @returns {Document} The shived document.
*/
function shivDocument(ownerDocument) {
if (!ownerDocument) {
ownerDocument = document;
}
var data = getExpandoData(ownerDocument);
if (html5.shivCSS && !supportsHtml5Styles && !data.hasCSS) {
data.hasCSS = !!addStyleSheet(ownerDocument,
// corrects block display not defined in IE6/7/8/9
'article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}' +
// adds styling not present in IE6/7/8/9
'mark{background:#FF0;color:#000}' +
// hides non-rendered elements
'template{display:none}'
);
}
if (!supportsUnknownElements) {
shivMethods(ownerDocument, data);
}
return ownerDocument;
}
/*--------------------------------------------------------------------------*/
/**
* The `html5` object is exposed so that more elements can be shived and
* existing shiving can be detected on iframes.
* @type Object
* @example
*
* // options can be changed before the script is included
* html5 = { 'elements': 'mark section', 'shivCSS': false, 'shivMethods': false };
*/
var html5 = {
/**
* An array or space separated string of node names of the elements to shiv.
* @memberOf html5
* @type Array|String
*/
'elements': options.elements || 'abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output picture progress section summary template time video',
/**
* current version of html5shiv
*/
'version': version,
/**
* A flag to indicate that the HTML5 style sheet should be inserted.
* @memberOf html5
* @type Boolean
*/
'shivCSS': (options.shivCSS !== false),
/**
* Is equal to true if a browser supports creating unknown/HTML5 elements
* @memberOf html5
* @type boolean
*/
'supportsUnknownElements': supportsUnknownElements,
/**
* A flag to indicate that the document's `createElement` and `createDocumentFragment`
* methods should be overwritten.
* @memberOf html5
* @type Boolean
*/
'shivMethods': (options.shivMethods !== false),
/**
* A string to describe the type of `html5` object ("default" or "default print").
* @memberOf html5
* @type String
*/
'type': 'default',
// shivs the document according to the specified `html5` object options
'shivDocument': shivDocument,
//creates a shived element
createElement: createElement,
//creates a shived documentFragment
createDocumentFragment: createDocumentFragment,
//extends list of elements
addElements: addElements
};
/*--------------------------------------------------------------------------*/
// expose html5
window.html5 = html5;
// shiv the document
shivDocument(document);
}(this, document));

File diff suppressed because one or more lines are too long

View File

@ -1,8 +1,8 @@
// i18next, v1.7.7 // i18next, v1.10.1
// Copyright (c)2014 Jan Mühlemann (jamuhl). // Copyright (c)2015 Jan Mühlemann (jamuhl).
// Distributed under MIT license // Distributed under MIT license
// http://i18next.com // http://i18next.com
(function() { (function(root) {
// add indexOf to non ECMA-262 standard compliant browsers // add indexOf to non ECMA-262 standard compliant browsers
if (!Array.prototype.indexOf) { if (!Array.prototype.indexOf) {
@ -76,15 +76,15 @@
} }
} }
var root = this var $ = root.jQuery || root.Zepto
, $ = root.jQuery || root.Zepto
, i18n = {} , i18n = {}
, resStore = {} , resStore = {}
, currentLng , currentLng
, replacementCounter = 0 , replacementCounter = 0
, languages = [] , languages = []
, initialized = false , initialized = false
, sync = {}; , sync = {}
, conflictReference = null;
@ -92,23 +92,16 @@
// If we're not in CommonJS, add `i18n` to the // If we're not in CommonJS, add `i18n` to the
// global object or to jquery. // global object or to jquery.
if (typeof module !== 'undefined' && module.exports) { if (typeof module !== 'undefined' && module.exports) {
if (!$) {
try {
$ = require('jquery');
} catch(e) {
// just ignore
}
}
if ($) {
$.i18n = $.i18n || i18n;
}
module.exports = i18n; module.exports = i18n;
} else { } else {
if ($) { if ($) {
$.i18n = $.i18n || i18n; $.i18n = $.i18n || i18n;
} }
root.i18n = root.i18n || i18n; if (root.i18n) {
conflictReference = root.i18n;
}
root.i18n = i18n;
} }
sync = { sync = {
@ -125,15 +118,15 @@
f.extend(store, fetched); f.extend(store, fetched);
sync._storeLocal(fetched); sync._storeLocal(fetched);
cb(null, store); cb(err, store);
}); });
} else { } else {
cb(null, store); cb(err, store);
} }
}); });
} else { } else {
sync._fetch(lngs, options, function(err, store){ sync._fetch(lngs, options, function(err, store){
cb(null, store); cb(err, store);
}); });
} }
}, },
@ -147,7 +140,7 @@
var todo = lngs.length; var todo = lngs.length;
f.each(lngs, function(key, lng) { f.each(lngs, function(key, lng) {
var local = window.localStorage.getItem('res_' + lng); var local = f.localStorage.getItem('res_' + lng);
if (local) { if (local) {
local = JSON.parse(local); local = JSON.parse(local);
@ -210,7 +203,7 @@
} else { } else {
// Call this once our translation has returned. // Call this once our translation has returned.
var loadComplete = function(err, data) { var loadComplete = function(err, data) {
cb(null, data); cb(err, data);
}; };
if(typeof options.customLoad == 'function'){ if(typeof options.customLoad == 'function'){
@ -221,6 +214,7 @@
// load all needed stuff once // load all needed stuff once
f.ajax({ f.ajax({
url: url, url: url,
cache: options.cache,
success: function(data, status, xhr) { success: function(data, status, xhr) {
f.log('loaded: ' + url); f.log('loaded: ' + url);
loadComplete(null, data); loadComplete(null, data);
@ -230,7 +224,8 @@
loadComplete('failed loading resource.json error: ' + error); loadComplete('failed loading resource.json error: ' + error);
}, },
dataType: "json", dataType: "json",
async : options.getAsync async : options.getAsync,
timeout: options.ajaxTimeout
}); });
} }
} }
@ -240,6 +235,7 @@
var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns }); var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
f.ajax({ f.ajax({
url: url, url: url,
cache: options.cache,
success: function(data, status, xhr) { success: function(data, status, xhr) {
f.log('loaded: ' + url); f.log('loaded: ' + url);
done(null, data); done(null, data);
@ -258,7 +254,8 @@
done(error, {}); done(error, {});
}, },
dataType: "json", dataType: "json",
async : options.getAsync async : options.getAsync,
timeout: options.ajaxTimeout
}); });
}, },
@ -306,7 +303,8 @@
f.log('failed posting missing key \'' + key + '\' to: ' + item.url); f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
}, },
dataType: "json", dataType: "json",
async : o.postAsync async : o.postAsync,
timeout: o.ajaxTimeout
}); });
} }
}, },
@ -324,10 +322,14 @@
fallbackNS: [], fallbackNS: [],
detectLngQS: 'setLng', detectLngQS: 'setLng',
detectLngFromLocalStorage: false, detectLngFromLocalStorage: false,
ns: 'translation', ns: {
namespaces: ['translation'],
defaultNs: 'translation'
},
fallbackOnNull: true, fallbackOnNull: true,
fallbackOnEmpty: false, fallbackOnEmpty: false,
fallbackToDefaultNS: false, fallbackToDefaultNS: false,
showKeyIfEmpty: false,
nsseparator: ':', nsseparator: ':',
keyseparator: '.', keyseparator: '.',
selectorAttr: 'data-i18n', selectorAttr: 'data-i18n',
@ -372,6 +374,7 @@
postProcess: undefined, postProcess: undefined,
parseMissingKey: undefined, parseMissingKey: undefined,
missingKeyHandler: sync.postMissing, missingKeyHandler: sync.postMissing,
ajaxTimeout: 0,
shortcutFunction: 'sprintf' // or: defaultValue shortcutFunction: 'sprintf' // or: defaultValue
}; };
@ -805,9 +808,13 @@
if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1; if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
return lng_index; return lng_index;
}, },
toLanguages: function(lng) { toLanguages: function(lng, fallbackLng) {
var log = this.log; var log = this.log;
fallbackLng = fallbackLng || o.fallbackLng;
if (typeof fallbackLng === 'string')
fallbackLng = [fallbackLng];
function applyCase(l) { function applyCase(l) {
var ret = l; var ret = l;
@ -843,8 +850,8 @@
addLanguage(applyCase(lng)); addLanguage(applyCase(lng));
} }
for (var i = 0; i < o.fallbackLng.length; i++) { for (var i = 0; i < fallbackLng.length; i++) {
if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i])); if (languages.indexOf(fallbackLng[i]) === -1 && fallbackLng[i]) languages.push(applyCase(fallbackLng[i]));
} }
return languages; return languages;
}, },
@ -867,6 +874,16 @@
f.log('failed to set value for key "' + key + '" to localStorage.'); f.log('failed to set value for key "' + key + '" to localStorage.');
} }
} }
},
getItem: function(key, value) {
if (window.localStorage) {
try {
return window.localStorage.getItem(key, value);
} catch (e) {
f.log('failed to get value for key "' + key + '" from localStorage.');
return undefined;
}
}
} }
} }
}; };
@ -933,7 +950,11 @@
pluralExtensions.setCurrentLng(currentLng); pluralExtensions.setCurrentLng(currentLng);
// add JQuery extensions // add JQuery extensions
if ($ && o.setJqueryExt) addJqueryFunct(); if ($ && o.setJqueryExt) {
addJqueryFunct && addJqueryFunct();
} else {
addJqueryLikeFunctionality && addJqueryLikeFunctionality();
}
// jQuery deferred // jQuery deferred
var deferred; var deferred;
@ -968,12 +989,16 @@
resStore = store; resStore = store;
initialized = true; initialized = true;
if (cb) cb(lngTranslate); if (cb) cb(err, lngTranslate);
if (deferred) deferred.resolve(lngTranslate); if (deferred) (!err ? deferred.resolve : deferred.reject)(err || lngTranslate);
}); });
if (deferred) return deferred.promise(); if (deferred) return deferred.promise();
} }
function isInitialized() {
return initialized;
}
function preload(lngs, cb) { function preload(lngs, cb) {
if (typeof lngs === 'string') lngs = [lngs]; if (typeof lngs === 'string') lngs = [lngs];
for (var i = 0, l = lngs.length; i < l; i++) { for (var i = 0, l = lngs.length; i < l; i++) {
@ -1000,6 +1025,9 @@
} else { } else {
f.extend(resStore[lng][ns], resources); f.extend(resStore[lng][ns], resources);
} }
if (o.useLocalStorage) {
sync._storeLocal(resStore);
}
} }
function hasResourceBundle(lng, ns) { function hasResourceBundle(lng, ns) {
@ -1020,6 +1048,15 @@
return hasValues; return hasValues;
} }
function getResourceBundle(lng, ns) {
if (typeof ns !== 'string') {
ns = o.ns.defaultNs;
}
resStore[lng] = resStore[lng] || {};
return f.extend({}, resStore[lng][ns]);
}
function removeResourceBundle(lng, ns) { function removeResourceBundle(lng, ns) {
if (typeof ns !== 'string') { if (typeof ns !== 'string') {
ns = o.ns.defaultNs; ns = o.ns.defaultNs;
@ -1027,6 +1064,9 @@
resStore[lng] = resStore[lng] || {}; resStore[lng] = resStore[lng] || {};
resStore[lng][ns] = {}; resStore[lng][ns] = {};
if (o.useLocalStorage) {
sync._storeLocal(resStore);
}
} }
function addResource(lng, ns, key, value) { function addResource(lng, ns, key, value) {
@ -1056,6 +1096,9 @@
} }
x++; x++;
} }
if (o.useLocalStorage) {
sync._storeLocal(resStore);
}
} }
function addResources(lng, ns, resources) { function addResources(lng, ns, resources) {
@ -1165,6 +1208,17 @@
resStore = {}; resStore = {};
setLng(currentLng, cb); setLng(currentLng, cb);
} }
function noConflict() {
window.i18next = window.i18n;
if (conflictReference) {
window.i18n = conflictReference;
} else {
delete window.i18n;
}
}
function addJqueryFunct() { function addJqueryFunct() {
// $.t shortcut // $.t shortcut
$.t = $.t || translate; $.t = $.t || translate;
@ -1255,6 +1309,69 @@
}); });
}; };
} }
function addJqueryLikeFunctionality() {
function parse(ele, key, options) {
if (key.length === 0) return;
var attr = 'text';
if (key.indexOf('[') === 0) {
var parts = key.split(']');
key = parts[1];
attr = parts[0].substr(1, parts[0].length-1);
}
if (key.indexOf(';') === key.length-1) {
key = key.substr(0, key.length-2);
}
if (attr === 'html') {
ele.innerHTML = translate(key, options);
} else if (attr === 'text') {
ele.textContent = translate(key, options);
} else if (attr === 'prepend') {
ele.insertAdjacentHTML(translate(key, options), 'afterbegin');
} else if (attr === 'append') {
ele.insertAdjacentHTML(translate(key, options), 'beforeend');
} else {
ele.setAttribute(attr, translate(key, options));
}
}
function localize(ele, options) {
var key = ele.getAttribute(o.selectorAttr);
if (!key && typeof key !== 'undefined' && key !== false) key = ele.textContent || ele.value;
if (!key) return;
var target = ele
, targetSelector = ele.getAttribute("i18n-target");
if (targetSelector) {
target = ele.querySelector(targetSelector) || ele;
}
if (key.indexOf(';') >= 0) {
var keys = key.split(';'), index = 0, length = keys.length;
for ( ; index < length; index++) {
if (keys[index] !== '') parse(target, keys[index], options);
}
} else {
parse(target, key, options);
}
}
// fn
i18n.translateObject = function (object, options) {
// localize childs
var elements = object.querySelectorAll('[' + o.selectorAttr + ']');
var index = 0, length = elements.length;
for ( ; index < length; index++) {
localize(elements[index], options);
}
};
}
function applyReplacement(str, replacementHash, nestedKey, options) { function applyReplacement(str, replacementHash, nestedKey, options) {
if (!str) return str; if (!str) return str;
@ -1397,6 +1514,10 @@
if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return ''; if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
if (typeof potentialKeys === 'number') {
potentialKeys = String(potentialKeys);
}
if (typeof potentialKeys === 'string') { if (typeof potentialKeys === 'string') {
potentialKeys = [potentialKeys]; potentialKeys = [potentialKeys];
} }
@ -1433,11 +1554,27 @@
} }
} }
var postProcessor = options.postProcess || o.postProcess; var postProcessorsToApply;
if (found !== undefined && postProcessor) { if (typeof o.postProcess === 'string' && o.postProcess !== '') {
postProcessorsToApply = [o.postProcess];
} else if (typeof o.postProcess === 'array' || typeof o.postProcess === 'object') {
postProcessorsToApply = o.postProcess;
} else {
postProcessorsToApply = [];
}
if (typeof options.postProcess === 'string' && options.postProcess !== '') {
postProcessorsToApply = postProcessorsToApply.concat([options.postProcess]);
} else if (typeof options.postProcess === 'array' || typeof options.postProcess === 'object') {
postProcessorsToApply = postProcessorsToApply.concat(options.postProcess);
}
if (found !== undefined && postProcessorsToApply.length) {
postProcessorsToApply.forEach(function(postProcessor) {
if (postProcessors[postProcessor]) { if (postProcessors[postProcessor]) {
found = postProcessors[postProcessor](found, key, options); found = postProcessors[postProcessor](found, key, options);
} }
});
} }
// process notFound if function exists // process notFound if function exists
@ -1454,10 +1591,14 @@
notFound = applyReplacement(notFound, options); notFound = applyReplacement(notFound, options);
notFound = applyReuse(notFound, options); notFound = applyReuse(notFound, options);
if (postProcessor && postProcessors[postProcessor]) { if (postProcessorsToApply.length) {
var val = _getDefaultValue(key, options); var val = _getDefaultValue(key, options);
postProcessorsToApply.forEach(function(postProcessor) {
if (postProcessors[postProcessor]) {
found = postProcessors[postProcessor](val, key, options); found = postProcessors[postProcessor](val, key, options);
} }
});
}
} }
return (found !== undefined) ? found : notFound; return (found !== undefined) ? found : notFound;
@ -1514,6 +1655,7 @@
if (needsPlural(options, lngs[0])) { if (needsPlural(options, lngs[0])) {
optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options); optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
delete optionWithoutCount.count; delete optionWithoutCount.count;
optionWithoutCount._origLng = optionWithoutCount._origLng || optionWithoutCount.lng || lngs[0];
delete optionWithoutCount.lng; delete optionWithoutCount.lng;
optionWithoutCount.defaultValue = o.pluralNotFound; optionWithoutCount.defaultValue = o.pluralNotFound;
@ -1543,12 +1685,21 @@
var clone = lngs.slice(); var clone = lngs.slice();
clone.shift(); clone.shift();
options = f.extend(options, { lngs: clone }); options = f.extend(options, { lngs: clone });
options._origLng = optionWithoutCount._origLng;
delete options.lng; delete options.lng;
// retry with fallbacks // retry with fallbacks
translated = translate(ns + o.nsseparator + key, options); translated = translate(ns + o.nsseparator + key, options);
if (translated != o.pluralNotFound) return translated; if (translated != o.pluralNotFound) return translated;
} else { } else {
return translated; optionWithoutCount.lng = optionWithoutCount._origLng;
delete optionWithoutCount._origLng;
translated = translate(ns + o.nsseparator + key, optionWithoutCount);
return applyReplacement(translated, {
count: options.count,
interpolationPrefix: options.interpolationPrefix,
interpolationSuffix: options.interpolationSuffix
});
} }
} }
@ -1577,7 +1728,7 @@
value = value && value[keys[x]]; value = value && value[keys[x]];
x++; x++;
} }
if (value !== undefined) { if (value !== undefined && (!o.showKeyIfEmpty || value !== '')) {
var valueType = Object.prototype.toString.apply(value); var valueType = Object.prototype.toString.apply(value);
if (typeof value === 'string') { if (typeof value === 'string') {
value = applyReplacement(value, options); value = applyReplacement(value, options);
@ -1631,6 +1782,7 @@
} }
} }
} else { } else {
options.ns = o.ns.defaultNs;
found = _find(key, options); // fallback to default NS found = _find(key, options); // fallback to default NS
} }
options.isFallbackLookup = false; options.isFallbackLookup = false;
@ -1669,7 +1821,10 @@
// get from localStorage // get from localStorage
if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) { if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
userLngChoices.push(window.localStorage.getItem('i18next_lng')); var lang = f.localStorage.getItem('i18next_lng');
if (lang) {
userLngChoices.push(lang);
}
} }
// get from navigator // get from navigator
@ -2098,10 +2253,12 @@
}); });
// public api interface // public api interface
i18n.init = init; i18n.init = init;
i18n.isInitialized = isInitialized;
i18n.setLng = setLng; i18n.setLng = setLng;
i18n.preload = preload; i18n.preload = preload;
i18n.addResourceBundle = addResourceBundle; i18n.addResourceBundle = addResourceBundle;
i18n.hasResourceBundle = hasResourceBundle; i18n.hasResourceBundle = hasResourceBundle;
i18n.getResourceBundle = getResourceBundle;
i18n.addResource = addResource; i18n.addResource = addResource;
i18n.addResources = addResources; i18n.addResources = addResources;
i18n.removeResourceBundle = removeResourceBundle; i18n.removeResourceBundle = removeResourceBundle;
@ -2117,6 +2274,8 @@
i18n.functions = f; i18n.functions = f;
i18n.lng = lng; i18n.lng = lng;
i18n.addPostProcessor = addPostProcessor; i18n.addPostProcessor = addPostProcessor;
i18n.applyReplacement = f.applyReplacement;
i18n.options = o; i18n.options = o;
i18n.noConflict = noConflict;
})(); })(typeof exports === 'undefined' ? window : exports);

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@ -1,5 +1,5 @@
/* /*
* JQuery URL Parser plugin, v2.2.1 * Purl (A JavaScript URL parser) v2.3.1
* Developed and maintanined by Mark Perkins, mark@allmarkedup.com * Developed and maintanined by Mark Perkins, mark@allmarkedup.com
* Source repository: https://github.com/allmarkedup/jQuery-URL-Parser * Source repository: https://github.com/allmarkedup/jQuery-URL-Parser
* Licensed under an MIT-style license. See https://github.com/allmarkedup/jQuery-URL-Parser/blob/master/LICENSE for details. * Licensed under an MIT-style license. See https://github.com/allmarkedup/jQuery-URL-Parser/blob/master/LICENSE for details.
@ -7,21 +7,11 @@
;(function(factory) { ;(function(factory) {
if (typeof define === 'function' && define.amd) { if (typeof define === 'function' && define.amd) {
// AMD available; use anonymous module define(factory);
if ( typeof jQuery !== 'undefined' ) {
define(['jquery'], factory);
} else { } else {
define([], factory); window.purl = factory();
} }
} else { })(function() {
// No AMD available; mutate global vars
if ( typeof jQuery !== 'undefined' ) {
factory(jQuery);
} else {
factory();
}
}
})(function($, undefined) {
var tag2attr = { var tag2attr = {
a : 'href', a : 'href',
@ -30,7 +20,9 @@
base : 'href', base : 'href',
script : 'src', script : 'src',
iframe : 'src', iframe : 'src',
link : 'href' link : 'href',
embed : 'src',
object : 'data'
}, },
key = ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'fragment'], // keys available to query key = ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'fragment'], // keys available to query
@ -42,8 +34,6 @@
loose : /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ // more intuitive, fails on relative paths and deviates from specs loose : /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ // more intuitive, fails on relative paths and deviates from specs
}, },
toString = Object.prototype.toString,
isint = /^[0-9]+$/; isint = /^[0-9]+$/;
function parseUri( url, strictMode ) { function parseUri( url, strictMode ) {
@ -68,7 +58,7 @@
uri.attr['base'] = uri.attr.host ? (uri.attr.protocol ? uri.attr.protocol+'://'+uri.attr.host : uri.attr.host) + (uri.attr.port ? ':'+uri.attr.port : '') : ''; uri.attr['base'] = uri.attr.host ? (uri.attr.protocol ? uri.attr.protocol+'://'+uri.attr.host : uri.attr.host) + (uri.attr.port ? ':'+uri.attr.port : '') : '';
return uri; return uri;
}; }
function getAttrName( elm ) { function getAttrName( elm ) {
var tn = elm.tagName; var tn = elm.tagName;
@ -77,7 +67,7 @@
} }
function promote(parent, key) { function promote(parent, key) {
if (parent[key].length == 0) return parent[key] = {}; if (parent[key].length === 0) return parent[key] = {};
var t = {}; var t = {};
for (var i in parent[key]) t[i] = parent[key][i]; for (var i in parent[key]) t[i] = parent[key][i];
parent[key] = t; parent[key] = t;
@ -100,7 +90,7 @@
var obj = parent[key] = parent[key] || []; var obj = parent[key] = parent[key] || [];
if (']' == part) { if (']' == part) {
if (isArray(obj)) { if (isArray(obj)) {
if ('' != val) obj.push(val); if ('' !== val) obj.push(val);
} else if ('object' == typeof obj) { } else if ('object' == typeof obj) {
obj[keys(obj).length] = val; obj[keys(obj).length] = val;
} else { } else {
@ -120,9 +110,7 @@
function merge(parent, key, val) { function merge(parent, key, val) {
if (~key.indexOf(']')) { if (~key.indexOf(']')) {
var parts = key.split('['), var parts = key.split('[');
len = parts.length,
last = len - 1;
parse(parts, parent, 'base', val); parse(parts, parent, 'base', val);
} else { } else {
if (!isint.test(key) && isArray(parent.base)) { if (!isint.test(key) && isArray(parent.base)) {
@ -130,8 +118,10 @@
for (var k in parent.base) t[k] = parent.base[k]; for (var k in parent.base) t[k] = parent.base[k];
parent.base = t; parent.base = t;
} }
if (key !== '') {
set(parent.base, key, val); set(parent.base, key, val);
} }
}
return parent; return parent;
} }
@ -145,10 +135,14 @@
var eql = pair.indexOf('='), var eql = pair.indexOf('='),
brace = lastBraceInKey(pair), brace = lastBraceInKey(pair),
key = pair.substr(0, brace || eql), key = pair.substr(0, brace || eql),
val = pair.substr(brace || eql, pair.length), val = pair.substr(brace || eql, pair.length);
val = val.substr(val.indexOf('=') + 1, val.length); val = val.substr(val.indexOf('=') + 1, val.length);
if ('' == key) key = pair, val = ''; if (key === '') {
key = pair;
val = '';
}
return merge(ret, key, val); return merge(ret, key, val);
}, { base: {} }).base; }, { base: {} }).base;
@ -156,7 +150,7 @@
function set(obj, key, val) { function set(obj, key, val) {
var v = obj[key]; var v = obj[key];
if (undefined === v) { if (typeof v === 'undefined') {
obj[key] = val; obj[key] = val;
} else if (isArray(v)) { } else if (isArray(v)) {
v.push(val); v.push(val);
@ -167,7 +161,8 @@
function lastBraceInKey(str) { function lastBraceInKey(str) {
var len = str.length, var len = str.length,
brace, c; brace,
c;
for (var i = 0; i < len; ++i) { for (var i = 0; i < len; ++i) {
c = str[i]; c = str[i];
if (']' == c) brace = false; if (']' == c) brace = false;
@ -192,11 +187,11 @@
} }
function keys(obj) { function keys(obj) {
var keys = []; var key_array = [];
for ( prop in obj ) { for ( var prop in obj ) {
if ( obj.hasOwnProperty(prop) ) keys.push(prop); if ( obj.hasOwnProperty(prop) ) key_array.push(prop);
} }
return keys; return key_array;
} }
function purl( url, strictMode ) { function purl( url, strictMode ) {
@ -249,10 +244,10 @@
}; };
}; }
if ( typeof $ !== 'undefined' ) {
purl.jQuery = function($){
if ($ != null) {
$.fn.url = function( strictMode ) { $.fn.url = function( strictMode ) {
var url = ''; var url = '';
if ( this.length ) { if ( this.length ) {
@ -262,10 +257,11 @@
}; };
$.url = purl; $.url = purl;
} else {
window.purl = purl;
} }
};
purl.jQuery(window.jQuery);
return purl;
}); });

View File

@ -1,7 +1,19 @@
(function() { /*!
var root = (typeof exports == 'undefined' ? window : exports); * Retina.js v1.3.0
*
* Copyright 2014 Imulus, LLC
* Released under the MIT license
*
* Retina.js is an open source script that makes it easy to serve
* high-resolution images to devices with retina displays.
*/
(function() {
var root = (typeof exports === 'undefined' ? window : exports);
var config = { var config = {
// An option to choose a suffix for 2x images
retinaImageSuffix : '@2x',
// Ensure Content-Type is an image before trying to load @2x image // Ensure Content-Type is an image before trying to load @2x image
// https://github.com/imulus/retinajs/pull/45) // https://github.com/imulus/retinajs/pull/45)
check_mime_type: true, check_mime_type: true,
@ -11,85 +23,109 @@
force_original_dimensions: true force_original_dimensions: true
}; };
root.Retina = Retina;
function Retina() {} function Retina() {}
root.Retina = Retina;
Retina.configure = function(options) { Retina.configure = function(options) {
if (options == null) options = {}; if (options === null) {
for (var prop in options) config[prop] = options[prop]; options = {};
}
for (var prop in options) {
if (options.hasOwnProperty(prop)) {
config[prop] = options[prop];
}
}
}; };
Retina.init = function(context) { Retina.init = function(context) {
if (context == null) context = root; if (context === null) {
context = root;
}
var existing_onload = context.onload || new Function; var existing_onload = context.onload || function(){};
context.onload = function() { context.onload = function() {
var images = document.getElementsByTagName("img"), retinaImages = [], i, image; var images = document.getElementsByTagName('img'), retinaImages = [], i, image;
for (i = 0; i < images.length; i++) { for (i = 0; i < images.length; i += 1) {
image = images[i]; image = images[i];
if (!!!image.getAttributeNode('data-no-retina')) {
retinaImages.push(new RetinaImage(image)); retinaImages.push(new RetinaImage(image));
} }
existing_onload();
} }
existing_onload();
};
}; };
Retina.isRetina = function(){ Retina.isRetina = function(){
var mediaQuery = "(-webkit-min-device-pixel-ratio: 1.5),\ var mediaQuery = '(-webkit-min-device-pixel-ratio: 1.5), (min--moz-device-pixel-ratio: 1.5), (-o-min-device-pixel-ratio: 3/2), (min-resolution: 1.5dppx)';
(min--moz-device-pixel-ratio: 1.5),\
(-o-min-device-pixel-ratio: 3/2),\
(min-resolution: 1.5dppx)";
if (root.devicePixelRatio > 1) if (root.devicePixelRatio > 1) {
return true; return true;
}
if (root.matchMedia && root.matchMedia(mediaQuery).matches) if (root.matchMedia && root.matchMedia(mediaQuery).matches) {
return true; return true;
}
return false; return false;
}; };
root.RetinaImagePath = RetinaImagePath; var regexMatch = /\.\w+$/;
function suffixReplace (match) {
return config.retinaImageSuffix + match;
}
function RetinaImagePath(path, at_2x_path) { function RetinaImagePath(path, at_2x_path) {
this.path = path; this.path = path || '';
if (typeof at_2x_path !== "undefined" && at_2x_path !== null) { if (typeof at_2x_path !== 'undefined' && at_2x_path !== null) {
this.at_2x_path = at_2x_path; this.at_2x_path = at_2x_path;
this.perform_check = false; this.perform_check = false;
} else { } else {
this.at_2x_path = path.replace(/\.\w+$/, function(match) { return "@2x" + match; }); if (undefined !== document.createElement) {
var locationObject = document.createElement('a');
locationObject.href = this.path;
locationObject.pathname = locationObject.pathname.replace(regexMatch, suffixReplace);
this.at_2x_path = locationObject.href;
} else {
var parts = this.path.split('?');
parts[0] = parts[0].replace(regexMatch, suffixReplace);
this.at_2x_path = parts.join('?');
}
this.perform_check = true; this.perform_check = true;
} }
} }
root.RetinaImagePath = RetinaImagePath;
RetinaImagePath.confirmed_paths = []; RetinaImagePath.confirmed_paths = [];
RetinaImagePath.prototype.is_external = function() { RetinaImagePath.prototype.is_external = function() {
return !!(this.path.match(/^https?\:/i) && !this.path.match('//' + document.domain) ) return !!(this.path.match(/^https?\:/i) && !this.path.match('//' + document.domain) );
} };
RetinaImagePath.prototype.check_2x_variant = function(callback) { RetinaImagePath.prototype.check_2x_variant = function(callback) {
var http, that = this; var http, that = this;
if (this.is_external()) { if (this.is_external()) {
return callback(false); return callback(false);
} else if (!this.perform_check && typeof this.at_2x_path !== "undefined" && this.at_2x_path !== null) { } else if (!this.perform_check && typeof this.at_2x_path !== 'undefined' && this.at_2x_path !== null) {
return callback(true); return callback(true);
} else if (this.at_2x_path in RetinaImagePath.confirmed_paths) { } else if (this.at_2x_path in RetinaImagePath.confirmed_paths) {
return callback(true); return callback(true);
} else { } else {
http = new XMLHttpRequest; http = new XMLHttpRequest();
http.open('GET', this.at_2x_path); http.open('GET', this.at_2x_path); // local patch HEAD->GET, play nice with firefox
http.onreadystatechange = function() { http.onreadystatechange = function() {
if (http.readyState != 4) { if (http.readyState !== 4) {
return callback(false); return callback(false);
} }
if (http.status >= 200 && http.status <= 399) { if (http.status >= 200 && http.status <= 399) {
if (config.check_mime_type) { if (config.check_mime_type) {
var type = http.getResponseHeader('Content-Type'); var type = http.getResponseHeader('Content-Type');
if (type == null || !type.match(/^image/i)) { if (type === null || !type.match(/^image/i)) {
return callback(false); return callback(false);
} }
} }
@ -99,11 +135,10 @@
} else { } else {
return callback(false); return callback(false);
} }
} };
http.send(); http.send();
} }
} };
function RetinaImage(el) { function RetinaImage(el) {
@ -111,14 +146,18 @@
this.path = new RetinaImagePath(this.el.getAttribute('src'), this.el.getAttribute('data-at2x')); this.path = new RetinaImagePath(this.el.getAttribute('src'), this.el.getAttribute('data-at2x'));
var that = this; var that = this;
this.path.check_2x_variant(function(hasVariant) { this.path.check_2x_variant(function(hasVariant) {
if (hasVariant) that.swap(); if (hasVariant) {
that.swap();
}
}); });
} }
root.RetinaImage = RetinaImage; root.RetinaImage = RetinaImage;
RetinaImage.prototype.swap = function(path) { RetinaImage.prototype.swap = function(path) {
if (typeof path == 'undefined') path = this.path.at_2x_path; if (typeof path === 'undefined') {
path = this.path.at_2x_path;
}
var that = this; var that = this;
function load() { function load() {
@ -134,14 +173,10 @@
} }
} }
load(); load();
} };
if (Retina.isRetina()) { if (Retina.isRetina()) {
Retina.init(root); Retina.init(root);
} }
})(); })();