Inseriti script x gestione globalizzazione!!! ok su chrome...

This commit is contained in:
Samuele E. Locatelli
2016-09-26 18:14:32 +02:00
parent 8c60d620f9
commit cca99eeca6
40 changed files with 17302 additions and 3 deletions
+11 -1
View File
@@ -16,7 +16,16 @@ namespace StockManMVC
));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
"~/Scripts/jquery.validate.js",
"~/Scripts/cldr.js",
"~/Scripts/cldr/event.js",
"~/Scripts/cldr/supplemental.js",
"~/Scripts/globalize.js",
"~/Scripts/globalize/number.js",
"~/Scripts/globalize/date.js",
//"~/Scripts/jquery.validate.unobtrusive.js",
"~/Scripts/jquery.validate.globalize.js"
));
//// bootgrid!
//bundles.Add(new ScriptBundle("~/bundles/jqbootgrid").Include(
@@ -41,3 +50,4 @@ namespace StockManMVC
}
}
}
+1
View File
@@ -39,6 +39,7 @@ namespace StockManMVC.Models
public string Qta;
[Display(Name = "Importo")]
[Range(0.1D, 99.9D)]
public string TotValue;
}
Binary file not shown.
+676
View File
@@ -0,0 +1,676 @@
/**
* CLDR JavaScript Library v0.4.4
* http://jquery.com/
*
* Copyright 2013 Rafael Xavier de Souza
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2016-01-18T12:25Z
*/
/*!
* CLDR JavaScript Library v0.4.4 2016-01-18T12:25Z MIT license © Rafael Xavier
* http://git.io/h4lmVg
*/
(function( root, factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD.
define( factory );
} else if ( typeof module === "object" && typeof module.exports === "object" ) {
// Node. CommonJS.
module.exports = factory();
} else {
// Global
root.Cldr = factory();
}
}( this, function() {
var arrayIsArray = Array.isArray || function( obj ) {
return Object.prototype.toString.call( obj ) === "[object Array]";
};
var pathNormalize = function( path, attributes ) {
if ( arrayIsArray( path ) ) {
path = path.join( "/" );
}
if ( typeof path !== "string" ) {
throw new Error( "invalid path \"" + path + "\"" );
}
// 1: Ignore leading slash `/`
// 2: Ignore leading `cldr/`
path = path
.replace( /^\// , "" ) /* 1 */
.replace( /^cldr\// , "" ); /* 2 */
// Replace {attribute}'s
path = path.replace( /{[a-zA-Z]+}/g, function( name ) {
name = name.replace( /^{([^}]*)}$/, "$1" );
return attributes[ name ];
});
return path.split( "/" );
};
var arraySome = function( array, callback ) {
var i, length;
if ( array.some ) {
return array.some( callback );
}
for ( i = 0, length = array.length; i < length; i++ ) {
if ( callback( array[ i ], i, array ) ) {
return true;
}
}
return false;
};
/**
* Return the maximized language id as defined in
* http://www.unicode.org/reports/tr35/#Likely_Subtags
* 1. Canonicalize.
* 1.1 Make sure the input locale is in canonical form: uses the right
* separator, and has the right casing.
* TODO Right casing? What df? It seems languages are lowercase, scripts are
* Capitalized, territory is uppercase. I am leaving this as an exercise to
* the user.
*
* 1.2 Replace any deprecated subtags with their canonical values using the
* <alias> data in supplemental metadata. Use the first value in the
* replacement list, if it exists. Language tag replacements may have multiple
* parts, such as "sh" ➞ "sr_Latn" or mo" ➞ "ro_MD". In such a case, the
* original script and/or region are retained if there is one. Thus
* "sh_Arab_AQ" ➞ "sr_Arab_AQ", not "sr_Latn_AQ".
* TODO What <alias> data?
*
* 1.3 If the tag is grandfathered (see <variable id="$grandfathered"
* type="choice"> in the supplemental data), then return it.
* TODO grandfathered?
*
* 1.4 Remove the script code 'Zzzz' and the region code 'ZZ' if they occur.
* 1.5 Get the components of the cleaned-up source tag (languages, scripts,
* and regions), plus any variants and extensions.
* 2. Lookup. Lookup each of the following in order, and stop on the first
* match:
* 2.1 languages_scripts_regions
* 2.2 languages_regions
* 2.3 languages_scripts
* 2.4 languages
* 2.5 und_scripts
* 3. Return
* 3.1 If there is no match, either return an error value, or the match for
* "und" (in APIs where a valid language tag is required).
* 3.2 Otherwise there is a match = languagem_scriptm_regionm
* 3.3 Let xr = xs if xs is not empty, and xm otherwise.
* 3.4 Return the language tag composed of languager _ scriptr _ regionr +
* variants + extensions.
*
* @subtags [Array] normalized language id subtags tuple (see init.js).
*/
var coreLikelySubtags = function( Cldr, cldr, subtags, options ) {
var match, matchFound,
language = subtags[ 0 ],
script = subtags[ 1 ],
sep = Cldr.localeSep,
territory = subtags[ 2 ],
variantsAndUnicodeLocaleExtensions = subtags.slice( 3, 4 );
options = options || {};
// Skip if (language, script, territory) is not empty [3.3]
if ( language !== "und" && script !== "Zzzz" && territory !== "ZZ" ) {
return [ language, script, territory ].concat( variantsAndUnicodeLocaleExtensions );
}
// Skip if no supplemental likelySubtags data is present
if ( typeof cldr.get( "supplemental/likelySubtags" ) === "undefined" ) {
return;
}
// [2]
matchFound = arraySome([
[ language, script, territory ],
[ language, territory ],
[ language, script ],
[ language ],
[ "und", script ]
], function( test ) {
return match = !(/\b(Zzzz|ZZ)\b/).test( test.join( sep ) ) /* [1.4] */ && cldr.get( [ "supplemental/likelySubtags", test.join( sep ) ] );
});
// [3]
if ( matchFound ) {
// [3.2 .. 3.4]
match = match.split( sep );
return [
language !== "und" ? language : match[ 0 ],
script !== "Zzzz" ? script : match[ 1 ],
territory !== "ZZ" ? territory : match[ 2 ]
].concat(
variantsAndUnicodeLocaleExtensions
);
} else if ( options.force ) {
// [3.1.2]
return cldr.get( "supplemental/likelySubtags/und" ).split( sep );
} else {
// [3.1.1]
return;
}
};
/**
* Given a locale, remove any fields that Add Likely Subtags would add.
* http://www.unicode.org/reports/tr35/#Likely_Subtags
* 1. First get max = AddLikelySubtags(inputLocale). If an error is signaled,
* return it.
* 2. Remove the variants from max.
* 3. Then for trial in {language, language _ region, language _ script}. If
* AddLikelySubtags(trial) = max, then return trial + variants.
* 4. If you do not get a match, return max + variants.
*
* @maxLanguageId [Array] maxLanguageId tuple (see init.js).
*/
var coreRemoveLikelySubtags = function( Cldr, cldr, maxLanguageId ) {
var match, matchFound,
language = maxLanguageId[ 0 ],
script = maxLanguageId[ 1 ],
territory = maxLanguageId[ 2 ],
variants = maxLanguageId[ 3 ];
// [3]
matchFound = arraySome([
[ [ language, "Zzzz", "ZZ" ], [ language ] ],
[ [ language, "Zzzz", territory ], [ language, territory ] ],
[ [ language, script, "ZZ" ], [ language, script ] ]
], function( test ) {
var result = coreLikelySubtags( Cldr, cldr, test[ 0 ] );
match = test[ 1 ];
return result && result[ 0 ] === maxLanguageId[ 0 ] &&
result[ 1 ] === maxLanguageId[ 1 ] &&
result[ 2 ] === maxLanguageId[ 2 ];
});
if ( matchFound ) {
if ( variants ) {
match.push( variants );
}
return match;
}
// [4]
return maxLanguageId;
};
/**
* subtags( locale )
*
* @locale [String]
*/
var coreSubtags = function( locale ) {
var aux, unicodeLanguageId,
subtags = [];
locale = locale.replace( /_/, "-" );
// Unicode locale extensions.
aux = locale.split( "-u-" );
if ( aux[ 1 ] ) {
aux[ 1 ] = aux[ 1 ].split( "-t-" );
locale = aux[ 0 ] + ( aux[ 1 ][ 1 ] ? "-t-" + aux[ 1 ][ 1 ] : "");
subtags[ 4 /* unicodeLocaleExtensions */ ] = aux[ 1 ][ 0 ];
}
// TODO normalize transformed extensions. Currently, skipped.
// subtags[ x ] = locale.split( "-t-" )[ 1 ];
unicodeLanguageId = locale.split( "-t-" )[ 0 ];
// unicode_language_id = "root"
// | unicode_language_subtag
// (sep unicode_script_subtag)?
// (sep unicode_region_subtag)?
// (sep unicode_variant_subtag)* ;
//
// Although unicode_language_subtag = alpha{2,8}, I'm using alpha{2,3}. Because, there's no language on CLDR lengthier than 3.
aux = unicodeLanguageId.match( /^(([a-z]{2,3})(-([A-Z][a-z]{3}))?(-([A-Z]{2}|[0-9]{3}))?)((-([a-zA-Z0-9]{5,8}|[0-9][a-zA-Z0-9]{3}))*)$|^(root)$/ );
if ( aux === null ) {
return [ "und", "Zzzz", "ZZ" ];
}
subtags[ 0 /* language */ ] = aux[ 10 ] /* root */ || aux[ 2 ] || "und";
subtags[ 1 /* script */ ] = aux[ 4 ] || "Zzzz";
subtags[ 2 /* territory */ ] = aux[ 6 ] || "ZZ";
if ( aux[ 7 ] && aux[ 7 ].length ) {
subtags[ 3 /* variant */ ] = aux[ 7 ].slice( 1 ) /* remove leading "-" */;
}
// 0: language
// 1: script
// 2: territory (aka region)
// 3: variant
// 4: unicodeLocaleExtensions
return subtags;
};
var arrayForEach = function( array, callback ) {
var i, length;
if ( array.forEach ) {
return array.forEach( callback );
}
for ( i = 0, length = array.length; i < length; i++ ) {
callback( array[ i ], i, array );
}
};
/**
* bundleLookup( minLanguageId )
*
* @Cldr [Cldr class]
*
* @cldr [Cldr instance]
*
* @minLanguageId [String] requested languageId after applied remove likely subtags.
*/
var bundleLookup = function( Cldr, cldr, minLanguageId ) {
var availableBundleMap = Cldr._availableBundleMap,
availableBundleMapQueue = Cldr._availableBundleMapQueue;
if ( availableBundleMapQueue.length ) {
arrayForEach( availableBundleMapQueue, function( bundle ) {
var existing, maxBundle, minBundle, subtags;
subtags = coreSubtags( bundle );
maxBundle = coreLikelySubtags( Cldr, cldr, subtags );
minBundle = coreRemoveLikelySubtags( Cldr, cldr, maxBundle );
minBundle = minBundle.join( Cldr.localeSep );
existing = availableBundleMapQueue[ minBundle ];
if ( existing && existing.length < bundle.length ) {
return;
}
availableBundleMap[ minBundle ] = bundle;
});
Cldr._availableBundleMapQueue = [];
}
return availableBundleMap[ minLanguageId ] || null;
};
var objectKeys = function( object ) {
var i,
result = [];
if ( Object.keys ) {
return Object.keys( object );
}
for ( i in object ) {
result.push( i );
}
return result;
};
var createError = function( code, attributes ) {
var error, message;
message = code + ( attributes && JSON ? ": " + JSON.stringify( attributes ) : "" );
error = new Error( message );
error.code = code;
// extend( error, attributes );
arrayForEach( objectKeys( attributes ), function( attribute ) {
error[ attribute ] = attributes[ attribute ];
});
return error;
};
var validate = function( code, check, attributes ) {
if ( !check ) {
throw createError( code, attributes );
}
};
var validatePresence = function( value, name ) {
validate( "E_MISSING_PARAMETER", typeof value !== "undefined", {
name: name
});
};
var validateType = function( value, name, check, expected ) {
validate( "E_INVALID_PAR_TYPE", check, {
expected: expected,
name: name,
value: value
});
};
var validateTypePath = function( value, name ) {
validateType( value, name, typeof value === "string" || arrayIsArray( value ), "String or Array" );
};
/**
* Function inspired by jQuery Core, but reduced to our use case.
*/
var isPlainObject = function( obj ) {
return obj !== null && "" + obj === "[object Object]";
};
var validateTypePlainObject = function( value, name ) {
validateType( value, name, typeof value === "undefined" || isPlainObject( value ), "Plain Object" );
};
var validateTypeString = function( value, name ) {
validateType( value, name, typeof value === "string", "a string" );
};
// @path: normalized path
var resourceGet = function( data, path ) {
var i,
node = data,
length = path.length;
for ( i = 0; i < length - 1; i++ ) {
node = node[ path[ i ] ];
if ( !node ) {
return undefined;
}
}
return node[ path[ i ] ];
};
/**
* setAvailableBundles( Cldr, json )
*
* @Cldr [Cldr class]
*
* @json resolved/unresolved cldr data.
*
* Set available bundles queue based on passed json CLDR data. Considers a bundle as any String at /main/{bundle}.
*/
var coreSetAvailableBundles = function( Cldr, json ) {
var bundle,
availableBundleMapQueue = Cldr._availableBundleMapQueue,
main = resourceGet( json, [ "main" ] );
if ( main ) {
for ( bundle in main ) {
if ( main.hasOwnProperty( bundle ) && bundle !== "root" &&
availableBundleMapQueue.indexOf( bundle ) === -1 ) {
availableBundleMapQueue.push( bundle );
}
}
}
};
var alwaysArray = function( somethingOrArray ) {
return arrayIsArray( somethingOrArray ) ? somethingOrArray : [ somethingOrArray ];
};
var jsonMerge = (function() {
// Returns new deeply merged JSON.
//
// Eg.
// merge( { a: { b: 1, c: 2 } }, { a: { b: 3, d: 4 } } )
// -> { a: { b: 3, c: 2, d: 4 } }
//
// @arguments JSON's
//
var merge = function() {
var destination = {},
sources = [].slice.call( arguments, 0 );
arrayForEach( sources, function( source ) {
var prop;
for ( prop in source ) {
if ( prop in destination && typeof destination[ prop ] === "object" && !arrayIsArray( destination[ prop ] ) ) {
// Merge Objects
destination[ prop ] = merge( destination[ prop ], source[ prop ] );
} else {
// Set new values
destination[ prop ] = source[ prop ];
}
}
});
return destination;
};
return merge;
}());
/**
* load( Cldr, source, jsons )
*
* @Cldr [Cldr class]
*
* @source [Object]
*
* @jsons [arguments]
*/
var coreLoad = function( Cldr, source, jsons ) {
var i, j, json;
validatePresence( jsons[ 0 ], "json" );
// Support arbitrary parameters, e.g., `Cldr.load({...}, {...})`.
for ( i = 0; i < jsons.length; i++ ) {
// Support array parameters, e.g., `Cldr.load([{...}, {...}])`.
json = alwaysArray( jsons[ i ] );
for ( j = 0; j < json.length; j++ ) {
validateTypePlainObject( json[ j ], "json" );
source = jsonMerge( source, json[ j ] );
coreSetAvailableBundles( Cldr, json[ j ] );
}
}
return source;
};
var itemGetResolved = function( Cldr, path, attributes ) {
// Resolve path
var normalizedPath = pathNormalize( path, attributes );
return resourceGet( Cldr._resolved, normalizedPath );
};
/**
* new Cldr()
*/
var Cldr = function( locale ) {
this.init( locale );
};
// Build optimization hack to avoid duplicating functions across modules.
Cldr._alwaysArray = alwaysArray;
Cldr._coreLoad = coreLoad;
Cldr._createError = createError;
Cldr._itemGetResolved = itemGetResolved;
Cldr._jsonMerge = jsonMerge;
Cldr._pathNormalize = pathNormalize;
Cldr._resourceGet = resourceGet;
Cldr._validatePresence = validatePresence;
Cldr._validateType = validateType;
Cldr._validateTypePath = validateTypePath;
Cldr._validateTypePlainObject = validateTypePlainObject;
Cldr._availableBundleMap = {};
Cldr._availableBundleMapQueue = [];
Cldr._resolved = {};
// Allow user to override locale separator "-" (default) | "_". According to http://www.unicode.org/reports/tr35/#Unicode_language_identifier, both "-" and "_" are valid locale separators (eg. "en_GB", "en-GB"). According to http://unicode.org/cldr/trac/ticket/6786 its usage must be consistent throughout the data set.
Cldr.localeSep = "-";
/**
* Cldr.load( json [, json, ...] )
*
* @json [JSON] CLDR data or [Array] Array of @json's.
*
* Load resolved cldr data.
*/
Cldr.load = function() {
Cldr._resolved = coreLoad( Cldr, Cldr._resolved, arguments );
};
/**
* .init() automatically run on instantiation/construction.
*/
Cldr.prototype.init = function( locale ) {
var attributes, language, maxLanguageId, minLanguageId, script, subtags, territory, unicodeLocaleExtensions, variant,
sep = Cldr.localeSep;
validatePresence( locale, "locale" );
validateTypeString( locale, "locale" );
subtags = coreSubtags( locale );
unicodeLocaleExtensions = subtags[ 4 ];
variant = subtags[ 3 ];
// Normalize locale code.
// Get (or deduce) the "triple subtags": language, territory (also aliased as region), and script subtags.
// Get the variant subtags (calendar, collation, currency, etc).
// refs:
// - http://www.unicode.org/reports/tr35/#Field_Definitions
// - http://www.unicode.org/reports/tr35/#Language_and_Locale_IDs
// - http://www.unicode.org/reports/tr35/#Unicode_locale_identifier
// When a locale id does not specify a language, or territory (region), or script, they are obtained by Likely Subtags.
maxLanguageId = coreLikelySubtags( Cldr, this, subtags, { force: true } ) || subtags;
language = maxLanguageId[ 0 ];
script = maxLanguageId[ 1 ];
territory = maxLanguageId[ 2 ];
minLanguageId = coreRemoveLikelySubtags( Cldr, this, maxLanguageId ).join( sep );
// Set attributes
this.attributes = attributes = {
bundle: bundleLookup( Cldr, this, minLanguageId ),
// Unicode Language Id
minlanguageId: minLanguageId,
maxLanguageId: maxLanguageId.join( sep ),
// Unicode Language Id Subtabs
language: language,
script: script,
territory: territory,
region: territory, /* alias */
variant: variant
};
// Unicode locale extensions.
unicodeLocaleExtensions && ( "-" + unicodeLocaleExtensions ).replace( /-[a-z]{3,8}|(-[a-z]{2})-([a-z]{3,8})/g, function( attribute, key, type ) {
if ( key ) {
// Extension is in the `keyword` form.
attributes[ "u" + key ] = type;
} else {
// Extension is in the `attribute` form.
attributes[ "u" + attribute ] = true;
}
});
this.locale = locale;
};
/**
* .get()
*/
Cldr.prototype.get = function( path ) {
validatePresence( path, "path" );
validateTypePath( path, "path" );
return itemGetResolved( Cldr, path, this.attributes );
};
/**
* .main()
*/
Cldr.prototype.main = function( path ) {
validatePresence( path, "path" );
validateTypePath( path, "path" );
validate( "E_MISSING_BUNDLE", this.attributes.bundle !== null, {
locale: this.locale
});
path = alwaysArray( path );
return this.get( [ "main/{bundle}" ].concat( path ) );
};
return Cldr;
}));
+585
View File
@@ -0,0 +1,585 @@
/**
* CLDR JavaScript Library v0.4.4
* http://jquery.com/
*
* Copyright 2013 Rafael Xavier de Souza
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2016-01-18T12:25Z
*/
/*!
* CLDR JavaScript Library v0.4.4 2016-01-18T12:25Z MIT license © Rafael Xavier
* http://git.io/h4lmVg
*/
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD.
define( [ "../cldr" ], factory );
} else if ( typeof module === "object" && typeof module.exports === "object" ) {
// Node. CommonJS.
module.exports = factory( require( "cldrjs" ) );
} else {
// Global
factory( Cldr );
}
}(function( Cldr ) {
// Build optimization hack to avoid duplicating functions across modules.
var pathNormalize = Cldr._pathNormalize,
validatePresence = Cldr._validatePresence,
validateType = Cldr._validateType;
/*!
* EventEmitter v4.2.7 - git.io/ee
* Oliver Caldwell
* MIT license
* @preserve
*/
var EventEmitter;
/* jshint ignore:start */
EventEmitter = (function () {
/**
* Class for managing events.
* Can be extended to provide event functionality in other classes.
*
* @class EventEmitter Manages event registering and emitting.
*/
function EventEmitter() {}
// Shortcuts to improve speed and size
var proto = EventEmitter.prototype;
var exports = this;
var originalGlobalValue = exports.EventEmitter;
/**
* Finds the index of the listener for the event in it's storage array.
*
* @param {Function[]} listeners Array of listeners to search through.
* @param {Function} listener Method to look for.
* @return {Number} Index of the specified listener, -1 if not found
* @api private
*/
function indexOfListener(listeners, listener) {
var i = listeners.length;
while (i--) {
if (listeners[i].listener === listener) {
return i;
}
}
return -1;
}
/**
* Alias a method while keeping the context correct, to allow for overwriting of target method.
*
* @param {String} name The name of the target method.
* @return {Function} The aliased method
* @api private
*/
function alias(name) {
return function aliasClosure() {
return this[name].apply(this, arguments);
};
}
/**
* Returns the listener array for the specified event.
* Will initialise the event object and listener arrays if required.
* Will return an object if you use a regex search. The object contains keys for each matched event. So /ba[rz]/ might return an object containing bar and baz. But only if you have either defined them with defineEvent or added some listeners to them.
* Each property in the object response is an array of listener functions.
*
* @param {String|RegExp} evt Name of the event to return the listeners from.
* @return {Function[]|Object} All listener functions for the event.
*/
proto.getListeners = function getListeners(evt) {
var events = this._getEvents();
var response;
var key;
// Return a concatenated array of all matching events if
// the selector is a regular expression.
if (evt instanceof RegExp) {
response = {};
for (key in events) {
if (events.hasOwnProperty(key) && evt.test(key)) {
response[key] = events[key];
}
}
}
else {
response = events[evt] || (events[evt] = []);
}
return response;
};
/**
* Takes a list of listener objects and flattens it into a list of listener functions.
*
* @param {Object[]} listeners Raw listener objects.
* @return {Function[]} Just the listener functions.
*/
proto.flattenListeners = function flattenListeners(listeners) {
var flatListeners = [];
var i;
for (i = 0; i < listeners.length; i += 1) {
flatListeners.push(listeners[i].listener);
}
return flatListeners;
};
/**
* Fetches the requested listeners via getListeners but will always return the results inside an object. This is mainly for internal use but others may find it useful.
*
* @param {String|RegExp} evt Name of the event to return the listeners from.
* @return {Object} All listener functions for an event in an object.
*/
proto.getListenersAsObject = function getListenersAsObject(evt) {
var listeners = this.getListeners(evt);
var response;
if (listeners instanceof Array) {
response = {};
response[evt] = listeners;
}
return response || listeners;
};
/**
* Adds a listener function to the specified event.
* The listener will not be added if it is a duplicate.
* If the listener returns true then it will be removed after it is called.
* If you pass a regular expression as the event name then the listener will be added to all events that match it.
*
* @param {String|RegExp} evt Name of the event to attach the listener to.
* @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.addListener = function addListener(evt, listener) {
var listeners = this.getListenersAsObject(evt);
var listenerIsWrapped = typeof listener === 'object';
var key;
for (key in listeners) {
if (listeners.hasOwnProperty(key) && indexOfListener(listeners[key], listener) === -1) {
listeners[key].push(listenerIsWrapped ? listener : {
listener: listener,
once: false
});
}
}
return this;
};
/**
* Alias of addListener
*/
proto.on = alias('addListener');
/**
* Semi-alias of addListener. It will add a listener that will be
* automatically removed after it's first execution.
*
* @param {String|RegExp} evt Name of the event to attach the listener to.
* @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.addOnceListener = function addOnceListener(evt, listener) {
return this.addListener(evt, {
listener: listener,
once: true
});
};
/**
* Alias of addOnceListener.
*/
proto.once = alias('addOnceListener');
/**
* Defines an event name. This is required if you want to use a regex to add a listener to multiple events at once. If you don't do this then how do you expect it to know what event to add to? Should it just add to every possible match for a regex? No. That is scary and bad.
* You need to tell it what event names should be matched by a regex.
*
* @param {String} evt Name of the event to create.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.defineEvent = function defineEvent(evt) {
this.getListeners(evt);
return this;
};
/**
* Uses defineEvent to define multiple events.
*
* @param {String[]} evts An array of event names to define.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.defineEvents = function defineEvents(evts) {
for (var i = 0; i < evts.length; i += 1) {
this.defineEvent(evts[i]);
}
return this;
};
/**
* Removes a listener function from the specified event.
* When passed a regular expression as the event name, it will remove the listener from all events that match it.
*
* @param {String|RegExp} evt Name of the event to remove the listener from.
* @param {Function} listener Method to remove from the event.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.removeListener = function removeListener(evt, listener) {
var listeners = this.getListenersAsObject(evt);
var index;
var key;
for (key in listeners) {
if (listeners.hasOwnProperty(key)) {
index = indexOfListener(listeners[key], listener);
if (index !== -1) {
listeners[key].splice(index, 1);
}
}
}
return this;
};
/**
* Alias of removeListener
*/
proto.off = alias('removeListener');
/**
* Adds listeners in bulk using the manipulateListeners method.
* If you pass an object as the second argument you can add to multiple events at once. The object should contain key value pairs of events and listeners or listener arrays. You can also pass it an event name and an array of listeners to be added.
* You can also pass it a regular expression to add the array of listeners to all events that match it.
* Yeah, this function does quite a bit. That's probably a bad thing.
*
* @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add to multiple events at once.
* @param {Function[]} [listeners] An optional array of listener functions to add.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.addListeners = function addListeners(evt, listeners) {
// Pass through to manipulateListeners
return this.manipulateListeners(false, evt, listeners);
};
/**
* Removes listeners in bulk using the manipulateListeners method.
* If you pass an object as the second argument you can remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays.
* You can also pass it an event name and an array of listeners to be removed.
* You can also pass it a regular expression to remove the listeners from all events that match it.
*
* @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to remove from multiple events at once.
* @param {Function[]} [listeners] An optional array of listener functions to remove.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.removeListeners = function removeListeners(evt, listeners) {
// Pass through to manipulateListeners
return this.manipulateListeners(true, evt, listeners);
};
/**
* Edits listeners in bulk. The addListeners and removeListeners methods both use this to do their job. You should really use those instead, this is a little lower level.
* The first argument will determine if the listeners are removed (true) or added (false).
* If you pass an object as the second argument you can add/remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays.
* You can also pass it an event name and an array of listeners to be added/removed.
* You can also pass it a regular expression to manipulate the listeners of all events that match it.
*
* @param {Boolean} remove True if you want to remove listeners, false if you want to add.
* @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add/remove from multiple events at once.
* @param {Function[]} [listeners] An optional array of listener functions to add/remove.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.manipulateListeners = function manipulateListeners(remove, evt, listeners) {
var i;
var value;
var single = remove ? this.removeListener : this.addListener;
var multiple = remove ? this.removeListeners : this.addListeners;
// If evt is an object then pass each of it's properties to this method
if (typeof evt === 'object' && !(evt instanceof RegExp)) {
for (i in evt) {
if (evt.hasOwnProperty(i) && (value = evt[i])) {
// Pass the single listener straight through to the singular method
if (typeof value === 'function') {
single.call(this, i, value);
}
else {
// Otherwise pass back to the multiple function
multiple.call(this, i, value);
}
}
}
}
else {
// So evt must be a string
// And listeners must be an array of listeners
// Loop over it and pass each one to the multiple method
i = listeners.length;
while (i--) {
single.call(this, evt, listeners[i]);
}
}
return this;
};
/**
* Removes all listeners from a specified event.
* If you do not specify an event then all listeners will be removed.
* That means every event will be emptied.
* You can also pass a regex to remove all events that match it.
*
* @param {String|RegExp} [evt] Optional name of the event to remove all listeners for. Will remove from every event if not passed.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.removeEvent = function removeEvent(evt) {
var type = typeof evt;
var events = this._getEvents();
var key;
// Remove different things depending on the state of evt
if (type === 'string') {
// Remove all listeners for the specified event
delete events[evt];
}
else if (evt instanceof RegExp) {
// Remove all events matching the regex.
for (key in events) {
if (events.hasOwnProperty(key) && evt.test(key)) {
delete events[key];
}
}
}
else {
// Remove all listeners in all events
delete this._events;
}
return this;
};
/**
* Alias of removeEvent.
*
* Added to mirror the node API.
*/
proto.removeAllListeners = alias('removeEvent');
/**
* Emits an event of your choice.
* When emitted, every listener attached to that event will be executed.
* If you pass the optional argument array then those arguments will be passed to every listener upon execution.
* Because it uses `apply`, your array of arguments will be passed as if you wrote them out separately.
* So they will not arrive within the array on the other side, they will be separate.
* You can also pass a regular expression to emit to all events that match it.
*
* @param {String|RegExp} evt Name of the event to emit and execute listeners for.
* @param {Array} [args] Optional array of arguments to be passed to each listener.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.emitEvent = function emitEvent(evt, args) {
var listeners = this.getListenersAsObject(evt);
var listener;
var i;
var key;
var response;
for (key in listeners) {
if (listeners.hasOwnProperty(key)) {
i = listeners[key].length;
while (i--) {
// If the listener returns true then it shall be removed from the event
// The function is executed either with a basic call or an apply if there is an args array
listener = listeners[key][i];
if (listener.once === true) {
this.removeListener(evt, listener.listener);
}
response = listener.listener.apply(this, args || []);
if (response === this._getOnceReturnValue()) {
this.removeListener(evt, listener.listener);
}
}
}
}
return this;
};
/**
* Alias of emitEvent
*/
proto.trigger = alias('emitEvent');
/**
* Subtly different from emitEvent in that it will pass its arguments on to the listeners, as opposed to taking a single array of arguments to pass on.
* As with emitEvent, you can pass a regex in place of the event name to emit to all events that match it.
*
* @param {String|RegExp} evt Name of the event to emit and execute listeners for.
* @param {...*} Optional additional arguments to be passed to each listener.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.emit = function emit(evt) {
var args = Array.prototype.slice.call(arguments, 1);
return this.emitEvent(evt, args);
};
/**
* Sets the current value to check against when executing listeners. If a
* listeners return value matches the one set here then it will be removed
* after execution. This value defaults to true.
*
* @param {*} value The new value to check for when executing listeners.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.setOnceReturnValue = function setOnceReturnValue(value) {
this._onceReturnValue = value;
return this;
};
/**
* Fetches the current value to check against when executing listeners. If
* the listeners return value matches this one then it should be removed
* automatically. It will return true by default.
*
* @return {*|Boolean} The current value to check for or the default, true.
* @api private
*/
proto._getOnceReturnValue = function _getOnceReturnValue() {
if (this.hasOwnProperty('_onceReturnValue')) {
return this._onceReturnValue;
}
else {
return true;
}
};
/**
* Fetches the events object and creates one if required.
*
* @return {Object} The events storage object.
* @api private
*/
proto._getEvents = function _getEvents() {
return this._events || (this._events = {});
};
/**
* Reverts the global {@link EventEmitter} to its previous value and returns a reference to this version.
*
* @return {Function} Non conflicting EventEmitter class.
*/
EventEmitter.noConflict = function noConflict() {
exports.EventEmitter = originalGlobalValue;
return EventEmitter;
};
return EventEmitter;
}());
/* jshint ignore:end */
var validateTypeFunction = function( value, name ) {
validateType( value, name, typeof value === "undefined" || typeof value === "function", "Function" );
};
var superGet, superInit,
globalEe = new EventEmitter();
function validateTypeEvent( value, name ) {
validateType( value, name, typeof value === "string" || value instanceof RegExp, "String or RegExp" );
}
function validateThenCall( method, self ) {
return function( event, listener ) {
validatePresence( event, "event" );
validateTypeEvent( event, "event" );
validatePresence( listener, "listener" );
validateTypeFunction( listener, "listener" );
return self[ method ].apply( self, arguments );
};
}
function off( self ) {
return validateThenCall( "off", self );
}
function on( self ) {
return validateThenCall( "on", self );
}
function once( self ) {
return validateThenCall( "once", self );
}
Cldr.off = off( globalEe );
Cldr.on = on( globalEe );
Cldr.once = once( globalEe );
/**
* Overload Cldr.prototype.init().
*/
superInit = Cldr.prototype.init;
Cldr.prototype.init = function() {
var ee;
this.ee = ee = new EventEmitter();
this.off = off( ee );
this.on = on( ee );
this.once = once( ee );
superInit.apply( this, arguments );
};
/**
* getOverload is encapsulated, because of cldr/unresolved. If it's loaded
* after cldr/event (and note it overwrites .get), it can trigger this
* overload again.
*/
function getOverload() {
/**
* Overload Cldr.prototype.get().
*/
superGet = Cldr.prototype.get;
Cldr.prototype.get = function( path ) {
var value = superGet.apply( this, arguments );
path = pathNormalize( path, this.attributes ).join( "/" );
globalEe.trigger( "get", [ path, value ] );
this.ee.trigger( "get", [ path, value ] );
return value;
};
}
Cldr._eventInit = getOverload;
getOverload();
return Cldr;
}));
+101
View File
@@ -0,0 +1,101 @@
/**
* CLDR JavaScript Library v0.4.4
* http://jquery.com/
*
* Copyright 2013 Rafael Xavier de Souza
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2016-01-18T12:25Z
*/
/*!
* CLDR JavaScript Library v0.4.4 2016-01-18T12:25Z MIT license © Rafael Xavier
* http://git.io/h4lmVg
*/
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD.
define( [ "../cldr" ], factory );
} else if ( typeof module === "object" && typeof module.exports === "object" ) {
// Node. CommonJS.
module.exports = factory( require( "cldrjs" ) );
} else {
// Global
factory( Cldr );
}
}(function( Cldr ) {
// Build optimization hack to avoid duplicating functions across modules.
var alwaysArray = Cldr._alwaysArray;
var supplementalMain = function( cldr ) {
var prepend, supplemental;
prepend = function( prepend ) {
return function( path ) {
path = alwaysArray( path );
return cldr.get( [ prepend ].concat( path ) );
};
};
supplemental = prepend( "supplemental" );
// Week Data
// http://www.unicode.org/reports/tr35/tr35-dates.html#Week_Data
supplemental.weekData = prepend( "supplemental/weekData" );
supplemental.weekData.firstDay = function() {
return cldr.get( "supplemental/weekData/firstDay/{territory}" ) ||
cldr.get( "supplemental/weekData/firstDay/001" );
};
supplemental.weekData.minDays = function() {
var minDays = cldr.get( "supplemental/weekData/minDays/{territory}" ) ||
cldr.get( "supplemental/weekData/minDays/001" );
return parseInt( minDays, 10 );
};
// Time Data
// http://www.unicode.org/reports/tr35/tr35-dates.html#Time_Data
supplemental.timeData = prepend( "supplemental/timeData" );
supplemental.timeData.allowed = function() {
return cldr.get( "supplemental/timeData/{territory}/_allowed" ) ||
cldr.get( "supplemental/timeData/001/_allowed" );
};
supplemental.timeData.preferred = function() {
return cldr.get( "supplemental/timeData/{territory}/_preferred" ) ||
cldr.get( "supplemental/timeData/001/_preferred" );
};
return supplemental;
};
var initSuper = Cldr.prototype.init;
/**
* .init() automatically ran on construction.
*
* Overload .init().
*/
Cldr.prototype.init = function() {
initSuper.apply( this, arguments );
this.supplemental = supplementalMain( this );
};
return Cldr;
}));
+164
View File
@@ -0,0 +1,164 @@
/**
* CLDR JavaScript Library v0.4.4
* http://jquery.com/
*
* Copyright 2013 Rafael Xavier de Souza
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2016-01-18T12:25Z
*/
/*!
* CLDR JavaScript Library v0.4.4 2016-01-18T12:25Z MIT license © Rafael Xavier
* http://git.io/h4lmVg
*/
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD.
define( [ "../cldr" ], factory );
} else if ( typeof module === "object" && typeof module.exports === "object" ) {
// Node. CommonJS.
module.exports = factory( require( "cldrjs" ) );
} else {
// Global
factory( Cldr );
}
}(function( Cldr ) {
// Build optimization hack to avoid duplicating functions across modules.
var coreLoad = Cldr._coreLoad;
var jsonMerge = Cldr._jsonMerge;
var pathNormalize = Cldr._pathNormalize;
var resourceGet = Cldr._resourceGet;
var validatePresence = Cldr._validatePresence;
var validateTypePath = Cldr._validateTypePath;
var bundleParentLookup = function( Cldr, locale ) {
var normalizedPath, parent;
if ( locale === "root" ) {
return;
}
// First, try to find parent on supplemental data.
normalizedPath = pathNormalize( [ "supplemental/parentLocales/parentLocale", locale ] );
parent = resourceGet( Cldr._resolved, normalizedPath ) || resourceGet( Cldr._raw, normalizedPath );
if ( parent ) {
return parent;
}
// Or truncate locale.
parent = locale.substr( 0, locale.lastIndexOf( Cldr.localeSep ) );
if ( !parent ) {
return "root";
}
return parent;
};
// @path: normalized path
var resourceSet = function( data, path, value ) {
var i,
node = data,
length = path.length;
for ( i = 0; i < length - 1; i++ ) {
if ( !node[ path[ i ] ] ) {
node[ path[ i ] ] = {};
}
node = node[ path[ i ] ];
}
node[ path[ i ] ] = value;
};
var itemLookup = (function() {
var lookup;
lookup = function( Cldr, locale, path, attributes, childLocale ) {
var normalizedPath, parent, value;
// 1: Finish recursion
// 2: Avoid infinite loop
if ( typeof locale === "undefined" /* 1 */ || locale === childLocale /* 2 */ ) {
return;
}
// Resolve path
normalizedPath = pathNormalize( path, attributes );
// Check resolved (cached) data first
// 1: Due to #16, never use the cached resolved non-leaf nodes. It may not
// represent its leafs in its entirety.
value = resourceGet( Cldr._resolved, normalizedPath );
if ( value && typeof value !== "object" /* 1 */ ) {
return value;
}
// Check raw data
value = resourceGet( Cldr._raw, normalizedPath );
if ( !value ) {
// Or, lookup at parent locale
parent = bundleParentLookup( Cldr, locale );
value = lookup( Cldr, parent, path, jsonMerge( attributes, { bundle: parent }), locale );
}
if ( value ) {
// Set resolved (cached)
resourceSet( Cldr._resolved, normalizedPath, value );
}
return value;
};
return lookup;
}());
Cldr._raw = {};
/**
* Cldr.load( json [, json, ...] )
*
* @json [JSON] CLDR data or [Array] Array of @json's.
*
* Load resolved or unresolved cldr data.
* Overwrite Cldr.load().
*/
Cldr.load = function() {
Cldr._raw = coreLoad( Cldr, Cldr._raw, arguments );
};
/**
* Overwrite Cldr.prototype.get().
*/
Cldr.prototype.get = function( path ) {
validatePresence( path, "path" );
validateTypePath( path, "path" );
// 1: use bundle as locale on item lookup for simplification purposes, because no other extended subtag is used anyway on bundle parent lookup.
// 2: during init(), this method is called, but bundle is yet not defined. Use "" as a workaround in this very specific scenario.
return itemLookup( Cldr, this.attributes && this.attributes.bundle /* 1 */ || "" /* 2 */, path, this.attributes );
};
// In case cldr/unresolved is loaded after cldr/event, we trigger its overloads again. Because, .get is overwritten in here.
if ( Cldr._eventInit ) {
Cldr._eventInit();
}
return Cldr;
}));
+421
View File
@@ -0,0 +1,421 @@
/**
* Globalize v1.1.1
*
* http://github.com/jquery/globalize
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2016-02-04T12:01Z
*/
/*!
* Globalize v1.1.1 2016-02-04T12:01Z Released under the MIT license
* http://git.io/TrdQbw
*/
(function( root, factory ) {
// UMD returnExports
if ( typeof define === "function" && define.amd ) {
// AMD
define([
"cldr",
"cldr/event"
], factory );
} else if ( typeof exports === "object" ) {
// Node, CommonJS
module.exports = factory( require( "cldrjs" ) );
} else {
// Global
root.Globalize = factory( root.Cldr );
}
}( this, function( Cldr ) {
/**
* A toString method that outputs meaningful values for objects or arrays and
* still performs as fast as a plain string in case variable is string, or as
* fast as `"" + number` in case variable is a number.
* Ref: http://jsperf.com/my-stringify
*/
var toString = function( variable ) {
return typeof variable === "string" ? variable : ( typeof variable === "number" ? "" +
variable : JSON.stringify( variable ) );
};
/**
* formatMessage( message, data )
*
* @message [String] A message with optional {vars} to be replaced.
*
* @data [Array or JSON] Object with replacing-variables content.
*
* Return the formatted message. For example:
*
* - formatMessage( "{0} second", [ 1 ] ); // 1 second
*
* - formatMessage( "{0}/{1}", ["m", "s"] ); // m/s
*
* - formatMessage( "{name} <{email}>", {
* name: "Foo",
* email: "bar@baz.qux"
* }); // Foo <bar@baz.qux>
*/
var formatMessage = function( message, data ) {
// Replace {attribute}'s
message = message.replace( /{[0-9a-zA-Z-_. ]+}/g, function( name ) {
name = name.replace( /^{([^}]*)}$/, "$1" );
return toString( data[ name ] );
});
return message;
};
var objectExtend = function() {
var destination = arguments[ 0 ],
sources = [].slice.call( arguments, 1 );
sources.forEach(function( source ) {
var prop;
for ( prop in source ) {
destination[ prop ] = source[ prop ];
}
});
return destination;
};
var createError = function( code, message, attributes ) {
var error;
message = code + ( message ? ": " + formatMessage( message, attributes ) : "" );
error = new Error( message );
error.code = code;
objectExtend( error, attributes );
return error;
};
// Based on http://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript-jquery
var stringHash = function( str ) {
return [].reduce.call( str, function( hash, i ) {
var chr = i.charCodeAt( 0 );
hash = ( ( hash << 5 ) - hash ) + chr;
return hash | 0;
}, 0 );
};
var runtimeKey = function( fnName, locale, args, argsStr ) {
var hash;
argsStr = argsStr || JSON.stringify( args );
hash = stringHash( fnName + locale + argsStr );
return hash > 0 ? "a" + hash : "b" + Math.abs( hash );
};
var functionName = function( fn ) {
if ( fn.name !== undefined ) {
return fn.name;
}
// fn.name is not supported by IE.
var matches = /^function\s+([\w\$]+)\s*\(/.exec( fn.toString() );
if ( matches && matches.length > 0 ) {
return matches[ 1 ];
}
};
var runtimeBind = function( args, cldr, fn, runtimeArgs ) {
var argsStr = JSON.stringify( args ),
fnName = functionName( fn ),
locale = cldr.locale;
// If name of the function is not available, this is most likely due uglification,
// which most likely means we are in production, and runtimeBind here is not necessary.
if ( !fnName ) {
return fn;
}
fn.runtimeKey = runtimeKey( fnName, locale, null, argsStr );
fn.generatorString = function() {
return "Globalize(\"" + locale + "\")." + fnName + "(" + argsStr.slice( 1, -1 ) + ")";
};
fn.runtimeArgs = runtimeArgs;
return fn;
};
var validate = function( code, message, check, attributes ) {
if ( !check ) {
throw createError( code, message, attributes );
}
};
var alwaysArray = function( stringOrArray ) {
return Array.isArray( stringOrArray ) ? stringOrArray : stringOrArray ? [ stringOrArray ] : [];
};
var validateCldr = function( path, value, options ) {
var skipBoolean;
options = options || {};
skipBoolean = alwaysArray( options.skip ).some(function( pathRe ) {
return pathRe.test( path );
});
validate( "E_MISSING_CLDR", "Missing required CLDR content `{path}`.", value || skipBoolean, {
path: path
});
};
var validateDefaultLocale = function( value ) {
validate( "E_DEFAULT_LOCALE_NOT_DEFINED", "Default locale has not been defined.",
value !== undefined, {} );
};
var validateParameterPresence = function( value, name ) {
validate( "E_MISSING_PARAMETER", "Missing required parameter `{name}`.",
value !== undefined, { name: name });
};
/**
* range( value, name, minimum, maximum )
*
* @value [Number].
*
* @name [String] name of variable.
*
* @minimum [Number]. The lowest valid value, inclusive.
*
* @maximum [Number]. The greatest valid value, inclusive.
*/
var validateParameterRange = function( value, name, minimum, maximum ) {
validate(
"E_PAR_OUT_OF_RANGE",
"Parameter `{name}` has value `{value}` out of range [{minimum}, {maximum}].",
value === undefined || value >= minimum && value <= maximum,
{
maximum: maximum,
minimum: minimum,
name: name,
value: value
}
);
};
var validateParameterType = function( value, name, check, expected ) {
validate(
"E_INVALID_PAR_TYPE",
"Invalid `{name}` parameter ({value}). {expected} expected.",
check,
{
expected: expected,
name: name,
value: value
}
);
};
var validateParameterTypeLocale = function( value, name ) {
validateParameterType(
value,
name,
value === undefined || typeof value === "string" || value instanceof Cldr,
"String or Cldr instance"
);
};
/**
* Function inspired by jQuery Core, but reduced to our use case.
*/
var isPlainObject = function( obj ) {
return obj !== null && "" + obj === "[object Object]";
};
var validateParameterTypePlainObject = function( value, name ) {
validateParameterType(
value,
name,
value === undefined || isPlainObject( value ),
"Plain Object"
);
};
var alwaysCldr = function( localeOrCldr ) {
return localeOrCldr instanceof Cldr ? localeOrCldr : new Cldr( localeOrCldr );
};
// ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions?redirectlocale=en-US&redirectslug=JavaScript%2FGuide%2FRegular_Expressions
var regexpEscape = function( string ) {
return string.replace( /([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1" );
};
var stringPad = function( str, count, right ) {
var length;
if ( typeof str !== "string" ) {
str = String( str );
}
for ( length = str.length; length < count; length += 1 ) {
str = ( right ? ( str + "0" ) : ( "0" + str ) );
}
return str;
};
function validateLikelySubtags( cldr ) {
cldr.once( "get", validateCldr );
cldr.get( "supplemental/likelySubtags" );
}
/**
* [new] Globalize( locale|cldr )
*
* @locale [String]
*
* @cldr [Cldr instance]
*
* Create a Globalize instance.
*/
function Globalize( locale ) {
if ( !( this instanceof Globalize ) ) {
return new Globalize( locale );
}
validateParameterPresence( locale, "locale" );
validateParameterTypeLocale( locale, "locale" );
this.cldr = alwaysCldr( locale );
validateLikelySubtags( this.cldr );
}
/**
* Globalize.load( json, ... )
*
* @json [JSON]
*
* Load resolved or unresolved cldr data.
* Somewhat equivalent to previous Globalize.addCultureInfo(...).
*/
Globalize.load = function() {
// validations are delegated to Cldr.load().
Cldr.load.apply( Cldr, arguments );
};
/**
* Globalize.locale( [locale|cldr] )
*
* @locale [String]
*
* @cldr [Cldr instance]
*
* Set default Cldr instance if locale or cldr argument is passed.
*
* Return the default Cldr instance.
*/
Globalize.locale = function( locale ) {
validateParameterTypeLocale( locale, "locale" );
if ( arguments.length ) {
this.cldr = alwaysCldr( locale );
validateLikelySubtags( this.cldr );
}
return this.cldr;
};
/**
* Optimization to avoid duplicating some internal functions across modules.
*/
Globalize._alwaysArray = alwaysArray;
Globalize._createError = createError;
Globalize._formatMessage = formatMessage;
Globalize._isPlainObject = isPlainObject;
Globalize._objectExtend = objectExtend;
Globalize._regexpEscape = regexpEscape;
Globalize._runtimeBind = runtimeBind;
Globalize._stringPad = stringPad;
Globalize._validate = validate;
Globalize._validateCldr = validateCldr;
Globalize._validateDefaultLocale = validateDefaultLocale;
Globalize._validateParameterPresence = validateParameterPresence;
Globalize._validateParameterRange = validateParameterRange;
Globalize._validateParameterTypePlainObject = validateParameterTypePlainObject;
Globalize._validateParameterType = validateParameterType;
return Globalize;
}));
+439
View File
@@ -0,0 +1,439 @@
/*!
* Globalize v1.1.1
*
* http://github.com/jquery/globalize
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2016-02-04T12:01Z
*/
(function( root, factory ) {
// UMD returnExports
if ( typeof define === "function" && define.amd ) {
// AMD
define([
"cldr",
"../globalize",
"./number",
"cldr/event",
"cldr/supplemental"
], factory );
} else if ( typeof exports === "object" ) {
// Node, CommonJS
module.exports = factory( require( "cldrjs" ), require( "globalize" ) );
} else {
// Global
factory( root.Cldr, root.Globalize );
}
}(this, function( Cldr, Globalize ) {
var alwaysArray = Globalize._alwaysArray,
formatMessage = Globalize._formatMessage,
numberNumberingSystem = Globalize._numberNumberingSystem,
numberPattern = Globalize._numberPattern,
runtimeBind = Globalize._runtimeBind,
stringPad = Globalize._stringPad,
validateCldr = Globalize._validateCldr,
validateDefaultLocale = Globalize._validateDefaultLocale,
validateParameterPresence = Globalize._validateParameterPresence,
validateParameterType = Globalize._validateParameterType,
validateParameterTypeNumber = Globalize._validateParameterTypeNumber,
validateParameterTypePlainObject = Globalize._validateParameterTypePlainObject;
var validateParameterTypeCurrency = function( value, name ) {
validateParameterType(
value,
name,
value === undefined || typeof value === "string" && ( /^[A-Za-z]{3}$/ ).test( value ),
"3-letter currency code string as defined by ISO 4217"
);
};
/**
* supplementalOverride( currency, pattern, cldr )
*
* Return pattern with fraction digits overriden by supplemental currency data.
*/
var currencySupplementalOverride = function( currency, pattern, cldr ) {
var digits,
fraction = "",
fractionData = cldr.supplemental([ "currencyData/fractions", currency ]) ||
cldr.supplemental( "currencyData/fractions/DEFAULT" );
digits = +fractionData._digits;
if ( digits ) {
fraction = "." + stringPad( "0", digits ).slice( 0, -1 ) + fractionData._rounding;
}
return pattern.replace( /\.(#+|0*[0-9]|0+[0-9]?)/g, fraction );
};
var objectFilter = function( object, testRe ) {
var key,
copy = {};
for ( key in object ) {
if ( testRe.test( key ) ) {
copy[ key ] = object[ key ];
}
}
return copy;
};
var currencyUnitPatterns = function( cldr ) {
return objectFilter( cldr.main([
"numbers",
"currencyFormats-numberSystem-" + numberNumberingSystem( cldr )
]), /^unitPattern/ );
};
/**
* codeProperties( currency, cldr )
*
* Return number pattern with the appropriate currency code in as literal.
*/
var currencyCodeProperties = function( currency, cldr ) {
var pattern = numberPattern( "decimal", cldr );
// The number of decimal places and the rounding for each currency is not locale-specific. Those
// values overridden by Supplemental Currency Data.
pattern = currencySupplementalOverride( currency, pattern, cldr );
return {
currency: currency,
pattern: pattern,
unitPatterns: currencyUnitPatterns( cldr )
};
};
/**
* nameFormat( formattedNumber, pluralForm, properties )
*
* Return the appropriate name form currency format.
*/
var currencyNameFormat = function( formattedNumber, pluralForm, properties ) {
var displayName, unitPattern,
displayNames = properties.displayNames || {},
unitPatterns = properties.unitPatterns;
displayName = displayNames[ "displayName-count-" + pluralForm ] ||
displayNames[ "displayName-count-other" ] ||
displayNames.displayName ||
properties.currency;
unitPattern = unitPatterns[ "unitPattern-count-" + pluralForm ] ||
unitPatterns[ "unitPattern-count-other" ];
return formatMessage( unitPattern, [ formattedNumber, displayName ]);
};
var currencyFormatterFn = function( numberFormatter, pluralGenerator, properties ) {
var fn;
// Return formatter when style is "code" or "name".
if ( pluralGenerator && properties ) {
fn = function currencyFormatter( value ) {
validateParameterPresence( value, "value" );
validateParameterTypeNumber( value, "value" );
return currencyNameFormat(
numberFormatter( value ),
pluralGenerator( value ),
properties
);
};
// Return formatter when style is "symbol" or "accounting".
} else {
fn = function currencyFormatter( value ) {
return numberFormatter( value );
};
}
return fn;
};
/**
* nameProperties( currency, cldr )
*
* Return number pattern with the appropriate currency code in as literal.
*/
var currencyNameProperties = function( currency, cldr ) {
var properties = currencyCodeProperties( currency, cldr );
properties.displayNames = objectFilter( cldr.main([
"numbers/currencies",
currency
]), /^displayName/ );
return properties;
};
/**
* Unicode regular expression for: everything except math symbols, currency signs, dingbats, and
* box-drawing characters.
*
* Generated by:
*
* regenerate()
* .addRange( 0x0, 0x10FFFF )
* .remove( require( "unicode-7.0.0/categories/S/symbols" ) ).toString();
*
* https://github.com/mathiasbynens/regenerate
* https://github.com/mathiasbynens/unicode-7.0.0
*/
var regexpNotS = /[\0-#%-\*,-;\?-\]_a-\{\}\x7F-\xA1\xA7\xAA\xAB\xAD\xB2\xB3\xB5-\xB7\xB9-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376-\u0383\u0386-\u03F5\u03F7-\u0481\u0483-\u058C\u0590-\u0605\u0609\u060A\u060C\u060D\u0610-\u06DD\u06DF-\u06E8\u06EA-\u06FC\u06FF-\u07F5\u07F7-\u09F1\u09F4-\u09F9\u09FC-\u0AF0\u0AF2-\u0B6F\u0B71-\u0BF2\u0BFB-\u0C7E\u0C80-\u0D78\u0D7A-\u0E3E\u0E40-\u0F00\u0F04-\u0F12\u0F14\u0F18\u0F19\u0F20-\u0F33\u0F35\u0F37\u0F39-\u0FBD\u0FC6\u0FCD\u0FD0-\u0FD4\u0FD9-\u109D\u10A0-\u138F\u139A-\u17DA\u17DC-\u193F\u1941-\u19DD\u1A00-\u1B60\u1B6B-\u1B73\u1B7D-\u1FBC\u1FBE\u1FC2-\u1FCC\u1FD0-\u1FDC\u1FE0-\u1FEC\u1FF0-\u1FFC\u1FFF-\u2043\u2045-\u2051\u2053-\u2079\u207D-\u2089\u208D-\u209F\u20BE-\u20FF\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2150-\u218F\u2308-\u230B\u2329\u232A\u23FB-\u23FF\u2427-\u243F\u244B-\u249B\u24EA-\u24FF\u2768-\u2793\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2B74\u2B75\u2B96\u2B97\u2BBA-\u2BBC\u2BC9\u2BD2-\u2CE4\u2CEB-\u2E7F\u2E9A\u2EF4-\u2EFF\u2FD6-\u2FEF\u2FFC-\u3003\u3005-\u3011\u3014-\u301F\u3021-\u3035\u3038-\u303D\u3040-\u309A\u309D-\u318F\u3192-\u3195\u31A0-\u31BF\u31E4-\u31FF\u321F-\u3229\u3248-\u324F\u3251-\u325F\u3280-\u3289\u32B1-\u32BF\u32FF\u3400-\u4DBF\u4E00-\uA48F\uA4C7-\uA6FF\uA717-\uA71F\uA722-\uA788\uA78B-\uA827\uA82C-\uA835\uA83A-\uAA76\uAA7A-\uAB5A\uAB5C-\uD7FF\uDC00-\uFB28\uFB2A-\uFBB1\uFBC2-\uFDFB\uFDFE-\uFE61\uFE63\uFE67\uFE68\uFE6A-\uFF03\uFF05-\uFF0A\uFF0C-\uFF1B\uFF1F-\uFF3D\uFF3F\uFF41-\uFF5B\uFF5D\uFF5F-\uFFDF\uFFE7\uFFEF-\uFFFB\uFFFE\uFFFF]|\uD800[\uDC00-\uDD36\uDD40-\uDD78\uDD8A\uDD8B\uDD8D-\uDD8F\uDD9C-\uDD9F\uDDA1-\uDDCF\uDDFD-\uDFFF]|[\uD801\uD803-\uD819\uD81B-\uD82E\uD830-\uD833\uD836-\uD83A\uD83F-\uDBFF][\uDC00-\uDFFF]|\uD802[\uDC00-\uDC76\uDC79-\uDEC7\uDEC9-\uDFFF]|\uD81A[\uDC00-\uDF3B\uDF40-\uDF44\uDF46-\uDFFF]|\uD82F[\uDC00-\uDC9B\uDC9D-\uDFFF]|\uD834[\uDCF6-\uDCFF\uDD27\uDD28\uDD65-\uDD69\uDD6D-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDDDE-\uDDFF\uDE42-\uDE44\uDE46-\uDEFF\uDF57-\uDFFF]|\uD835[\uDC00-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFFF]|\uD83B[\uDC00-\uDEEF\uDEF2-\uDFFF]|\uD83C[\uDC2C-\uDC2F\uDC94-\uDC9F\uDCAF\uDCB0\uDCC0\uDCD0\uDCF6-\uDD0F\uDD2F\uDD6C-\uDD6F\uDD9B-\uDDE5\uDE03-\uDE0F\uDE3B-\uDE3F\uDE49-\uDE4F\uDE52-\uDEFF\uDF2D-\uDF2F\uDF7E\uDF7F\uDFCF-\uDFD3\uDFF8-\uDFFF]|\uD83D[\uDCFF\uDD4B-\uDD4F\uDD7A\uDDA4\uDE43\uDE44\uDED0-\uDEDF\uDEED-\uDEEF\uDEF4-\uDEFF\uDF74-\uDF7F\uDFD5-\uDFFF]|\uD83E[\uDC0C-\uDC0F\uDC48-\uDC4F\uDC5A-\uDC5F\uDC88-\uDC8F\uDCAE-\uDFFF]|[\uD800-\uDBFF]/;
/**
* symbolProperties( currency, cldr )
*
* Return pattern replacing `¤` with the appropriate currency symbol literal.
*/
var currencySymbolProperties = function( currency, cldr, options ) {
var currencySpacing, pattern,
regexp = {
"[:digit:]": /\d/,
"[:^S:]": regexpNotS
},
symbol = cldr.main([
"numbers/currencies",
currency,
"symbol"
]);
currencySpacing = [ "beforeCurrency", "afterCurrency" ].map(function( position ) {
return cldr.main([
"numbers",
"currencyFormats-numberSystem-" + numberNumberingSystem( cldr ),
"currencySpacing",
position
]);
});
pattern = cldr.main([
"numbers",
"currencyFormats-numberSystem-" + numberNumberingSystem( cldr ),
options.style === "accounting" ? "accounting" : "standard"
]);
pattern =
// The number of decimal places and the rounding for each currency is not locale-specific.
// Those values are overridden by Supplemental Currency Data.
currencySupplementalOverride( currency, pattern, cldr )
// Replace "¤" (\u00A4) with the appropriate symbol literal.
.split( ";" ).map(function( pattern ) {
return pattern.split( "\u00A4" ).map(function( part, i ) {
var currencyMatch = regexp[ currencySpacing[ i ].currencyMatch ],
surroundingMatch = regexp[ currencySpacing[ i ].surroundingMatch ],
insertBetween = "";
// For currencyMatch and surroundingMatch definitions, read [1].
// When i === 0, beforeCurrency is being handled. Otherwise, afterCurrency.
// 1: http://www.unicode.org/reports/tr35/tr35-numbers.html#Currencies
currencyMatch = currencyMatch.test( symbol.charAt( i ? symbol.length - 1 : 0 ) );
surroundingMatch = surroundingMatch.test(
part.charAt( i ? 0 : part.length - 1 ).replace( /[#@,.]/g, "0" )
);
if ( currencyMatch && part && surroundingMatch ) {
insertBetween = currencySpacing[ i ].insertBetween;
}
return ( i ? insertBetween : "" ) + part + ( i ? "" : insertBetween );
}).join( "'" + symbol + "'" );
}).join( ";" );
return {
pattern: pattern
};
};
/**
* objectOmit( object, keys )
*
* Return a copy of the object, filtered to omit the blacklisted key or array of keys.
*/
var objectOmit = function( object, keys ) {
var key,
copy = {};
keys = alwaysArray( keys );
for ( key in object ) {
if ( keys.indexOf( key ) === -1 ) {
copy[ key ] = object[ key ];
}
}
return copy;
};
function validateRequiredCldr( path, value ) {
validateCldr( path, value, {
skip: [ /supplemental\/currencyData\/fractions\/[A-Za-z]{3}$/ ]
});
}
/**
* .currencyFormatter( currency [, options] )
*
* @currency [String] 3-letter currency code as defined by ISO 4217.
*
* @options [Object]:
* - style: [String] "symbol" (default), "accounting", "code" or "name".
* - see also number/format options.
*
* Return a function that formats a currency according to the given options and default/instance
* locale.
*/
Globalize.currencyFormatter =
Globalize.prototype.currencyFormatter = function( currency, options ) {
var args, cldr, numberFormatter, pluralGenerator, properties, returnFn, style;
validateParameterPresence( currency, "currency" );
validateParameterTypeCurrency( currency, "currency" );
validateParameterTypePlainObject( options, "options" );
cldr = this.cldr;
options = options || {};
args = [ currency, options ];
style = options.style || "symbol";
validateDefaultLocale( cldr );
// Get properties given style ("symbol" default, "code" or "name").
cldr.on( "get", validateRequiredCldr );
properties = ({
accounting: currencySymbolProperties,
code: currencyCodeProperties,
name: currencyNameProperties,
symbol: currencySymbolProperties
}[ style ] )( currency, cldr, options );
cldr.off( "get", validateRequiredCldr );
// options = options minus style, plus raw pattern.
options = objectOmit( options, "style" );
options.raw = properties.pattern;
// Return formatter when style is "symbol" or "accounting".
if ( style === "symbol" || style === "accounting" ) {
numberFormatter = this.numberFormatter( options );
returnFn = currencyFormatterFn( numberFormatter );
runtimeBind( args, cldr, returnFn, [ numberFormatter ] );
// Return formatter when style is "code" or "name".
} else {
numberFormatter = this.numberFormatter( options );
pluralGenerator = this.pluralGenerator();
returnFn = currencyFormatterFn( numberFormatter, pluralGenerator, properties );
runtimeBind( args, cldr, returnFn, [ numberFormatter, pluralGenerator, properties ] );
}
return returnFn;
};
/**
* .currencyParser( currency [, options] )
*
* @currency [String] 3-letter currency code as defined by ISO 4217.
*
* @options [Object] see currencyFormatter.
*
* Return the currency parser according to the given options and the default/instance locale.
*/
Globalize.currencyParser =
Globalize.prototype.currencyParser = function( /* currency, options */ ) {
// TODO implement parser.
};
/**
* .formatCurrency( value, currency [, options] )
*
* @value [Number] number to be formatted.
*
* @currency [String] 3-letter currency code as defined by ISO 4217.
*
* @options [Object] see currencyFormatter.
*
* Format a currency according to the given options and the default/instance locale.
*/
Globalize.formatCurrency =
Globalize.prototype.formatCurrency = function( value, currency, options ) {
validateParameterPresence( value, "value" );
validateParameterTypeNumber( value, "value" );
return this.currencyFormatter( currency, options )( value );
};
/**
* .parseCurrency( value, currency [, options] )
*
* @value [String]
*
* @currency [String] 3-letter currency code as defined by ISO 4217.
*
* @options [Object]: See currencyFormatter.
*
* Return the parsed currency or NaN when value is invalid.
*/
Globalize.parseCurrency =
Globalize.prototype.parseCurrency = function( /* value, currency, options */ ) {
};
return Globalize;
}));
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+373
View File
@@ -0,0 +1,373 @@
/**
* Globalize v1.1.1
*
* http://github.com/jquery/globalize
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2016-02-04T12:01Z
*/
/*!
* Globalize v1.1.1 2016-02-04T12:01Z Released under the MIT license
* http://git.io/TrdQbw
*/
(function( root, factory ) {
// UMD returnExports
if ( typeof define === "function" && define.amd ) {
// AMD
define([
"cldr",
"../globalize",
"cldr/event",
"cldr/supplemental"
], factory );
} else if ( typeof exports === "object" ) {
// Node, CommonJS
module.exports = factory( require( "cldrjs" ), require( "globalize" ) );
} else {
// Global
factory( root.Cldr, root.Globalize );
}
}(this, function( Cldr, Globalize ) {
var runtimeBind = Globalize._runtimeBind,
validateCldr = Globalize._validateCldr,
validateDefaultLocale = Globalize._validateDefaultLocale,
validateParameterPresence = Globalize._validateParameterPresence,
validateParameterType = Globalize._validateParameterType,
validateParameterTypePlainObject = Globalize._validateParameterTypePlainObject;
var MakePlural;
/* jshint ignore:start */
MakePlural = (function() {
'use strict';
var _toArray = function (arr) { return Array.isArray(arr) ? arr : Array.from(arr); };
var _toConsumableArray = function (arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
/**
* make-plural.js -- https://github.com/eemeli/make-plural.js/
* Copyright (c) 2014-2015 by Eemeli Aro <eemeli@gmail.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* The software is provided "as is" and the author disclaims all warranties
* with regard to this software including all implied warranties of
* merchantability and fitness. In no event shall the author be liable for
* any special, direct, indirect, or consequential damages or any damages
* whatsoever resulting from loss of use, data or profits, whether in an
* action of contract, negligence or other tortious action, arising out of
* or in connection with the use or performance of this software.
*/
var Parser = (function () {
function Parser() {
_classCallCheck(this, Parser);
}
_createClass(Parser, [{
key: 'parse',
value: function parse(cond) {
var _this = this;
if (cond === 'i = 0 or n = 1') {
return 'n >= 0 && n <= 1';
}if (cond === 'i = 0,1') {
return 'n >= 0 && n < 2';
}if (cond === 'i = 1 and v = 0') {
this.v0 = 1;
return 'n == 1 && v0';
}
return cond.replace(/([tv]) (!?)= 0/g, function (m, sym, noteq) {
var sn = sym + '0';
_this[sn] = 1;
return noteq ? '!' + sn : sn;
}).replace(/\b[fintv]\b/g, function (m) {
_this[m] = 1;
return m;
}).replace(/([fin]) % (10+)/g, function (m, sym, num) {
var sn = sym + num;
_this[sn] = 1;
return sn;
}).replace(/n10+ = 0/g, 't0 && $&').replace(/(\w+ (!?)= )([0-9.]+,[0-9.,]+)/g, function (m, se, noteq, x) {
if (m === 'n = 0,1') return '(n == 0 || n == 1)';
if (noteq) return se + x.split(',').join(' && ' + se);
return '(' + se + x.split(',').join(' || ' + se) + ')';
}).replace(/(\w+) (!?)= ([0-9]+)\.\.([0-9]+)/g, function (m, sym, noteq, x0, x1) {
if (Number(x0) + 1 === Number(x1)) {
if (noteq) return '' + sym + ' != ' + x0 + ' && ' + sym + ' != ' + x1;
return '(' + sym + ' == ' + x0 + ' || ' + sym + ' == ' + x1 + ')';
}
if (noteq) return '(' + sym + ' < ' + x0 + ' || ' + sym + ' > ' + x1 + ')';
if (sym === 'n') {
_this.t0 = 1;return '(t0 && n >= ' + x0 + ' && n <= ' + x1 + ')';
}
return '(' + sym + ' >= ' + x0 + ' && ' + sym + ' <= ' + x1 + ')';
}).replace(/ and /g, ' && ').replace(/ or /g, ' || ').replace(/ = /g, ' == ');
}
}, {
key: 'vars',
value: (function (_vars) {
function vars() {
return _vars.apply(this, arguments);
}
vars.toString = function () {
return _vars.toString();
};
return vars;
})(function () {
var vars = [];
if (this.i) vars.push('i = s[0]');
if (this.f || this.v) vars.push('f = s[1] || \'\'');
if (this.t) vars.push('t = (s[1] || \'\').replace(/0+$/, \'\')');
if (this.v) vars.push('v = f.length');
if (this.v0) vars.push('v0 = !s[1]');
if (this.t0 || this.n10 || this.n100) vars.push('t0 = Number(s[0]) == n');
for (var k in this) {
if (/^.10+$/.test(k)) {
var k0 = k[0] === 'n' ? 't0 && s[0]' : k[0];
vars.push('' + k + ' = ' + k0 + '.slice(-' + k.substr(2).length + ')');
}
}if (!vars.length) return '';
return 'var ' + ['s = String(n).split(\'.\')'].concat(vars).join(', ');
})
}]);
return Parser;
})();
var MakePlural = (function () {
function MakePlural(lc) {
var _ref = arguments[1] === undefined ? MakePlural : arguments[1];
var cardinals = _ref.cardinals;
var ordinals = _ref.ordinals;
_classCallCheck(this, MakePlural);
if (!cardinals && !ordinals) throw new Error('At least one type of plural is required');
this.lc = lc;
this.categories = { cardinal: [], ordinal: [] };
this.parser = new Parser();
this.fn = this.buildFunction(cardinals, ordinals);
this.fn._obj = this;
this.fn.categories = this.categories;
this.fn.toString = this.fnToString.bind(this);
return this.fn;
}
_createClass(MakePlural, [{
key: 'compile',
value: function compile(type, req) {
var cases = [];
var rules = MakePlural.rules[type][this.lc];
if (!rules) {
if (req) throw new Error('Locale "' + this.lc + '" ' + type + ' rules not found');
this.categories[type] = ['other'];
return '\'other\'';
}
for (var r in rules) {
var _rules$r$trim$split = rules[r].trim().split(/\s*@\w*/);
var _rules$r$trim$split2 = _toArray(_rules$r$trim$split);
var cond = _rules$r$trim$split2[0];
var examples = _rules$r$trim$split2.slice(1);
var cat = r.replace('pluralRule-count-', '');
if (cond) cases.push([this.parser.parse(cond), cat]);
}
this.categories[type] = cases.map(function (c) {
return c[1];
}).concat('other');
if (cases.length === 1) {
return '(' + cases[0][0] + ') ? \'' + cases[0][1] + '\' : \'other\'';
} else {
return [].concat(_toConsumableArray(cases.map(function (c) {
return '(' + c[0] + ') ? \'' + c[1] + '\'';
})), ['\'other\'']).join('\n : ');
}
}
}, {
key: 'buildFunction',
value: function buildFunction(cardinals, ordinals) {
var _this3 = this;
var compile = function compile(c) {
return c ? (c[1] ? 'return ' : 'if (ord) return ') + _this3.compile.apply(_this3, _toConsumableArray(c)) : '';
},
fold = { vars: function vars(str) {
return (' ' + str + ';').replace(/(.{1,78})(,|$) ?/g, '$1$2\n ');
},
cond: function cond(str) {
return (' ' + str + ';').replace(/(.{1,78}) (\|\| |$) ?/gm, '$1\n $2');
} },
cond = [ordinals && ['ordinal', !cardinals], cardinals && ['cardinal', true]].map(compile).map(fold.cond),
body = [fold.vars(this.parser.vars())].concat(_toConsumableArray(cond)).join('\n').replace(/\s+$/gm, '').replace(/^[\s;]*[\r\n]+/gm, ''),
args = ordinals && cardinals ? 'n, ord' : 'n';
return new Function(args, body);
}
}, {
key: 'fnToString',
value: function fnToString(name) {
return Function.prototype.toString.call(this.fn).replace(/^function( \w+)?/, name ? 'function ' + name : 'function').replace('\n/**/', '');
}
}], [{
key: 'load',
value: function load() {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
args.forEach(function (cldr) {
var data = cldr && cldr.supplemental || null;
if (!data) throw new Error('Data does not appear to be CLDR data');
MakePlural.rules = {
cardinal: data['plurals-type-cardinal'] || MakePlural.rules.cardinal,
ordinal: data['plurals-type-ordinal'] || MakePlural.rules.ordinal
};
});
return MakePlural;
}
}]);
return MakePlural;
})();
MakePlural.cardinals = true;
MakePlural.ordinals = false;
MakePlural.rules = { cardinal: {}, ordinal: {} };
return MakePlural;
}());
/* jshint ignore:end */
var validateParameterTypeNumber = function( value, name ) {
validateParameterType(
value,
name,
value === undefined || typeof value === "number",
"Number"
);
};
var validateParameterTypePluralType = function( value, name ) {
validateParameterType(
value,
name,
value === undefined || value === "cardinal" || value === "ordinal",
"String \"cardinal\" or \"ordinal\""
);
};
var pluralGeneratorFn = function( plural ) {
return function pluralGenerator( value ) {
validateParameterPresence( value, "value" );
validateParameterTypeNumber( value, "value" );
return plural( value );
};
};
/**
* .plural( value )
*
* @value [Number]
*
* Return the corresponding form (zero | one | two | few | many | other) of a
* value given locale.
*/
Globalize.plural =
Globalize.prototype.plural = function( value, options ) {
validateParameterPresence( value, "value" );
validateParameterTypeNumber( value, "value" );
return this.pluralGenerator( options )( value );
};
/**
* .pluralGenerator( [options] )
*
* Return a plural function (of the form below).
*
* fn( value )
*
* @value [Number]
*
* Return the corresponding form (zero | one | two | few | many | other) of a value given the
* default/instance locale.
*/
Globalize.pluralGenerator =
Globalize.prototype.pluralGenerator = function( options ) {
var args, cldr, isOrdinal, plural, returnFn, type;
validateParameterTypePlainObject( options, "options" );
options = options || {};
cldr = this.cldr;
args = [ options ];
type = options.type || "cardinal";
validateParameterTypePluralType( options.type, "options.type" );
validateDefaultLocale( cldr );
isOrdinal = type === "ordinal";
cldr.on( "get", validateCldr );
cldr.supplemental([ "plurals-type-" + type, "{language}" ]);
cldr.off( "get", validateCldr );
MakePlural.rules = {};
MakePlural.rules[ type ] = cldr.supplemental( "plurals-type-" + type );
plural = new MakePlural( cldr.attributes.language, {
"ordinals": isOrdinal,
"cardinals": !isOrdinal
});
returnFn = pluralGeneratorFn( plural );
runtimeBind( args, cldr, returnFn, [ plural ] );
return returnFn;
};
return Globalize;
}));
@@ -0,0 +1,201 @@
/**
* Globalize v1.1.1
*
* http://github.com/jquery/globalize
*
* Copyright 2010, 2014 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2016-02-04T12:01Z
*/
/*!
* Globalize v1.1.1 2016-02-04T12:01Z Released under the MIT license
* http://git.io/TrdQbw
*/
(function( root, factory ) {
// UMD returnExports
if ( typeof define === "function" && define.amd ) {
// AMD
define([
"cldr",
"../globalize",
"./number",
"./plural",
"cldr/event",
"cldr/supplemental"
], factory );
} else if ( typeof exports === "object" ) {
// Node, CommonJS
module.exports = factory( require( "cldrjs" ), require( "globalize" ) );
} else {
// Extend global
factory( root.Cldr, root.Globalize );
}
}(this, function( Cldr, Globalize ) {
var formatMessage = Globalize._formatMessage,
runtimeBind = Globalize._runtimeBind,
validateCldr = Globalize._validateCldr,
validateDefaultLocale = Globalize._validateDefaultLocale,
validateParameterPresence = Globalize._validateParameterPresence,
validateParameterTypeString = Globalize._validateParameterTypeString,
validateParameterTypeNumber = Globalize._validateParameterTypeNumber;
/**
* format( value, numberFormatter, pluralGenerator, properties )
*
* @value [Number] The number to format
*
* @numberFormatter [String] A numberFormatter from Globalize.numberFormatter
*
* @pluralGenerator [String] A pluralGenerator from Globalize.pluralGenerator
*
* @properties [Object] containing relative time plural message.
*
* Format relative time.
*/
var relativeTimeFormat = function( value, numberFormatter, pluralGenerator, properties ) {
var relativeTime,
message = properties[ "relative-type-" + value ];
if ( message ) {
return message;
}
relativeTime = value <= 0 ? properties[ "relativeTime-type-past" ]
: properties[ "relativeTime-type-future" ];
value = Math.abs( value );
message = relativeTime[ "relativeTimePattern-count-" + pluralGenerator( value ) ];
return formatMessage( message, [ numberFormatter( value ) ] );
};
var relativeTimeFormatterFn = function( numberFormatter, pluralGenerator, properties ) {
return function relativeTimeFormatter( value ) {
validateParameterPresence( value, "value" );
validateParameterTypeNumber( value, "value" );
return relativeTimeFormat( value, numberFormatter, pluralGenerator, properties );
};
};
/**
* properties( unit, cldr, options )
*
* @unit [String] eg. "day", "week", "month", etc.
*
* @cldr [Cldr instance].
*
* @options [Object]
* - form: [String] eg. "short" or "narrow". Or falsy for default long form.
*
* Return relative time properties.
*/
var relativeTimeProperties = function( unit, cldr, options ) {
var form = options.form,
raw, properties, key, match;
if ( form ) {
unit = unit + "-" + form;
}
raw = cldr.main( [ "dates", "fields", unit ] );
properties = {
"relativeTime-type-future": raw[ "relativeTime-type-future" ],
"relativeTime-type-past": raw[ "relativeTime-type-past" ]
};
for ( key in raw ) {
if ( raw.hasOwnProperty( key ) ) {
match = /relative-type-(-?[0-9]+)/.exec( key );
if ( match ) {
properties[ key ] = raw[ key ];
}
}
}
return properties;
};
/**
* .formatRelativeTime( value, unit [, options] )
*
* @value [Number] The number of unit to format.
*
* @unit [String] see .relativeTimeFormatter() for details.
*
* @options [Object] see .relativeTimeFormatter() for details.
*
* Formats a relative time according to the given unit, options, and the default/instance locale.
*/
Globalize.formatRelativeTime =
Globalize.prototype.formatRelativeTime = function( value, unit, options ) {
validateParameterPresence( value, "value" );
validateParameterTypeNumber( value, "value" );
return this.relativeTimeFormatter( unit, options )( value );
};
/**
* .relativeTimeFormatter( unit [, options ])
*
* @unit [String] String value indicating the unit to be formatted. eg. "day", "week", "month", etc.
*
* @options [Object]
* - form: [String] eg. "short" or "narrow". Or falsy for default long form.
*
* Returns a function that formats a relative time according to the given unit, options, and the
* default/instance locale.
*/
Globalize.relativeTimeFormatter =
Globalize.prototype.relativeTimeFormatter = function( unit, options ) {
var args, cldr, numberFormatter, pluralGenerator, properties, returnFn;
validateParameterPresence( unit, "unit" );
validateParameterTypeString( unit, "unit" );
cldr = this.cldr;
options = options || {};
args = [ unit, options ];
validateDefaultLocale( cldr );
cldr.on( "get", validateCldr );
properties = relativeTimeProperties( unit, cldr, options );
cldr.off( "get", validateCldr );
numberFormatter = this.numberFormatter( options );
pluralGenerator = this.pluralGenerator();
returnFn = relativeTimeFormatterFn( numberFormatter, pluralGenerator, properties );
runtimeBind( args, cldr, returnFn, [ numberFormatter, pluralGenerator, properties ] );
return returnFn;
};
return Globalize;
}));
+300
View File
@@ -0,0 +1,300 @@
/**
* Globalize v1.1.1
*
* http://github.com/jquery/globalize
*
* Copyright 2010, 2014 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2016-02-04T12:01Z
*/
/*!
* Globalize v1.1.1 2016-02-04T12:01Z Released under the MIT license
* http://git.io/TrdQbw
*/
(function( root, factory ) {
// UMD returnExports
if ( typeof define === "function" && define.amd ) {
// AMD
define([
"cldr",
"../globalize",
"./number",
"./plural"
], factory );
} else if ( typeof exports === "object" ) {
// Node, CommonJS
module.exports = factory( require( "cldrjs" ), require( "globalize" ) );
} else {
// Extend global
factory( root.Cldr, root.Globalize );
}
}(this, function( Cldr, Globalize ) {
var formatMessage = Globalize._formatMessage,
runtimeBind = Globalize._runtimeBind,
validateParameterPresence = Globalize._validateParameterPresence,
validateParameterTypePlainObject = Globalize._validateParameterTypePlainObject,
validateParameterTypeNumber = Globalize._validateParameterTypeNumber,
validateParameterTypeString = Globalize._validateParameterTypeString;
/**
* format( value, numberFormatter, pluralGenerator, unitProperies )
*
* @value [Number]
*
* @numberFormatter [Object]: A numberFormatter from Globalize.numberFormatter.
*
* @pluralGenerator [Object]: A pluralGenerator from Globalize.pluralGenerator.
*
* @unitProperies [Object]: localized unit data from cldr.
*
* Format units such as seconds, minutes, days, weeks, etc.
*
* OBS:
*
* Unit Sequences are not implemented.
* http://www.unicode.org/reports/tr35/tr35-35/tr35-general.html#Unit_Sequences
*
* Duration Unit (for composed time unit durations) is not implemented.
* http://www.unicode.org/reports/tr35/tr35-35/tr35-general.html#durationUnit
*/
var unitFormat = function( value, numberFormatter, pluralGenerator, unitProperties ) {
var compoundUnitPattern = unitProperties.compoundUnitPattern, dividend, dividendProperties,
formattedValue, divisor, divisorProperties, message, pluralValue;
unitProperties = unitProperties.unitProperties;
formattedValue = numberFormatter( value );
pluralValue = pluralGenerator( value );
// computed compound unit, eg. "megabyte-per-second".
if ( unitProperties instanceof Array ) {
dividendProperties = unitProperties[ 0 ];
divisorProperties = unitProperties[ 1 ];
dividend = formatMessage( dividendProperties[ pluralValue ], [ value ] );
divisor = formatMessage( divisorProperties.one, [ "" ] ).trim();
return formatMessage( compoundUnitPattern, [ dividend, divisor ] );
}
message = unitProperties[ pluralValue ];
return formatMessage( message, [ formattedValue ] );
};
var unitFormatterFn = function( numberFormatter, pluralGenerator, unitProperties ) {
return function unitFormatter( value ) {
validateParameterPresence( value, "value" );
validateParameterTypeNumber( value, "value" );
return unitFormat( value, numberFormatter, pluralGenerator, unitProperties );
};
};
/**
* categories()
*
* Return all unit categories.
*/
var unitCategories = [ "acceleration", "angle", "area", "digital", "duration", "length", "mass", "power",
"pressure", "speed", "temperature", "volume" ];
function stripPluralGarbage( data ) {
var aux, pluralCount;
if ( data ) {
aux = {};
for ( pluralCount in data ) {
aux[ pluralCount.replace( /unitPattern-count-/, "" ) ] = data[ pluralCount ];
}
}
return aux;
}
/**
* get( unit, form, cldr )
*
* @unit [String] The full type-unit name (eg. duration-second), or the short unit name
* (eg. second).
*
* @form [String] A string describing the form of the unit representation (eg. long,
* short, narrow).
*
* @cldr [Cldr instance].
*
* Return the plural map of a unit, eg: "second"
* { "one": "{0} second",
* "other": "{0} seconds" }
* }
*
* Or the Array of plural maps of a compound-unit, eg: "foot-per-second"
* [ { "one": "{0} foot",
* "other": "{0} feet" },
* { "one": "{0} second",
* "other": "{0} seconds" } ]
*
* Uses the precomputed form of a compound-unit if available, eg: "mile-per-hour"
* { "displayName": "miles per hour",
* "unitPattern-count-one": "{0} mile per hour",
* "unitPattern-count-other": "{0} miles per hour"
* },
*
* Also supports "/" instead of "-per-", eg. "foot/second", using the precomputed form if
* available.
*
* Or the Array of plural maps of a compound-unit, eg: "foot-per-second"
* [ { "one": "{0} foot",
* "other": "{0} feet" },
* { "one": "{0} second",
* "other": "{0} seconds" } ]
*
* Or undefined in case the unit (or a unit of the compound-unit) doesn't exist.
*/
var get = function( unit, form, cldr ) {
var ret;
// Ensure that we get the 'precomputed' form, if present.
unit = unit.replace( /\//, "-per-" );
// Get unit or <category>-unit (eg. "duration-second").
[ "" ].concat( unitCategories ).some(function( category ) {
return ret = cldr.main([
"units",
form,
category.length ? category + "-" + unit : unit
]);
});
// Rename keys s/unitPattern-count-//g.
ret = stripPluralGarbage( ret );
// Compound Unit, eg. "foot-per-second" or "foot/second".
if ( !ret && ( /-per-/ ).test( unit ) ) {
// "Some units already have 'precomputed' forms, such as kilometer-per-hour;
// where such units exist, they should be used in preference" UTS#35.
// Note that precomputed form has already been handled above (!ret).
// Get both recursively.
unit = unit.split( "-per-" );
ret = unit.map(function( unit ) {
return get( unit, form, cldr );
});
if ( !ret[ 0 ] || !ret[ 1 ] ) {
return;
}
}
return ret;
};
var unitGet = get;
/**
* properties( unit, form, cldr )
*
* @unit [String] The full type-unit name (eg. duration-second), or the short unit name
* (eg. second).
*
* @form [String] A string describing the form of the unit representation (eg. long,
* short, narrow).
*
* @cldr [Cldr instance].
*/
var unitProperties = function( unit, form, cldr ) {
var compoundUnitPattern, unitProperties;
compoundUnitPattern = cldr.main( [ "units", form, "per/compoundUnitPattern" ] );
unitProperties = unitGet( unit, form, cldr );
return {
compoundUnitPattern: compoundUnitPattern,
unitProperties: unitProperties
};
};
/**
* Globalize.formatUnit( value, unit, options )
*
* @value [Number]
*
* @unit [String]: The unit (e.g "second", "day", "year")
*
* @options [Object]
* - form: [String] "long", "short" (default), or "narrow".
*
* Format units such as seconds, minutes, days, weeks, etc.
*/
Globalize.formatUnit =
Globalize.prototype.formatUnit = function( value, unit, options ) {
validateParameterPresence( value, "value" );
validateParameterTypeNumber( value, "value" );
return this.unitFormatter( unit, options )( value );
};
/**
* Globalize.unitFormatter( unit, options )
*
* @unit [String]: The unit (e.g "second", "day", "year")
*
* @options [Object]
* - form: [String] "long", "short" (default), or "narrow".
*
* - numberFormatter: [Function] a number formatter function. Defaults to Globalize
* `.numberFormatter()` for the current locale using the default options.
*/
Globalize.unitFormatter =
Globalize.prototype.unitFormatter = function( unit, options ) {
var args, form, numberFormatter, pluralGenerator, returnFn, properties;
validateParameterPresence( unit, "unit" );
validateParameterTypeString( unit, "unit" );
validateParameterTypePlainObject( options, "options" );
options = options || {};
args = [ unit, options ];
form = options.form || "long";
properties = unitProperties( unit, form, this.cldr );
numberFormatter = options.numberFormatter || this.numberFormatter();
pluralGenerator = this.pluralGenerator();
returnFn = unitFormatterFn( numberFormatter, pluralGenerator, properties );
runtimeBind( args, this.cldr, returnFn, [ numberFormatter, pluralGenerator, properties ] );
return returnFn;
};
return Globalize;
}));
@@ -0,0 +1,49 @@
/*!
** An extension to the jQuery Validation Plugin which makes it use Globalize.js for number and date parsing
** Copyright (c) 2013 John Reilly
*/
(function ($, Globalize) {
// Clone original methods we want to call into
var originalMethods = {
min: $.validator.methods.min,
max: $.validator.methods.max,
range: $.validator.methods.range
};
// Globalize options - initially just the date format used for parsing
// Users can customise this to suit them
$.validator.methods.dateGlobalizeOptions = { dateParseFormat: { skeleton: "yMd" } };
// Tell the validator that we want numbers parsed using Globalize
$.validator.methods.number = function (value, element) {
var val = Globalize.parseNumber(value);
return this.optional(element) || ($.isNumeric(val));
};
// Tell the validator that we want dates parsed using Globalize
$.validator.methods.date = function (value, element) {
var val = Globalize.parseDate(value, $.validator.methods.dateGlobalizeOptions.dateParseFormat);
return this.optional(element) || (val instanceof Date);
};
// Tell the validator that we want numbers parsed using Globalize,
// then call into original implementation with parsed value
$.validator.methods.min = function (value, element, param) {
var val = Globalize.parseNumber(value);
return originalMethods.min.call(this, val, element, param);
};
$.validator.methods.max = function (value, element, param) {
var val = Globalize.parseNumber(value);
return originalMethods.max.call(this, val, element, param);
};
$.validator.methods.range = function (value, element, param) {
var val = Globalize.parseNumber(value);
return originalMethods.range.call(this, val, element, param);
};
}(jQuery, Globalize));
+1
View File
@@ -0,0 +1 @@
!function(a,t){var e={min:a.validator.methods.min,max:a.validator.methods.max,range:a.validator.methods.range};a.validator.methods.dateGlobalizeOptions={dateParseFormat:{skeleton:"yMd"}},a.validator.methods.number=function(e,r){var o=t.parseNumber(e);return this.optional(r)||a.isNumeric(o)},a.validator.methods.date=function(e,r){var o=t.parseDate(e,a.validator.methods.dateGlobalizeOptions.dateParseFormat);return this.optional(r)||o instanceof Date},a.validator.methods.min=function(a,r,o){var i=t.parseNumber(a);return e.min.call(this,i,r,o)},a.validator.methods.max=function(a,r,o){var i=t.parseNumber(a);return e.max.call(this,i,r,o)},a.validator.methods.range=function(a,r,o){var i=t.parseNumber(a);return e.range.call(this,i,r,o)}}(jQuery,Globalize);
+14
View File
@@ -335,6 +335,18 @@
<None Include="Properties\PublishProfiles\IIS01.pubxml" />
<None Include="Properties\PublishProfiles\IIS02.pubxml" />
<None Include="Scripts\jquery-3.1.0.intellisense.js" />
<Content Include="Scripts\cldr.js" />
<Content Include="Scripts\cldr\event.js" />
<Content Include="Scripts\cldr\supplemental.js" />
<Content Include="Scripts\cldr\unresolved.js" />
<Content Include="Scripts\globalize.js" />
<Content Include="Scripts\globalize\currency.js" />
<Content Include="Scripts\globalize\date.js" />
<Content Include="Scripts\globalize\message.js" />
<Content Include="Scripts\globalize\number.js" />
<Content Include="Scripts\globalize\plural.js" />
<Content Include="Scripts\globalize\relative-time.js" />
<Content Include="Scripts\globalize\unit.js" />
<Content Include="Scripts\gridmvc.js" />
<Content Include="Scripts\gridmvc.lang.ru.js" />
<Content Include="Scripts\gridmvc.min.js" />
@@ -347,6 +359,8 @@
<None Include="Scripts\jquery.validate-vsdoc.js" />
<Content Include="Scripts\jquery-ui-1.12.1.js" />
<Content Include="Scripts\jquery-ui-1.12.1.min.js" />
<Content Include="Scripts\jquery.validate.globalize.js" />
<Content Include="Scripts\jquery.validate.globalize.min.js" />
<Content Include="Scripts\jquery.validate.js" />
<Content Include="Scripts\jquery.validate.min.js" />
<Content Include="Scripts\jquery.validate.unobtrusive.js" />
+2 -2
View File
@@ -52,7 +52,7 @@
<div class="form-group">
@Html.LabelFor(model => model.dtMov, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.dtMov, new { htmlAttributes = new { @class = "form-control date-picker", type="date" } })
@Html.EditorFor(model => model.dtMov, "DateTime", new { htmlAttributes = new { @class = "form-control date-picker", type="date" } })
@Html.ValidationMessageFor(model => model.dtMov, "", new { @class = "text-danger" })
</div>
</div>
@@ -74,7 +74,7 @@
</div>
<div class="form-group">
@Html.LabelFor(model => model.UnitVal, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.LabelFor(model => model.UnitVal, "Double", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.UnitVal, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.UnitVal, "", new { @class = "text-danger" })
+3
View File
@@ -83,6 +83,9 @@
@*@Scripts.Render("~/bundles/jqbootgrid")*@
@Scripts.Render("~/bundles/jqueryval")
@RenderSection("scripts", required: false)
</body>
</html>
Binary file not shown.
+3
View File
@@ -2,6 +2,7 @@
<packages>
<package id="Antlr" version="3.5.0.2" targetFramework="net462" />
<package id="bootstrap" version="3.3.7" targetFramework="net462" />
<package id="cldrjs" version="0.4.4" targetFramework="net462" />
<package id="EntityFramework" version="6.1.3" targetFramework="net462" />
<package id="FontAwesome" version="4.6.3" targetFramework="net462" />
<package id="Glimpse" version="1.8.6" targetFramework="net462" />
@@ -13,6 +14,8 @@
<package id="jQuery" version="3.1.0" targetFramework="net462" />
<package id="jQuery.UI.Combined" version="1.12.1" targetFramework="net462" />
<package id="jQuery.Validation" version="1.15.1" targetFramework="net462" />
<package id="jQuery.Validation.Globalize" version="1.1.0" targetFramework="net462" />
<package id="jquery-globalize" version="1.1.1" targetFramework="net462" />
<package id="Microsoft.AspNet.Mvc" version="5.2.3" targetFramework="net462" />
<package id="Microsoft.AspNet.Razor" version="3.2.3" targetFramework="net462" />
<package id="Microsoft.AspNet.Web.Optimization" version="1.1.3" targetFramework="net462" />
Binary file not shown.
+676
View File
@@ -0,0 +1,676 @@
/**
* CLDR JavaScript Library v0.4.4
* http://jquery.com/
*
* Copyright 2013 Rafael Xavier de Souza
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2016-01-18T12:25Z
*/
/*!
* CLDR JavaScript Library v0.4.4 2016-01-18T12:25Z MIT license © Rafael Xavier
* http://git.io/h4lmVg
*/
(function( root, factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD.
define( factory );
} else if ( typeof module === "object" && typeof module.exports === "object" ) {
// Node. CommonJS.
module.exports = factory();
} else {
// Global
root.Cldr = factory();
}
}( this, function() {
var arrayIsArray = Array.isArray || function( obj ) {
return Object.prototype.toString.call( obj ) === "[object Array]";
};
var pathNormalize = function( path, attributes ) {
if ( arrayIsArray( path ) ) {
path = path.join( "/" );
}
if ( typeof path !== "string" ) {
throw new Error( "invalid path \"" + path + "\"" );
}
// 1: Ignore leading slash `/`
// 2: Ignore leading `cldr/`
path = path
.replace( /^\// , "" ) /* 1 */
.replace( /^cldr\// , "" ); /* 2 */
// Replace {attribute}'s
path = path.replace( /{[a-zA-Z]+}/g, function( name ) {
name = name.replace( /^{([^}]*)}$/, "$1" );
return attributes[ name ];
});
return path.split( "/" );
};
var arraySome = function( array, callback ) {
var i, length;
if ( array.some ) {
return array.some( callback );
}
for ( i = 0, length = array.length; i < length; i++ ) {
if ( callback( array[ i ], i, array ) ) {
return true;
}
}
return false;
};
/**
* Return the maximized language id as defined in
* http://www.unicode.org/reports/tr35/#Likely_Subtags
* 1. Canonicalize.
* 1.1 Make sure the input locale is in canonical form: uses the right
* separator, and has the right casing.
* TODO Right casing? What df? It seems languages are lowercase, scripts are
* Capitalized, territory is uppercase. I am leaving this as an exercise to
* the user.
*
* 1.2 Replace any deprecated subtags with their canonical values using the
* <alias> data in supplemental metadata. Use the first value in the
* replacement list, if it exists. Language tag replacements may have multiple
* parts, such as "sh" ➞ "sr_Latn" or mo" ➞ "ro_MD". In such a case, the
* original script and/or region are retained if there is one. Thus
* "sh_Arab_AQ" ➞ "sr_Arab_AQ", not "sr_Latn_AQ".
* TODO What <alias> data?
*
* 1.3 If the tag is grandfathered (see <variable id="$grandfathered"
* type="choice"> in the supplemental data), then return it.
* TODO grandfathered?
*
* 1.4 Remove the script code 'Zzzz' and the region code 'ZZ' if they occur.
* 1.5 Get the components of the cleaned-up source tag (languages, scripts,
* and regions), plus any variants and extensions.
* 2. Lookup. Lookup each of the following in order, and stop on the first
* match:
* 2.1 languages_scripts_regions
* 2.2 languages_regions
* 2.3 languages_scripts
* 2.4 languages
* 2.5 und_scripts
* 3. Return
* 3.1 If there is no match, either return an error value, or the match for
* "und" (in APIs where a valid language tag is required).
* 3.2 Otherwise there is a match = languagem_scriptm_regionm
* 3.3 Let xr = xs if xs is not empty, and xm otherwise.
* 3.4 Return the language tag composed of languager _ scriptr _ regionr +
* variants + extensions.
*
* @subtags [Array] normalized language id subtags tuple (see init.js).
*/
var coreLikelySubtags = function( Cldr, cldr, subtags, options ) {
var match, matchFound,
language = subtags[ 0 ],
script = subtags[ 1 ],
sep = Cldr.localeSep,
territory = subtags[ 2 ],
variantsAndUnicodeLocaleExtensions = subtags.slice( 3, 4 );
options = options || {};
// Skip if (language, script, territory) is not empty [3.3]
if ( language !== "und" && script !== "Zzzz" && territory !== "ZZ" ) {
return [ language, script, territory ].concat( variantsAndUnicodeLocaleExtensions );
}
// Skip if no supplemental likelySubtags data is present
if ( typeof cldr.get( "supplemental/likelySubtags" ) === "undefined" ) {
return;
}
// [2]
matchFound = arraySome([
[ language, script, territory ],
[ language, territory ],
[ language, script ],
[ language ],
[ "und", script ]
], function( test ) {
return match = !(/\b(Zzzz|ZZ)\b/).test( test.join( sep ) ) /* [1.4] */ && cldr.get( [ "supplemental/likelySubtags", test.join( sep ) ] );
});
// [3]
if ( matchFound ) {
// [3.2 .. 3.4]
match = match.split( sep );
return [
language !== "und" ? language : match[ 0 ],
script !== "Zzzz" ? script : match[ 1 ],
territory !== "ZZ" ? territory : match[ 2 ]
].concat(
variantsAndUnicodeLocaleExtensions
);
} else if ( options.force ) {
// [3.1.2]
return cldr.get( "supplemental/likelySubtags/und" ).split( sep );
} else {
// [3.1.1]
return;
}
};
/**
* Given a locale, remove any fields that Add Likely Subtags would add.
* http://www.unicode.org/reports/tr35/#Likely_Subtags
* 1. First get max = AddLikelySubtags(inputLocale). If an error is signaled,
* return it.
* 2. Remove the variants from max.
* 3. Then for trial in {language, language _ region, language _ script}. If
* AddLikelySubtags(trial) = max, then return trial + variants.
* 4. If you do not get a match, return max + variants.
*
* @maxLanguageId [Array] maxLanguageId tuple (see init.js).
*/
var coreRemoveLikelySubtags = function( Cldr, cldr, maxLanguageId ) {
var match, matchFound,
language = maxLanguageId[ 0 ],
script = maxLanguageId[ 1 ],
territory = maxLanguageId[ 2 ],
variants = maxLanguageId[ 3 ];
// [3]
matchFound = arraySome([
[ [ language, "Zzzz", "ZZ" ], [ language ] ],
[ [ language, "Zzzz", territory ], [ language, territory ] ],
[ [ language, script, "ZZ" ], [ language, script ] ]
], function( test ) {
var result = coreLikelySubtags( Cldr, cldr, test[ 0 ] );
match = test[ 1 ];
return result && result[ 0 ] === maxLanguageId[ 0 ] &&
result[ 1 ] === maxLanguageId[ 1 ] &&
result[ 2 ] === maxLanguageId[ 2 ];
});
if ( matchFound ) {
if ( variants ) {
match.push( variants );
}
return match;
}
// [4]
return maxLanguageId;
};
/**
* subtags( locale )
*
* @locale [String]
*/
var coreSubtags = function( locale ) {
var aux, unicodeLanguageId,
subtags = [];
locale = locale.replace( /_/, "-" );
// Unicode locale extensions.
aux = locale.split( "-u-" );
if ( aux[ 1 ] ) {
aux[ 1 ] = aux[ 1 ].split( "-t-" );
locale = aux[ 0 ] + ( aux[ 1 ][ 1 ] ? "-t-" + aux[ 1 ][ 1 ] : "");
subtags[ 4 /* unicodeLocaleExtensions */ ] = aux[ 1 ][ 0 ];
}
// TODO normalize transformed extensions. Currently, skipped.
// subtags[ x ] = locale.split( "-t-" )[ 1 ];
unicodeLanguageId = locale.split( "-t-" )[ 0 ];
// unicode_language_id = "root"
// | unicode_language_subtag
// (sep unicode_script_subtag)?
// (sep unicode_region_subtag)?
// (sep unicode_variant_subtag)* ;
//
// Although unicode_language_subtag = alpha{2,8}, I'm using alpha{2,3}. Because, there's no language on CLDR lengthier than 3.
aux = unicodeLanguageId.match( /^(([a-z]{2,3})(-([A-Z][a-z]{3}))?(-([A-Z]{2}|[0-9]{3}))?)((-([a-zA-Z0-9]{5,8}|[0-9][a-zA-Z0-9]{3}))*)$|^(root)$/ );
if ( aux === null ) {
return [ "und", "Zzzz", "ZZ" ];
}
subtags[ 0 /* language */ ] = aux[ 10 ] /* root */ || aux[ 2 ] || "und";
subtags[ 1 /* script */ ] = aux[ 4 ] || "Zzzz";
subtags[ 2 /* territory */ ] = aux[ 6 ] || "ZZ";
if ( aux[ 7 ] && aux[ 7 ].length ) {
subtags[ 3 /* variant */ ] = aux[ 7 ].slice( 1 ) /* remove leading "-" */;
}
// 0: language
// 1: script
// 2: territory (aka region)
// 3: variant
// 4: unicodeLocaleExtensions
return subtags;
};
var arrayForEach = function( array, callback ) {
var i, length;
if ( array.forEach ) {
return array.forEach( callback );
}
for ( i = 0, length = array.length; i < length; i++ ) {
callback( array[ i ], i, array );
}
};
/**
* bundleLookup( minLanguageId )
*
* @Cldr [Cldr class]
*
* @cldr [Cldr instance]
*
* @minLanguageId [String] requested languageId after applied remove likely subtags.
*/
var bundleLookup = function( Cldr, cldr, minLanguageId ) {
var availableBundleMap = Cldr._availableBundleMap,
availableBundleMapQueue = Cldr._availableBundleMapQueue;
if ( availableBundleMapQueue.length ) {
arrayForEach( availableBundleMapQueue, function( bundle ) {
var existing, maxBundle, minBundle, subtags;
subtags = coreSubtags( bundle );
maxBundle = coreLikelySubtags( Cldr, cldr, subtags );
minBundle = coreRemoveLikelySubtags( Cldr, cldr, maxBundle );
minBundle = minBundle.join( Cldr.localeSep );
existing = availableBundleMapQueue[ minBundle ];
if ( existing && existing.length < bundle.length ) {
return;
}
availableBundleMap[ minBundle ] = bundle;
});
Cldr._availableBundleMapQueue = [];
}
return availableBundleMap[ minLanguageId ] || null;
};
var objectKeys = function( object ) {
var i,
result = [];
if ( Object.keys ) {
return Object.keys( object );
}
for ( i in object ) {
result.push( i );
}
return result;
};
var createError = function( code, attributes ) {
var error, message;
message = code + ( attributes && JSON ? ": " + JSON.stringify( attributes ) : "" );
error = new Error( message );
error.code = code;
// extend( error, attributes );
arrayForEach( objectKeys( attributes ), function( attribute ) {
error[ attribute ] = attributes[ attribute ];
});
return error;
};
var validate = function( code, check, attributes ) {
if ( !check ) {
throw createError( code, attributes );
}
};
var validatePresence = function( value, name ) {
validate( "E_MISSING_PARAMETER", typeof value !== "undefined", {
name: name
});
};
var validateType = function( value, name, check, expected ) {
validate( "E_INVALID_PAR_TYPE", check, {
expected: expected,
name: name,
value: value
});
};
var validateTypePath = function( value, name ) {
validateType( value, name, typeof value === "string" || arrayIsArray( value ), "String or Array" );
};
/**
* Function inspired by jQuery Core, but reduced to our use case.
*/
var isPlainObject = function( obj ) {
return obj !== null && "" + obj === "[object Object]";
};
var validateTypePlainObject = function( value, name ) {
validateType( value, name, typeof value === "undefined" || isPlainObject( value ), "Plain Object" );
};
var validateTypeString = function( value, name ) {
validateType( value, name, typeof value === "string", "a string" );
};
// @path: normalized path
var resourceGet = function( data, path ) {
var i,
node = data,
length = path.length;
for ( i = 0; i < length - 1; i++ ) {
node = node[ path[ i ] ];
if ( !node ) {
return undefined;
}
}
return node[ path[ i ] ];
};
/**
* setAvailableBundles( Cldr, json )
*
* @Cldr [Cldr class]
*
* @json resolved/unresolved cldr data.
*
* Set available bundles queue based on passed json CLDR data. Considers a bundle as any String at /main/{bundle}.
*/
var coreSetAvailableBundles = function( Cldr, json ) {
var bundle,
availableBundleMapQueue = Cldr._availableBundleMapQueue,
main = resourceGet( json, [ "main" ] );
if ( main ) {
for ( bundle in main ) {
if ( main.hasOwnProperty( bundle ) && bundle !== "root" &&
availableBundleMapQueue.indexOf( bundle ) === -1 ) {
availableBundleMapQueue.push( bundle );
}
}
}
};
var alwaysArray = function( somethingOrArray ) {
return arrayIsArray( somethingOrArray ) ? somethingOrArray : [ somethingOrArray ];
};
var jsonMerge = (function() {
// Returns new deeply merged JSON.
//
// Eg.
// merge( { a: { b: 1, c: 2 } }, { a: { b: 3, d: 4 } } )
// -> { a: { b: 3, c: 2, d: 4 } }
//
// @arguments JSON's
//
var merge = function() {
var destination = {},
sources = [].slice.call( arguments, 0 );
arrayForEach( sources, function( source ) {
var prop;
for ( prop in source ) {
if ( prop in destination && typeof destination[ prop ] === "object" && !arrayIsArray( destination[ prop ] ) ) {
// Merge Objects
destination[ prop ] = merge( destination[ prop ], source[ prop ] );
} else {
// Set new values
destination[ prop ] = source[ prop ];
}
}
});
return destination;
};
return merge;
}());
/**
* load( Cldr, source, jsons )
*
* @Cldr [Cldr class]
*
* @source [Object]
*
* @jsons [arguments]
*/
var coreLoad = function( Cldr, source, jsons ) {
var i, j, json;
validatePresence( jsons[ 0 ], "json" );
// Support arbitrary parameters, e.g., `Cldr.load({...}, {...})`.
for ( i = 0; i < jsons.length; i++ ) {
// Support array parameters, e.g., `Cldr.load([{...}, {...}])`.
json = alwaysArray( jsons[ i ] );
for ( j = 0; j < json.length; j++ ) {
validateTypePlainObject( json[ j ], "json" );
source = jsonMerge( source, json[ j ] );
coreSetAvailableBundles( Cldr, json[ j ] );
}
}
return source;
};
var itemGetResolved = function( Cldr, path, attributes ) {
// Resolve path
var normalizedPath = pathNormalize( path, attributes );
return resourceGet( Cldr._resolved, normalizedPath );
};
/**
* new Cldr()
*/
var Cldr = function( locale ) {
this.init( locale );
};
// Build optimization hack to avoid duplicating functions across modules.
Cldr._alwaysArray = alwaysArray;
Cldr._coreLoad = coreLoad;
Cldr._createError = createError;
Cldr._itemGetResolved = itemGetResolved;
Cldr._jsonMerge = jsonMerge;
Cldr._pathNormalize = pathNormalize;
Cldr._resourceGet = resourceGet;
Cldr._validatePresence = validatePresence;
Cldr._validateType = validateType;
Cldr._validateTypePath = validateTypePath;
Cldr._validateTypePlainObject = validateTypePlainObject;
Cldr._availableBundleMap = {};
Cldr._availableBundleMapQueue = [];
Cldr._resolved = {};
// Allow user to override locale separator "-" (default) | "_". According to http://www.unicode.org/reports/tr35/#Unicode_language_identifier, both "-" and "_" are valid locale separators (eg. "en_GB", "en-GB"). According to http://unicode.org/cldr/trac/ticket/6786 its usage must be consistent throughout the data set.
Cldr.localeSep = "-";
/**
* Cldr.load( json [, json, ...] )
*
* @json [JSON] CLDR data or [Array] Array of @json's.
*
* Load resolved cldr data.
*/
Cldr.load = function() {
Cldr._resolved = coreLoad( Cldr, Cldr._resolved, arguments );
};
/**
* .init() automatically run on instantiation/construction.
*/
Cldr.prototype.init = function( locale ) {
var attributes, language, maxLanguageId, minLanguageId, script, subtags, territory, unicodeLocaleExtensions, variant,
sep = Cldr.localeSep;
validatePresence( locale, "locale" );
validateTypeString( locale, "locale" );
subtags = coreSubtags( locale );
unicodeLocaleExtensions = subtags[ 4 ];
variant = subtags[ 3 ];
// Normalize locale code.
// Get (or deduce) the "triple subtags": language, territory (also aliased as region), and script subtags.
// Get the variant subtags (calendar, collation, currency, etc).
// refs:
// - http://www.unicode.org/reports/tr35/#Field_Definitions
// - http://www.unicode.org/reports/tr35/#Language_and_Locale_IDs
// - http://www.unicode.org/reports/tr35/#Unicode_locale_identifier
// When a locale id does not specify a language, or territory (region), or script, they are obtained by Likely Subtags.
maxLanguageId = coreLikelySubtags( Cldr, this, subtags, { force: true } ) || subtags;
language = maxLanguageId[ 0 ];
script = maxLanguageId[ 1 ];
territory = maxLanguageId[ 2 ];
minLanguageId = coreRemoveLikelySubtags( Cldr, this, maxLanguageId ).join( sep );
// Set attributes
this.attributes = attributes = {
bundle: bundleLookup( Cldr, this, minLanguageId ),
// Unicode Language Id
minlanguageId: minLanguageId,
maxLanguageId: maxLanguageId.join( sep ),
// Unicode Language Id Subtabs
language: language,
script: script,
territory: territory,
region: territory, /* alias */
variant: variant
};
// Unicode locale extensions.
unicodeLocaleExtensions && ( "-" + unicodeLocaleExtensions ).replace( /-[a-z]{3,8}|(-[a-z]{2})-([a-z]{3,8})/g, function( attribute, key, type ) {
if ( key ) {
// Extension is in the `keyword` form.
attributes[ "u" + key ] = type;
} else {
// Extension is in the `attribute` form.
attributes[ "u" + attribute ] = true;
}
});
this.locale = locale;
};
/**
* .get()
*/
Cldr.prototype.get = function( path ) {
validatePresence( path, "path" );
validateTypePath( path, "path" );
return itemGetResolved( Cldr, path, this.attributes );
};
/**
* .main()
*/
Cldr.prototype.main = function( path ) {
validatePresence( path, "path" );
validateTypePath( path, "path" );
validate( "E_MISSING_BUNDLE", this.attributes.bundle !== null, {
locale: this.locale
});
path = alwaysArray( path );
return this.get( [ "main/{bundle}" ].concat( path ) );
};
return Cldr;
}));
+585
View File
@@ -0,0 +1,585 @@
/**
* CLDR JavaScript Library v0.4.4
* http://jquery.com/
*
* Copyright 2013 Rafael Xavier de Souza
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2016-01-18T12:25Z
*/
/*!
* CLDR JavaScript Library v0.4.4 2016-01-18T12:25Z MIT license © Rafael Xavier
* http://git.io/h4lmVg
*/
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD.
define( [ "../cldr" ], factory );
} else if ( typeof module === "object" && typeof module.exports === "object" ) {
// Node. CommonJS.
module.exports = factory( require( "cldrjs" ) );
} else {
// Global
factory( Cldr );
}
}(function( Cldr ) {
// Build optimization hack to avoid duplicating functions across modules.
var pathNormalize = Cldr._pathNormalize,
validatePresence = Cldr._validatePresence,
validateType = Cldr._validateType;
/*!
* EventEmitter v4.2.7 - git.io/ee
* Oliver Caldwell
* MIT license
* @preserve
*/
var EventEmitter;
/* jshint ignore:start */
EventEmitter = (function () {
/**
* Class for managing events.
* Can be extended to provide event functionality in other classes.
*
* @class EventEmitter Manages event registering and emitting.
*/
function EventEmitter() {}
// Shortcuts to improve speed and size
var proto = EventEmitter.prototype;
var exports = this;
var originalGlobalValue = exports.EventEmitter;
/**
* Finds the index of the listener for the event in it's storage array.
*
* @param {Function[]} listeners Array of listeners to search through.
* @param {Function} listener Method to look for.
* @return {Number} Index of the specified listener, -1 if not found
* @api private
*/
function indexOfListener(listeners, listener) {
var i = listeners.length;
while (i--) {
if (listeners[i].listener === listener) {
return i;
}
}
return -1;
}
/**
* Alias a method while keeping the context correct, to allow for overwriting of target method.
*
* @param {String} name The name of the target method.
* @return {Function} The aliased method
* @api private
*/
function alias(name) {
return function aliasClosure() {
return this[name].apply(this, arguments);
};
}
/**
* Returns the listener array for the specified event.
* Will initialise the event object and listener arrays if required.
* Will return an object if you use a regex search. The object contains keys for each matched event. So /ba[rz]/ might return an object containing bar and baz. But only if you have either defined them with defineEvent or added some listeners to them.
* Each property in the object response is an array of listener functions.
*
* @param {String|RegExp} evt Name of the event to return the listeners from.
* @return {Function[]|Object} All listener functions for the event.
*/
proto.getListeners = function getListeners(evt) {
var events = this._getEvents();
var response;
var key;
// Return a concatenated array of all matching events if
// the selector is a regular expression.
if (evt instanceof RegExp) {
response = {};
for (key in events) {
if (events.hasOwnProperty(key) && evt.test(key)) {
response[key] = events[key];
}
}
}
else {
response = events[evt] || (events[evt] = []);
}
return response;
};
/**
* Takes a list of listener objects and flattens it into a list of listener functions.
*
* @param {Object[]} listeners Raw listener objects.
* @return {Function[]} Just the listener functions.
*/
proto.flattenListeners = function flattenListeners(listeners) {
var flatListeners = [];
var i;
for (i = 0; i < listeners.length; i += 1) {
flatListeners.push(listeners[i].listener);
}
return flatListeners;
};
/**
* Fetches the requested listeners via getListeners but will always return the results inside an object. This is mainly for internal use but others may find it useful.
*
* @param {String|RegExp} evt Name of the event to return the listeners from.
* @return {Object} All listener functions for an event in an object.
*/
proto.getListenersAsObject = function getListenersAsObject(evt) {
var listeners = this.getListeners(evt);
var response;
if (listeners instanceof Array) {
response = {};
response[evt] = listeners;
}
return response || listeners;
};
/**
* Adds a listener function to the specified event.
* The listener will not be added if it is a duplicate.
* If the listener returns true then it will be removed after it is called.
* If you pass a regular expression as the event name then the listener will be added to all events that match it.
*
* @param {String|RegExp} evt Name of the event to attach the listener to.
* @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.addListener = function addListener(evt, listener) {
var listeners = this.getListenersAsObject(evt);
var listenerIsWrapped = typeof listener === 'object';
var key;
for (key in listeners) {
if (listeners.hasOwnProperty(key) && indexOfListener(listeners[key], listener) === -1) {
listeners[key].push(listenerIsWrapped ? listener : {
listener: listener,
once: false
});
}
}
return this;
};
/**
* Alias of addListener
*/
proto.on = alias('addListener');
/**
* Semi-alias of addListener. It will add a listener that will be
* automatically removed after it's first execution.
*
* @param {String|RegExp} evt Name of the event to attach the listener to.
* @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.addOnceListener = function addOnceListener(evt, listener) {
return this.addListener(evt, {
listener: listener,
once: true
});
};
/**
* Alias of addOnceListener.
*/
proto.once = alias('addOnceListener');
/**
* Defines an event name. This is required if you want to use a regex to add a listener to multiple events at once. If you don't do this then how do you expect it to know what event to add to? Should it just add to every possible match for a regex? No. That is scary and bad.
* You need to tell it what event names should be matched by a regex.
*
* @param {String} evt Name of the event to create.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.defineEvent = function defineEvent(evt) {
this.getListeners(evt);
return this;
};
/**
* Uses defineEvent to define multiple events.
*
* @param {String[]} evts An array of event names to define.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.defineEvents = function defineEvents(evts) {
for (var i = 0; i < evts.length; i += 1) {
this.defineEvent(evts[i]);
}
return this;
};
/**
* Removes a listener function from the specified event.
* When passed a regular expression as the event name, it will remove the listener from all events that match it.
*
* @param {String|RegExp} evt Name of the event to remove the listener from.
* @param {Function} listener Method to remove from the event.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.removeListener = function removeListener(evt, listener) {
var listeners = this.getListenersAsObject(evt);
var index;
var key;
for (key in listeners) {
if (listeners.hasOwnProperty(key)) {
index = indexOfListener(listeners[key], listener);
if (index !== -1) {
listeners[key].splice(index, 1);
}
}
}
return this;
};
/**
* Alias of removeListener
*/
proto.off = alias('removeListener');
/**
* Adds listeners in bulk using the manipulateListeners method.
* If you pass an object as the second argument you can add to multiple events at once. The object should contain key value pairs of events and listeners or listener arrays. You can also pass it an event name and an array of listeners to be added.
* You can also pass it a regular expression to add the array of listeners to all events that match it.
* Yeah, this function does quite a bit. That's probably a bad thing.
*
* @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add to multiple events at once.
* @param {Function[]} [listeners] An optional array of listener functions to add.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.addListeners = function addListeners(evt, listeners) {
// Pass through to manipulateListeners
return this.manipulateListeners(false, evt, listeners);
};
/**
* Removes listeners in bulk using the manipulateListeners method.
* If you pass an object as the second argument you can remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays.
* You can also pass it an event name and an array of listeners to be removed.
* You can also pass it a regular expression to remove the listeners from all events that match it.
*
* @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to remove from multiple events at once.
* @param {Function[]} [listeners] An optional array of listener functions to remove.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.removeListeners = function removeListeners(evt, listeners) {
// Pass through to manipulateListeners
return this.manipulateListeners(true, evt, listeners);
};
/**
* Edits listeners in bulk. The addListeners and removeListeners methods both use this to do their job. You should really use those instead, this is a little lower level.
* The first argument will determine if the listeners are removed (true) or added (false).
* If you pass an object as the second argument you can add/remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays.
* You can also pass it an event name and an array of listeners to be added/removed.
* You can also pass it a regular expression to manipulate the listeners of all events that match it.
*
* @param {Boolean} remove True if you want to remove listeners, false if you want to add.
* @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add/remove from multiple events at once.
* @param {Function[]} [listeners] An optional array of listener functions to add/remove.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.manipulateListeners = function manipulateListeners(remove, evt, listeners) {
var i;
var value;
var single = remove ? this.removeListener : this.addListener;
var multiple = remove ? this.removeListeners : this.addListeners;
// If evt is an object then pass each of it's properties to this method
if (typeof evt === 'object' && !(evt instanceof RegExp)) {
for (i in evt) {
if (evt.hasOwnProperty(i) && (value = evt[i])) {
// Pass the single listener straight through to the singular method
if (typeof value === 'function') {
single.call(this, i, value);
}
else {
// Otherwise pass back to the multiple function
multiple.call(this, i, value);
}
}
}
}
else {
// So evt must be a string
// And listeners must be an array of listeners
// Loop over it and pass each one to the multiple method
i = listeners.length;
while (i--) {
single.call(this, evt, listeners[i]);
}
}
return this;
};
/**
* Removes all listeners from a specified event.
* If you do not specify an event then all listeners will be removed.
* That means every event will be emptied.
* You can also pass a regex to remove all events that match it.
*
* @param {String|RegExp} [evt] Optional name of the event to remove all listeners for. Will remove from every event if not passed.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.removeEvent = function removeEvent(evt) {
var type = typeof evt;
var events = this._getEvents();
var key;
// Remove different things depending on the state of evt
if (type === 'string') {
// Remove all listeners for the specified event
delete events[evt];
}
else if (evt instanceof RegExp) {
// Remove all events matching the regex.
for (key in events) {
if (events.hasOwnProperty(key) && evt.test(key)) {
delete events[key];
}
}
}
else {
// Remove all listeners in all events
delete this._events;
}
return this;
};
/**
* Alias of removeEvent.
*
* Added to mirror the node API.
*/
proto.removeAllListeners = alias('removeEvent');
/**
* Emits an event of your choice.
* When emitted, every listener attached to that event will be executed.
* If you pass the optional argument array then those arguments will be passed to every listener upon execution.
* Because it uses `apply`, your array of arguments will be passed as if you wrote them out separately.
* So they will not arrive within the array on the other side, they will be separate.
* You can also pass a regular expression to emit to all events that match it.
*
* @param {String|RegExp} evt Name of the event to emit and execute listeners for.
* @param {Array} [args] Optional array of arguments to be passed to each listener.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.emitEvent = function emitEvent(evt, args) {
var listeners = this.getListenersAsObject(evt);
var listener;
var i;
var key;
var response;
for (key in listeners) {
if (listeners.hasOwnProperty(key)) {
i = listeners[key].length;
while (i--) {
// If the listener returns true then it shall be removed from the event
// The function is executed either with a basic call or an apply if there is an args array
listener = listeners[key][i];
if (listener.once === true) {
this.removeListener(evt, listener.listener);
}
response = listener.listener.apply(this, args || []);
if (response === this._getOnceReturnValue()) {
this.removeListener(evt, listener.listener);
}
}
}
}
return this;
};
/**
* Alias of emitEvent
*/
proto.trigger = alias('emitEvent');
/**
* Subtly different from emitEvent in that it will pass its arguments on to the listeners, as opposed to taking a single array of arguments to pass on.
* As with emitEvent, you can pass a regex in place of the event name to emit to all events that match it.
*
* @param {String|RegExp} evt Name of the event to emit and execute listeners for.
* @param {...*} Optional additional arguments to be passed to each listener.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.emit = function emit(evt) {
var args = Array.prototype.slice.call(arguments, 1);
return this.emitEvent(evt, args);
};
/**
* Sets the current value to check against when executing listeners. If a
* listeners return value matches the one set here then it will be removed
* after execution. This value defaults to true.
*
* @param {*} value The new value to check for when executing listeners.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.setOnceReturnValue = function setOnceReturnValue(value) {
this._onceReturnValue = value;
return this;
};
/**
* Fetches the current value to check against when executing listeners. If
* the listeners return value matches this one then it should be removed
* automatically. It will return true by default.
*
* @return {*|Boolean} The current value to check for or the default, true.
* @api private
*/
proto._getOnceReturnValue = function _getOnceReturnValue() {
if (this.hasOwnProperty('_onceReturnValue')) {
return this._onceReturnValue;
}
else {
return true;
}
};
/**
* Fetches the events object and creates one if required.
*
* @return {Object} The events storage object.
* @api private
*/
proto._getEvents = function _getEvents() {
return this._events || (this._events = {});
};
/**
* Reverts the global {@link EventEmitter} to its previous value and returns a reference to this version.
*
* @return {Function} Non conflicting EventEmitter class.
*/
EventEmitter.noConflict = function noConflict() {
exports.EventEmitter = originalGlobalValue;
return EventEmitter;
};
return EventEmitter;
}());
/* jshint ignore:end */
var validateTypeFunction = function( value, name ) {
validateType( value, name, typeof value === "undefined" || typeof value === "function", "Function" );
};
var superGet, superInit,
globalEe = new EventEmitter();
function validateTypeEvent( value, name ) {
validateType( value, name, typeof value === "string" || value instanceof RegExp, "String or RegExp" );
}
function validateThenCall( method, self ) {
return function( event, listener ) {
validatePresence( event, "event" );
validateTypeEvent( event, "event" );
validatePresence( listener, "listener" );
validateTypeFunction( listener, "listener" );
return self[ method ].apply( self, arguments );
};
}
function off( self ) {
return validateThenCall( "off", self );
}
function on( self ) {
return validateThenCall( "on", self );
}
function once( self ) {
return validateThenCall( "once", self );
}
Cldr.off = off( globalEe );
Cldr.on = on( globalEe );
Cldr.once = once( globalEe );
/**
* Overload Cldr.prototype.init().
*/
superInit = Cldr.prototype.init;
Cldr.prototype.init = function() {
var ee;
this.ee = ee = new EventEmitter();
this.off = off( ee );
this.on = on( ee );
this.once = once( ee );
superInit.apply( this, arguments );
};
/**
* getOverload is encapsulated, because of cldr/unresolved. If it's loaded
* after cldr/event (and note it overwrites .get), it can trigger this
* overload again.
*/
function getOverload() {
/**
* Overload Cldr.prototype.get().
*/
superGet = Cldr.prototype.get;
Cldr.prototype.get = function( path ) {
var value = superGet.apply( this, arguments );
path = pathNormalize( path, this.attributes ).join( "/" );
globalEe.trigger( "get", [ path, value ] );
this.ee.trigger( "get", [ path, value ] );
return value;
};
}
Cldr._eventInit = getOverload;
getOverload();
return Cldr;
}));
@@ -0,0 +1,101 @@
/**
* CLDR JavaScript Library v0.4.4
* http://jquery.com/
*
* Copyright 2013 Rafael Xavier de Souza
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2016-01-18T12:25Z
*/
/*!
* CLDR JavaScript Library v0.4.4 2016-01-18T12:25Z MIT license © Rafael Xavier
* http://git.io/h4lmVg
*/
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD.
define( [ "../cldr" ], factory );
} else if ( typeof module === "object" && typeof module.exports === "object" ) {
// Node. CommonJS.
module.exports = factory( require( "cldrjs" ) );
} else {
// Global
factory( Cldr );
}
}(function( Cldr ) {
// Build optimization hack to avoid duplicating functions across modules.
var alwaysArray = Cldr._alwaysArray;
var supplementalMain = function( cldr ) {
var prepend, supplemental;
prepend = function( prepend ) {
return function( path ) {
path = alwaysArray( path );
return cldr.get( [ prepend ].concat( path ) );
};
};
supplemental = prepend( "supplemental" );
// Week Data
// http://www.unicode.org/reports/tr35/tr35-dates.html#Week_Data
supplemental.weekData = prepend( "supplemental/weekData" );
supplemental.weekData.firstDay = function() {
return cldr.get( "supplemental/weekData/firstDay/{territory}" ) ||
cldr.get( "supplemental/weekData/firstDay/001" );
};
supplemental.weekData.minDays = function() {
var minDays = cldr.get( "supplemental/weekData/minDays/{territory}" ) ||
cldr.get( "supplemental/weekData/minDays/001" );
return parseInt( minDays, 10 );
};
// Time Data
// http://www.unicode.org/reports/tr35/tr35-dates.html#Time_Data
supplemental.timeData = prepend( "supplemental/timeData" );
supplemental.timeData.allowed = function() {
return cldr.get( "supplemental/timeData/{territory}/_allowed" ) ||
cldr.get( "supplemental/timeData/001/_allowed" );
};
supplemental.timeData.preferred = function() {
return cldr.get( "supplemental/timeData/{territory}/_preferred" ) ||
cldr.get( "supplemental/timeData/001/_preferred" );
};
return supplemental;
};
var initSuper = Cldr.prototype.init;
/**
* .init() automatically ran on construction.
*
* Overload .init().
*/
Cldr.prototype.init = function() {
initSuper.apply( this, arguments );
this.supplemental = supplementalMain( this );
};
return Cldr;
}));
+164
View File
@@ -0,0 +1,164 @@
/**
* CLDR JavaScript Library v0.4.4
* http://jquery.com/
*
* Copyright 2013 Rafael Xavier de Souza
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2016-01-18T12:25Z
*/
/*!
* CLDR JavaScript Library v0.4.4 2016-01-18T12:25Z MIT license © Rafael Xavier
* http://git.io/h4lmVg
*/
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD.
define( [ "../cldr" ], factory );
} else if ( typeof module === "object" && typeof module.exports === "object" ) {
// Node. CommonJS.
module.exports = factory( require( "cldrjs" ) );
} else {
// Global
factory( Cldr );
}
}(function( Cldr ) {
// Build optimization hack to avoid duplicating functions across modules.
var coreLoad = Cldr._coreLoad;
var jsonMerge = Cldr._jsonMerge;
var pathNormalize = Cldr._pathNormalize;
var resourceGet = Cldr._resourceGet;
var validatePresence = Cldr._validatePresence;
var validateTypePath = Cldr._validateTypePath;
var bundleParentLookup = function( Cldr, locale ) {
var normalizedPath, parent;
if ( locale === "root" ) {
return;
}
// First, try to find parent on supplemental data.
normalizedPath = pathNormalize( [ "supplemental/parentLocales/parentLocale", locale ] );
parent = resourceGet( Cldr._resolved, normalizedPath ) || resourceGet( Cldr._raw, normalizedPath );
if ( parent ) {
return parent;
}
// Or truncate locale.
parent = locale.substr( 0, locale.lastIndexOf( Cldr.localeSep ) );
if ( !parent ) {
return "root";
}
return parent;
};
// @path: normalized path
var resourceSet = function( data, path, value ) {
var i,
node = data,
length = path.length;
for ( i = 0; i < length - 1; i++ ) {
if ( !node[ path[ i ] ] ) {
node[ path[ i ] ] = {};
}
node = node[ path[ i ] ];
}
node[ path[ i ] ] = value;
};
var itemLookup = (function() {
var lookup;
lookup = function( Cldr, locale, path, attributes, childLocale ) {
var normalizedPath, parent, value;
// 1: Finish recursion
// 2: Avoid infinite loop
if ( typeof locale === "undefined" /* 1 */ || locale === childLocale /* 2 */ ) {
return;
}
// Resolve path
normalizedPath = pathNormalize( path, attributes );
// Check resolved (cached) data first
// 1: Due to #16, never use the cached resolved non-leaf nodes. It may not
// represent its leafs in its entirety.
value = resourceGet( Cldr._resolved, normalizedPath );
if ( value && typeof value !== "object" /* 1 */ ) {
return value;
}
// Check raw data
value = resourceGet( Cldr._raw, normalizedPath );
if ( !value ) {
// Or, lookup at parent locale
parent = bundleParentLookup( Cldr, locale );
value = lookup( Cldr, parent, path, jsonMerge( attributes, { bundle: parent }), locale );
}
if ( value ) {
// Set resolved (cached)
resourceSet( Cldr._resolved, normalizedPath, value );
}
return value;
};
return lookup;
}());
Cldr._raw = {};
/**
* Cldr.load( json [, json, ...] )
*
* @json [JSON] CLDR data or [Array] Array of @json's.
*
* Load resolved or unresolved cldr data.
* Overwrite Cldr.load().
*/
Cldr.load = function() {
Cldr._raw = coreLoad( Cldr, Cldr._raw, arguments );
};
/**
* Overwrite Cldr.prototype.get().
*/
Cldr.prototype.get = function( path ) {
validatePresence( path, "path" );
validateTypePath( path, "path" );
// 1: use bundle as locale on item lookup for simplification purposes, because no other extended subtag is used anyway on bundle parent lookup.
// 2: during init(), this method is called, but bundle is yet not defined. Use "" as a workaround in this very specific scenario.
return itemLookup( Cldr, this.attributes && this.attributes.bundle /* 1 */ || "" /* 2 */, path, this.attributes );
};
// In case cldr/unresolved is loaded after cldr/event, we trigger its overloads again. Because, .get is overwritten in here.
if ( Cldr._eventInit ) {
Cldr._eventInit();
}
return Cldr;
}));
+28
View File
@@ -0,0 +1,28 @@
jscolor-nuget
=============
NuGet Package for **JSColor: JavaScript / HTML Color Picker**
This is just the source for [JSColor](http://jscolor.com/), and I just packed the sources and assets to work with ASP.NET MVC projects.
## Usage Instructions ##
Just add a reference to `/Scripts/jscolor.js`, directly or via bundling:
**Direct Example**
<script type="text/javascript" src="jscolor/jscolor.js"></script>
**Bundling Example**
At `/App_Start/BundleConfig.cs`:
public static void RegisterBundles(BundleCollection bundles)
{
...
bundles.Add(new ScriptBundle("~/bundles/general").Include(
"~/Scripts/jscolor.js"));
...
}
@@ -0,0 +1,49 @@
/*!
** An extension to the jQuery Validation Plugin which makes it use Globalize.js for number and date parsing
** Copyright (c) 2013 John Reilly
*/
(function ($, Globalize) {
// Clone original methods we want to call into
var originalMethods = {
min: $.validator.methods.min,
max: $.validator.methods.max,
range: $.validator.methods.range
};
// Globalize options - initially just the date format used for parsing
// Users can customise this to suit them
$.validator.methods.dateGlobalizeOptions = { dateParseFormat: { skeleton: "yMd" } };
// Tell the validator that we want numbers parsed using Globalize
$.validator.methods.number = function (value, element) {
var val = Globalize.parseNumber(value);
return this.optional(element) || ($.isNumeric(val));
};
// Tell the validator that we want dates parsed using Globalize
$.validator.methods.date = function (value, element) {
var val = Globalize.parseDate(value, $.validator.methods.dateGlobalizeOptions.dateParseFormat);
return this.optional(element) || (val instanceof Date);
};
// Tell the validator that we want numbers parsed using Globalize,
// then call into original implementation with parsed value
$.validator.methods.min = function (value, element, param) {
var val = Globalize.parseNumber(value);
return originalMethods.min.call(this, val, element, param);
};
$.validator.methods.max = function (value, element, param) {
var val = Globalize.parseNumber(value);
return originalMethods.max.call(this, val, element, param);
};
$.validator.methods.range = function (value, element, param) {
var val = Globalize.parseNumber(value);
return originalMethods.range.call(this, val, element, param);
};
}(jQuery, Globalize));
@@ -0,0 +1 @@
!function(a,t){var e={min:a.validator.methods.min,max:a.validator.methods.max,range:a.validator.methods.range};a.validator.methods.dateGlobalizeOptions={dateParseFormat:{skeleton:"yMd"}},a.validator.methods.number=function(e,r){var o=t.parseNumber(e);return this.optional(r)||a.isNumeric(o)},a.validator.methods.date=function(e,r){var o=t.parseDate(e,a.validator.methods.dateGlobalizeOptions.dateParseFormat);return this.optional(r)||o instanceof Date},a.validator.methods.min=function(a,r,o){var i=t.parseNumber(a);return e.min.call(this,i,r,o)},a.validator.methods.max=function(a,r,o){var i=t.parseNumber(a);return e.max.call(this,i,r,o)},a.validator.methods.range=function(a,r,o){var i=t.parseNumber(a);return e.range.call(this,i,r,o)}}(jQuery,Globalize);
@@ -0,0 +1,421 @@
/**
* Globalize v1.1.1
*
* http://github.com/jquery/globalize
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2016-02-04T12:01Z
*/
/*!
* Globalize v1.1.1 2016-02-04T12:01Z Released under the MIT license
* http://git.io/TrdQbw
*/
(function( root, factory ) {
// UMD returnExports
if ( typeof define === "function" && define.amd ) {
// AMD
define([
"cldr",
"cldr/event"
], factory );
} else if ( typeof exports === "object" ) {
// Node, CommonJS
module.exports = factory( require( "cldrjs" ) );
} else {
// Global
root.Globalize = factory( root.Cldr );
}
}( this, function( Cldr ) {
/**
* A toString method that outputs meaningful values for objects or arrays and
* still performs as fast as a plain string in case variable is string, or as
* fast as `"" + number` in case variable is a number.
* Ref: http://jsperf.com/my-stringify
*/
var toString = function( variable ) {
return typeof variable === "string" ? variable : ( typeof variable === "number" ? "" +
variable : JSON.stringify( variable ) );
};
/**
* formatMessage( message, data )
*
* @message [String] A message with optional {vars} to be replaced.
*
* @data [Array or JSON] Object with replacing-variables content.
*
* Return the formatted message. For example:
*
* - formatMessage( "{0} second", [ 1 ] ); // 1 second
*
* - formatMessage( "{0}/{1}", ["m", "s"] ); // m/s
*
* - formatMessage( "{name} <{email}>", {
* name: "Foo",
* email: "bar@baz.qux"
* }); // Foo <bar@baz.qux>
*/
var formatMessage = function( message, data ) {
// Replace {attribute}'s
message = message.replace( /{[0-9a-zA-Z-_. ]+}/g, function( name ) {
name = name.replace( /^{([^}]*)}$/, "$1" );
return toString( data[ name ] );
});
return message;
};
var objectExtend = function() {
var destination = arguments[ 0 ],
sources = [].slice.call( arguments, 1 );
sources.forEach(function( source ) {
var prop;
for ( prop in source ) {
destination[ prop ] = source[ prop ];
}
});
return destination;
};
var createError = function( code, message, attributes ) {
var error;
message = code + ( message ? ": " + formatMessage( message, attributes ) : "" );
error = new Error( message );
error.code = code;
objectExtend( error, attributes );
return error;
};
// Based on http://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript-jquery
var stringHash = function( str ) {
return [].reduce.call( str, function( hash, i ) {
var chr = i.charCodeAt( 0 );
hash = ( ( hash << 5 ) - hash ) + chr;
return hash | 0;
}, 0 );
};
var runtimeKey = function( fnName, locale, args, argsStr ) {
var hash;
argsStr = argsStr || JSON.stringify( args );
hash = stringHash( fnName + locale + argsStr );
return hash > 0 ? "a" + hash : "b" + Math.abs( hash );
};
var functionName = function( fn ) {
if ( fn.name !== undefined ) {
return fn.name;
}
// fn.name is not supported by IE.
var matches = /^function\s+([\w\$]+)\s*\(/.exec( fn.toString() );
if ( matches && matches.length > 0 ) {
return matches[ 1 ];
}
};
var runtimeBind = function( args, cldr, fn, runtimeArgs ) {
var argsStr = JSON.stringify( args ),
fnName = functionName( fn ),
locale = cldr.locale;
// If name of the function is not available, this is most likely due uglification,
// which most likely means we are in production, and runtimeBind here is not necessary.
if ( !fnName ) {
return fn;
}
fn.runtimeKey = runtimeKey( fnName, locale, null, argsStr );
fn.generatorString = function() {
return "Globalize(\"" + locale + "\")." + fnName + "(" + argsStr.slice( 1, -1 ) + ")";
};
fn.runtimeArgs = runtimeArgs;
return fn;
};
var validate = function( code, message, check, attributes ) {
if ( !check ) {
throw createError( code, message, attributes );
}
};
var alwaysArray = function( stringOrArray ) {
return Array.isArray( stringOrArray ) ? stringOrArray : stringOrArray ? [ stringOrArray ] : [];
};
var validateCldr = function( path, value, options ) {
var skipBoolean;
options = options || {};
skipBoolean = alwaysArray( options.skip ).some(function( pathRe ) {
return pathRe.test( path );
});
validate( "E_MISSING_CLDR", "Missing required CLDR content `{path}`.", value || skipBoolean, {
path: path
});
};
var validateDefaultLocale = function( value ) {
validate( "E_DEFAULT_LOCALE_NOT_DEFINED", "Default locale has not been defined.",
value !== undefined, {} );
};
var validateParameterPresence = function( value, name ) {
validate( "E_MISSING_PARAMETER", "Missing required parameter `{name}`.",
value !== undefined, { name: name });
};
/**
* range( value, name, minimum, maximum )
*
* @value [Number].
*
* @name [String] name of variable.
*
* @minimum [Number]. The lowest valid value, inclusive.
*
* @maximum [Number]. The greatest valid value, inclusive.
*/
var validateParameterRange = function( value, name, minimum, maximum ) {
validate(
"E_PAR_OUT_OF_RANGE",
"Parameter `{name}` has value `{value}` out of range [{minimum}, {maximum}].",
value === undefined || value >= minimum && value <= maximum,
{
maximum: maximum,
minimum: minimum,
name: name,
value: value
}
);
};
var validateParameterType = function( value, name, check, expected ) {
validate(
"E_INVALID_PAR_TYPE",
"Invalid `{name}` parameter ({value}). {expected} expected.",
check,
{
expected: expected,
name: name,
value: value
}
);
};
var validateParameterTypeLocale = function( value, name ) {
validateParameterType(
value,
name,
value === undefined || typeof value === "string" || value instanceof Cldr,
"String or Cldr instance"
);
};
/**
* Function inspired by jQuery Core, but reduced to our use case.
*/
var isPlainObject = function( obj ) {
return obj !== null && "" + obj === "[object Object]";
};
var validateParameterTypePlainObject = function( value, name ) {
validateParameterType(
value,
name,
value === undefined || isPlainObject( value ),
"Plain Object"
);
};
var alwaysCldr = function( localeOrCldr ) {
return localeOrCldr instanceof Cldr ? localeOrCldr : new Cldr( localeOrCldr );
};
// ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions?redirectlocale=en-US&redirectslug=JavaScript%2FGuide%2FRegular_Expressions
var regexpEscape = function( string ) {
return string.replace( /([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1" );
};
var stringPad = function( str, count, right ) {
var length;
if ( typeof str !== "string" ) {
str = String( str );
}
for ( length = str.length; length < count; length += 1 ) {
str = ( right ? ( str + "0" ) : ( "0" + str ) );
}
return str;
};
function validateLikelySubtags( cldr ) {
cldr.once( "get", validateCldr );
cldr.get( "supplemental/likelySubtags" );
}
/**
* [new] Globalize( locale|cldr )
*
* @locale [String]
*
* @cldr [Cldr instance]
*
* Create a Globalize instance.
*/
function Globalize( locale ) {
if ( !( this instanceof Globalize ) ) {
return new Globalize( locale );
}
validateParameterPresence( locale, "locale" );
validateParameterTypeLocale( locale, "locale" );
this.cldr = alwaysCldr( locale );
validateLikelySubtags( this.cldr );
}
/**
* Globalize.load( json, ... )
*
* @json [JSON]
*
* Load resolved or unresolved cldr data.
* Somewhat equivalent to previous Globalize.addCultureInfo(...).
*/
Globalize.load = function() {
// validations are delegated to Cldr.load().
Cldr.load.apply( Cldr, arguments );
};
/**
* Globalize.locale( [locale|cldr] )
*
* @locale [String]
*
* @cldr [Cldr instance]
*
* Set default Cldr instance if locale or cldr argument is passed.
*
* Return the default Cldr instance.
*/
Globalize.locale = function( locale ) {
validateParameterTypeLocale( locale, "locale" );
if ( arguments.length ) {
this.cldr = alwaysCldr( locale );
validateLikelySubtags( this.cldr );
}
return this.cldr;
};
/**
* Optimization to avoid duplicating some internal functions across modules.
*/
Globalize._alwaysArray = alwaysArray;
Globalize._createError = createError;
Globalize._formatMessage = formatMessage;
Globalize._isPlainObject = isPlainObject;
Globalize._objectExtend = objectExtend;
Globalize._regexpEscape = regexpEscape;
Globalize._runtimeBind = runtimeBind;
Globalize._stringPad = stringPad;
Globalize._validate = validate;
Globalize._validateCldr = validateCldr;
Globalize._validateDefaultLocale = validateDefaultLocale;
Globalize._validateParameterPresence = validateParameterPresence;
Globalize._validateParameterRange = validateParameterRange;
Globalize._validateParameterTypePlainObject = validateParameterTypePlainObject;
Globalize._validateParameterType = validateParameterType;
return Globalize;
}));
@@ -0,0 +1,439 @@
/*!
* Globalize v1.1.1
*
* http://github.com/jquery/globalize
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2016-02-04T12:01Z
*/
(function( root, factory ) {
// UMD returnExports
if ( typeof define === "function" && define.amd ) {
// AMD
define([
"cldr",
"../globalize",
"./number",
"cldr/event",
"cldr/supplemental"
], factory );
} else if ( typeof exports === "object" ) {
// Node, CommonJS
module.exports = factory( require( "cldrjs" ), require( "globalize" ) );
} else {
// Global
factory( root.Cldr, root.Globalize );
}
}(this, function( Cldr, Globalize ) {
var alwaysArray = Globalize._alwaysArray,
formatMessage = Globalize._formatMessage,
numberNumberingSystem = Globalize._numberNumberingSystem,
numberPattern = Globalize._numberPattern,
runtimeBind = Globalize._runtimeBind,
stringPad = Globalize._stringPad,
validateCldr = Globalize._validateCldr,
validateDefaultLocale = Globalize._validateDefaultLocale,
validateParameterPresence = Globalize._validateParameterPresence,
validateParameterType = Globalize._validateParameterType,
validateParameterTypeNumber = Globalize._validateParameterTypeNumber,
validateParameterTypePlainObject = Globalize._validateParameterTypePlainObject;
var validateParameterTypeCurrency = function( value, name ) {
validateParameterType(
value,
name,
value === undefined || typeof value === "string" && ( /^[A-Za-z]{3}$/ ).test( value ),
"3-letter currency code string as defined by ISO 4217"
);
};
/**
* supplementalOverride( currency, pattern, cldr )
*
* Return pattern with fraction digits overriden by supplemental currency data.
*/
var currencySupplementalOverride = function( currency, pattern, cldr ) {
var digits,
fraction = "",
fractionData = cldr.supplemental([ "currencyData/fractions", currency ]) ||
cldr.supplemental( "currencyData/fractions/DEFAULT" );
digits = +fractionData._digits;
if ( digits ) {
fraction = "." + stringPad( "0", digits ).slice( 0, -1 ) + fractionData._rounding;
}
return pattern.replace( /\.(#+|0*[0-9]|0+[0-9]?)/g, fraction );
};
var objectFilter = function( object, testRe ) {
var key,
copy = {};
for ( key in object ) {
if ( testRe.test( key ) ) {
copy[ key ] = object[ key ];
}
}
return copy;
};
var currencyUnitPatterns = function( cldr ) {
return objectFilter( cldr.main([
"numbers",
"currencyFormats-numberSystem-" + numberNumberingSystem( cldr )
]), /^unitPattern/ );
};
/**
* codeProperties( currency, cldr )
*
* Return number pattern with the appropriate currency code in as literal.
*/
var currencyCodeProperties = function( currency, cldr ) {
var pattern = numberPattern( "decimal", cldr );
// The number of decimal places and the rounding for each currency is not locale-specific. Those
// values overridden by Supplemental Currency Data.
pattern = currencySupplementalOverride( currency, pattern, cldr );
return {
currency: currency,
pattern: pattern,
unitPatterns: currencyUnitPatterns( cldr )
};
};
/**
* nameFormat( formattedNumber, pluralForm, properties )
*
* Return the appropriate name form currency format.
*/
var currencyNameFormat = function( formattedNumber, pluralForm, properties ) {
var displayName, unitPattern,
displayNames = properties.displayNames || {},
unitPatterns = properties.unitPatterns;
displayName = displayNames[ "displayName-count-" + pluralForm ] ||
displayNames[ "displayName-count-other" ] ||
displayNames.displayName ||
properties.currency;
unitPattern = unitPatterns[ "unitPattern-count-" + pluralForm ] ||
unitPatterns[ "unitPattern-count-other" ];
return formatMessage( unitPattern, [ formattedNumber, displayName ]);
};
var currencyFormatterFn = function( numberFormatter, pluralGenerator, properties ) {
var fn;
// Return formatter when style is "code" or "name".
if ( pluralGenerator && properties ) {
fn = function currencyFormatter( value ) {
validateParameterPresence( value, "value" );
validateParameterTypeNumber( value, "value" );
return currencyNameFormat(
numberFormatter( value ),
pluralGenerator( value ),
properties
);
};
// Return formatter when style is "symbol" or "accounting".
} else {
fn = function currencyFormatter( value ) {
return numberFormatter( value );
};
}
return fn;
};
/**
* nameProperties( currency, cldr )
*
* Return number pattern with the appropriate currency code in as literal.
*/
var currencyNameProperties = function( currency, cldr ) {
var properties = currencyCodeProperties( currency, cldr );
properties.displayNames = objectFilter( cldr.main([
"numbers/currencies",
currency
]), /^displayName/ );
return properties;
};
/**
* Unicode regular expression for: everything except math symbols, currency signs, dingbats, and
* box-drawing characters.
*
* Generated by:
*
* regenerate()
* .addRange( 0x0, 0x10FFFF )
* .remove( require( "unicode-7.0.0/categories/S/symbols" ) ).toString();
*
* https://github.com/mathiasbynens/regenerate
* https://github.com/mathiasbynens/unicode-7.0.0
*/
var regexpNotS = /[\0-#%-\*,-;\?-\]_a-\{\}\x7F-\xA1\xA7\xAA\xAB\xAD\xB2\xB3\xB5-\xB7\xB9-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376-\u0383\u0386-\u03F5\u03F7-\u0481\u0483-\u058C\u0590-\u0605\u0609\u060A\u060C\u060D\u0610-\u06DD\u06DF-\u06E8\u06EA-\u06FC\u06FF-\u07F5\u07F7-\u09F1\u09F4-\u09F9\u09FC-\u0AF0\u0AF2-\u0B6F\u0B71-\u0BF2\u0BFB-\u0C7E\u0C80-\u0D78\u0D7A-\u0E3E\u0E40-\u0F00\u0F04-\u0F12\u0F14\u0F18\u0F19\u0F20-\u0F33\u0F35\u0F37\u0F39-\u0FBD\u0FC6\u0FCD\u0FD0-\u0FD4\u0FD9-\u109D\u10A0-\u138F\u139A-\u17DA\u17DC-\u193F\u1941-\u19DD\u1A00-\u1B60\u1B6B-\u1B73\u1B7D-\u1FBC\u1FBE\u1FC2-\u1FCC\u1FD0-\u1FDC\u1FE0-\u1FEC\u1FF0-\u1FFC\u1FFF-\u2043\u2045-\u2051\u2053-\u2079\u207D-\u2089\u208D-\u209F\u20BE-\u20FF\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2150-\u218F\u2308-\u230B\u2329\u232A\u23FB-\u23FF\u2427-\u243F\u244B-\u249B\u24EA-\u24FF\u2768-\u2793\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2B74\u2B75\u2B96\u2B97\u2BBA-\u2BBC\u2BC9\u2BD2-\u2CE4\u2CEB-\u2E7F\u2E9A\u2EF4-\u2EFF\u2FD6-\u2FEF\u2FFC-\u3003\u3005-\u3011\u3014-\u301F\u3021-\u3035\u3038-\u303D\u3040-\u309A\u309D-\u318F\u3192-\u3195\u31A0-\u31BF\u31E4-\u31FF\u321F-\u3229\u3248-\u324F\u3251-\u325F\u3280-\u3289\u32B1-\u32BF\u32FF\u3400-\u4DBF\u4E00-\uA48F\uA4C7-\uA6FF\uA717-\uA71F\uA722-\uA788\uA78B-\uA827\uA82C-\uA835\uA83A-\uAA76\uAA7A-\uAB5A\uAB5C-\uD7FF\uDC00-\uFB28\uFB2A-\uFBB1\uFBC2-\uFDFB\uFDFE-\uFE61\uFE63\uFE67\uFE68\uFE6A-\uFF03\uFF05-\uFF0A\uFF0C-\uFF1B\uFF1F-\uFF3D\uFF3F\uFF41-\uFF5B\uFF5D\uFF5F-\uFFDF\uFFE7\uFFEF-\uFFFB\uFFFE\uFFFF]|\uD800[\uDC00-\uDD36\uDD40-\uDD78\uDD8A\uDD8B\uDD8D-\uDD8F\uDD9C-\uDD9F\uDDA1-\uDDCF\uDDFD-\uDFFF]|[\uD801\uD803-\uD819\uD81B-\uD82E\uD830-\uD833\uD836-\uD83A\uD83F-\uDBFF][\uDC00-\uDFFF]|\uD802[\uDC00-\uDC76\uDC79-\uDEC7\uDEC9-\uDFFF]|\uD81A[\uDC00-\uDF3B\uDF40-\uDF44\uDF46-\uDFFF]|\uD82F[\uDC00-\uDC9B\uDC9D-\uDFFF]|\uD834[\uDCF6-\uDCFF\uDD27\uDD28\uDD65-\uDD69\uDD6D-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDDDE-\uDDFF\uDE42-\uDE44\uDE46-\uDEFF\uDF57-\uDFFF]|\uD835[\uDC00-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFFF]|\uD83B[\uDC00-\uDEEF\uDEF2-\uDFFF]|\uD83C[\uDC2C-\uDC2F\uDC94-\uDC9F\uDCAF\uDCB0\uDCC0\uDCD0\uDCF6-\uDD0F\uDD2F\uDD6C-\uDD6F\uDD9B-\uDDE5\uDE03-\uDE0F\uDE3B-\uDE3F\uDE49-\uDE4F\uDE52-\uDEFF\uDF2D-\uDF2F\uDF7E\uDF7F\uDFCF-\uDFD3\uDFF8-\uDFFF]|\uD83D[\uDCFF\uDD4B-\uDD4F\uDD7A\uDDA4\uDE43\uDE44\uDED0-\uDEDF\uDEED-\uDEEF\uDEF4-\uDEFF\uDF74-\uDF7F\uDFD5-\uDFFF]|\uD83E[\uDC0C-\uDC0F\uDC48-\uDC4F\uDC5A-\uDC5F\uDC88-\uDC8F\uDCAE-\uDFFF]|[\uD800-\uDBFF]/;
/**
* symbolProperties( currency, cldr )
*
* Return pattern replacing `¤` with the appropriate currency symbol literal.
*/
var currencySymbolProperties = function( currency, cldr, options ) {
var currencySpacing, pattern,
regexp = {
"[:digit:]": /\d/,
"[:^S:]": regexpNotS
},
symbol = cldr.main([
"numbers/currencies",
currency,
"symbol"
]);
currencySpacing = [ "beforeCurrency", "afterCurrency" ].map(function( position ) {
return cldr.main([
"numbers",
"currencyFormats-numberSystem-" + numberNumberingSystem( cldr ),
"currencySpacing",
position
]);
});
pattern = cldr.main([
"numbers",
"currencyFormats-numberSystem-" + numberNumberingSystem( cldr ),
options.style === "accounting" ? "accounting" : "standard"
]);
pattern =
// The number of decimal places and the rounding for each currency is not locale-specific.
// Those values are overridden by Supplemental Currency Data.
currencySupplementalOverride( currency, pattern, cldr )
// Replace "¤" (\u00A4) with the appropriate symbol literal.
.split( ";" ).map(function( pattern ) {
return pattern.split( "\u00A4" ).map(function( part, i ) {
var currencyMatch = regexp[ currencySpacing[ i ].currencyMatch ],
surroundingMatch = regexp[ currencySpacing[ i ].surroundingMatch ],
insertBetween = "";
// For currencyMatch and surroundingMatch definitions, read [1].
// When i === 0, beforeCurrency is being handled. Otherwise, afterCurrency.
// 1: http://www.unicode.org/reports/tr35/tr35-numbers.html#Currencies
currencyMatch = currencyMatch.test( symbol.charAt( i ? symbol.length - 1 : 0 ) );
surroundingMatch = surroundingMatch.test(
part.charAt( i ? 0 : part.length - 1 ).replace( /[#@,.]/g, "0" )
);
if ( currencyMatch && part && surroundingMatch ) {
insertBetween = currencySpacing[ i ].insertBetween;
}
return ( i ? insertBetween : "" ) + part + ( i ? "" : insertBetween );
}).join( "'" + symbol + "'" );
}).join( ";" );
return {
pattern: pattern
};
};
/**
* objectOmit( object, keys )
*
* Return a copy of the object, filtered to omit the blacklisted key or array of keys.
*/
var objectOmit = function( object, keys ) {
var key,
copy = {};
keys = alwaysArray( keys );
for ( key in object ) {
if ( keys.indexOf( key ) === -1 ) {
copy[ key ] = object[ key ];
}
}
return copy;
};
function validateRequiredCldr( path, value ) {
validateCldr( path, value, {
skip: [ /supplemental\/currencyData\/fractions\/[A-Za-z]{3}$/ ]
});
}
/**
* .currencyFormatter( currency [, options] )
*
* @currency [String] 3-letter currency code as defined by ISO 4217.
*
* @options [Object]:
* - style: [String] "symbol" (default), "accounting", "code" or "name".
* - see also number/format options.
*
* Return a function that formats a currency according to the given options and default/instance
* locale.
*/
Globalize.currencyFormatter =
Globalize.prototype.currencyFormatter = function( currency, options ) {
var args, cldr, numberFormatter, pluralGenerator, properties, returnFn, style;
validateParameterPresence( currency, "currency" );
validateParameterTypeCurrency( currency, "currency" );
validateParameterTypePlainObject( options, "options" );
cldr = this.cldr;
options = options || {};
args = [ currency, options ];
style = options.style || "symbol";
validateDefaultLocale( cldr );
// Get properties given style ("symbol" default, "code" or "name").
cldr.on( "get", validateRequiredCldr );
properties = ({
accounting: currencySymbolProperties,
code: currencyCodeProperties,
name: currencyNameProperties,
symbol: currencySymbolProperties
}[ style ] )( currency, cldr, options );
cldr.off( "get", validateRequiredCldr );
// options = options minus style, plus raw pattern.
options = objectOmit( options, "style" );
options.raw = properties.pattern;
// Return formatter when style is "symbol" or "accounting".
if ( style === "symbol" || style === "accounting" ) {
numberFormatter = this.numberFormatter( options );
returnFn = currencyFormatterFn( numberFormatter );
runtimeBind( args, cldr, returnFn, [ numberFormatter ] );
// Return formatter when style is "code" or "name".
} else {
numberFormatter = this.numberFormatter( options );
pluralGenerator = this.pluralGenerator();
returnFn = currencyFormatterFn( numberFormatter, pluralGenerator, properties );
runtimeBind( args, cldr, returnFn, [ numberFormatter, pluralGenerator, properties ] );
}
return returnFn;
};
/**
* .currencyParser( currency [, options] )
*
* @currency [String] 3-letter currency code as defined by ISO 4217.
*
* @options [Object] see currencyFormatter.
*
* Return the currency parser according to the given options and the default/instance locale.
*/
Globalize.currencyParser =
Globalize.prototype.currencyParser = function( /* currency, options */ ) {
// TODO implement parser.
};
/**
* .formatCurrency( value, currency [, options] )
*
* @value [Number] number to be formatted.
*
* @currency [String] 3-letter currency code as defined by ISO 4217.
*
* @options [Object] see currencyFormatter.
*
* Format a currency according to the given options and the default/instance locale.
*/
Globalize.formatCurrency =
Globalize.prototype.formatCurrency = function( value, currency, options ) {
validateParameterPresence( value, "value" );
validateParameterTypeNumber( value, "value" );
return this.currencyFormatter( currency, options )( value );
};
/**
* .parseCurrency( value, currency [, options] )
*
* @value [String]
*
* @currency [String] 3-letter currency code as defined by ISO 4217.
*
* @options [Object]: See currencyFormatter.
*
* Return the parsed currency or NaN when value is invalid.
*/
Globalize.parseCurrency =
Globalize.prototype.parseCurrency = function( /* value, currency, options */ ) {
};
return Globalize;
}));
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,373 @@
/**
* Globalize v1.1.1
*
* http://github.com/jquery/globalize
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2016-02-04T12:01Z
*/
/*!
* Globalize v1.1.1 2016-02-04T12:01Z Released under the MIT license
* http://git.io/TrdQbw
*/
(function( root, factory ) {
// UMD returnExports
if ( typeof define === "function" && define.amd ) {
// AMD
define([
"cldr",
"../globalize",
"cldr/event",
"cldr/supplemental"
], factory );
} else if ( typeof exports === "object" ) {
// Node, CommonJS
module.exports = factory( require( "cldrjs" ), require( "globalize" ) );
} else {
// Global
factory( root.Cldr, root.Globalize );
}
}(this, function( Cldr, Globalize ) {
var runtimeBind = Globalize._runtimeBind,
validateCldr = Globalize._validateCldr,
validateDefaultLocale = Globalize._validateDefaultLocale,
validateParameterPresence = Globalize._validateParameterPresence,
validateParameterType = Globalize._validateParameterType,
validateParameterTypePlainObject = Globalize._validateParameterTypePlainObject;
var MakePlural;
/* jshint ignore:start */
MakePlural = (function() {
'use strict';
var _toArray = function (arr) { return Array.isArray(arr) ? arr : Array.from(arr); };
var _toConsumableArray = function (arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
/**
* make-plural.js -- https://github.com/eemeli/make-plural.js/
* Copyright (c) 2014-2015 by Eemeli Aro <eemeli@gmail.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* The software is provided "as is" and the author disclaims all warranties
* with regard to this software including all implied warranties of
* merchantability and fitness. In no event shall the author be liable for
* any special, direct, indirect, or consequential damages or any damages
* whatsoever resulting from loss of use, data or profits, whether in an
* action of contract, negligence or other tortious action, arising out of
* or in connection with the use or performance of this software.
*/
var Parser = (function () {
function Parser() {
_classCallCheck(this, Parser);
}
_createClass(Parser, [{
key: 'parse',
value: function parse(cond) {
var _this = this;
if (cond === 'i = 0 or n = 1') {
return 'n >= 0 && n <= 1';
}if (cond === 'i = 0,1') {
return 'n >= 0 && n < 2';
}if (cond === 'i = 1 and v = 0') {
this.v0 = 1;
return 'n == 1 && v0';
}
return cond.replace(/([tv]) (!?)= 0/g, function (m, sym, noteq) {
var sn = sym + '0';
_this[sn] = 1;
return noteq ? '!' + sn : sn;
}).replace(/\b[fintv]\b/g, function (m) {
_this[m] = 1;
return m;
}).replace(/([fin]) % (10+)/g, function (m, sym, num) {
var sn = sym + num;
_this[sn] = 1;
return sn;
}).replace(/n10+ = 0/g, 't0 && $&').replace(/(\w+ (!?)= )([0-9.]+,[0-9.,]+)/g, function (m, se, noteq, x) {
if (m === 'n = 0,1') return '(n == 0 || n == 1)';
if (noteq) return se + x.split(',').join(' && ' + se);
return '(' + se + x.split(',').join(' || ' + se) + ')';
}).replace(/(\w+) (!?)= ([0-9]+)\.\.([0-9]+)/g, function (m, sym, noteq, x0, x1) {
if (Number(x0) + 1 === Number(x1)) {
if (noteq) return '' + sym + ' != ' + x0 + ' && ' + sym + ' != ' + x1;
return '(' + sym + ' == ' + x0 + ' || ' + sym + ' == ' + x1 + ')';
}
if (noteq) return '(' + sym + ' < ' + x0 + ' || ' + sym + ' > ' + x1 + ')';
if (sym === 'n') {
_this.t0 = 1;return '(t0 && n >= ' + x0 + ' && n <= ' + x1 + ')';
}
return '(' + sym + ' >= ' + x0 + ' && ' + sym + ' <= ' + x1 + ')';
}).replace(/ and /g, ' && ').replace(/ or /g, ' || ').replace(/ = /g, ' == ');
}
}, {
key: 'vars',
value: (function (_vars) {
function vars() {
return _vars.apply(this, arguments);
}
vars.toString = function () {
return _vars.toString();
};
return vars;
})(function () {
var vars = [];
if (this.i) vars.push('i = s[0]');
if (this.f || this.v) vars.push('f = s[1] || \'\'');
if (this.t) vars.push('t = (s[1] || \'\').replace(/0+$/, \'\')');
if (this.v) vars.push('v = f.length');
if (this.v0) vars.push('v0 = !s[1]');
if (this.t0 || this.n10 || this.n100) vars.push('t0 = Number(s[0]) == n');
for (var k in this) {
if (/^.10+$/.test(k)) {
var k0 = k[0] === 'n' ? 't0 && s[0]' : k[0];
vars.push('' + k + ' = ' + k0 + '.slice(-' + k.substr(2).length + ')');
}
}if (!vars.length) return '';
return 'var ' + ['s = String(n).split(\'.\')'].concat(vars).join(', ');
})
}]);
return Parser;
})();
var MakePlural = (function () {
function MakePlural(lc) {
var _ref = arguments[1] === undefined ? MakePlural : arguments[1];
var cardinals = _ref.cardinals;
var ordinals = _ref.ordinals;
_classCallCheck(this, MakePlural);
if (!cardinals && !ordinals) throw new Error('At least one type of plural is required');
this.lc = lc;
this.categories = { cardinal: [], ordinal: [] };
this.parser = new Parser();
this.fn = this.buildFunction(cardinals, ordinals);
this.fn._obj = this;
this.fn.categories = this.categories;
this.fn.toString = this.fnToString.bind(this);
return this.fn;
}
_createClass(MakePlural, [{
key: 'compile',
value: function compile(type, req) {
var cases = [];
var rules = MakePlural.rules[type][this.lc];
if (!rules) {
if (req) throw new Error('Locale "' + this.lc + '" ' + type + ' rules not found');
this.categories[type] = ['other'];
return '\'other\'';
}
for (var r in rules) {
var _rules$r$trim$split = rules[r].trim().split(/\s*@\w*/);
var _rules$r$trim$split2 = _toArray(_rules$r$trim$split);
var cond = _rules$r$trim$split2[0];
var examples = _rules$r$trim$split2.slice(1);
var cat = r.replace('pluralRule-count-', '');
if (cond) cases.push([this.parser.parse(cond), cat]);
}
this.categories[type] = cases.map(function (c) {
return c[1];
}).concat('other');
if (cases.length === 1) {
return '(' + cases[0][0] + ') ? \'' + cases[0][1] + '\' : \'other\'';
} else {
return [].concat(_toConsumableArray(cases.map(function (c) {
return '(' + c[0] + ') ? \'' + c[1] + '\'';
})), ['\'other\'']).join('\n : ');
}
}
}, {
key: 'buildFunction',
value: function buildFunction(cardinals, ordinals) {
var _this3 = this;
var compile = function compile(c) {
return c ? (c[1] ? 'return ' : 'if (ord) return ') + _this3.compile.apply(_this3, _toConsumableArray(c)) : '';
},
fold = { vars: function vars(str) {
return (' ' + str + ';').replace(/(.{1,78})(,|$) ?/g, '$1$2\n ');
},
cond: function cond(str) {
return (' ' + str + ';').replace(/(.{1,78}) (\|\| |$) ?/gm, '$1\n $2');
} },
cond = [ordinals && ['ordinal', !cardinals], cardinals && ['cardinal', true]].map(compile).map(fold.cond),
body = [fold.vars(this.parser.vars())].concat(_toConsumableArray(cond)).join('\n').replace(/\s+$/gm, '').replace(/^[\s;]*[\r\n]+/gm, ''),
args = ordinals && cardinals ? 'n, ord' : 'n';
return new Function(args, body);
}
}, {
key: 'fnToString',
value: function fnToString(name) {
return Function.prototype.toString.call(this.fn).replace(/^function( \w+)?/, name ? 'function ' + name : 'function').replace('\n/**/', '');
}
}], [{
key: 'load',
value: function load() {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
args.forEach(function (cldr) {
var data = cldr && cldr.supplemental || null;
if (!data) throw new Error('Data does not appear to be CLDR data');
MakePlural.rules = {
cardinal: data['plurals-type-cardinal'] || MakePlural.rules.cardinal,
ordinal: data['plurals-type-ordinal'] || MakePlural.rules.ordinal
};
});
return MakePlural;
}
}]);
return MakePlural;
})();
MakePlural.cardinals = true;
MakePlural.ordinals = false;
MakePlural.rules = { cardinal: {}, ordinal: {} };
return MakePlural;
}());
/* jshint ignore:end */
var validateParameterTypeNumber = function( value, name ) {
validateParameterType(
value,
name,
value === undefined || typeof value === "number",
"Number"
);
};
var validateParameterTypePluralType = function( value, name ) {
validateParameterType(
value,
name,
value === undefined || value === "cardinal" || value === "ordinal",
"String \"cardinal\" or \"ordinal\""
);
};
var pluralGeneratorFn = function( plural ) {
return function pluralGenerator( value ) {
validateParameterPresence( value, "value" );
validateParameterTypeNumber( value, "value" );
return plural( value );
};
};
/**
* .plural( value )
*
* @value [Number]
*
* Return the corresponding form (zero | one | two | few | many | other) of a
* value given locale.
*/
Globalize.plural =
Globalize.prototype.plural = function( value, options ) {
validateParameterPresence( value, "value" );
validateParameterTypeNumber( value, "value" );
return this.pluralGenerator( options )( value );
};
/**
* .pluralGenerator( [options] )
*
* Return a plural function (of the form below).
*
* fn( value )
*
* @value [Number]
*
* Return the corresponding form (zero | one | two | few | many | other) of a value given the
* default/instance locale.
*/
Globalize.pluralGenerator =
Globalize.prototype.pluralGenerator = function( options ) {
var args, cldr, isOrdinal, plural, returnFn, type;
validateParameterTypePlainObject( options, "options" );
options = options || {};
cldr = this.cldr;
args = [ options ];
type = options.type || "cardinal";
validateParameterTypePluralType( options.type, "options.type" );
validateDefaultLocale( cldr );
isOrdinal = type === "ordinal";
cldr.on( "get", validateCldr );
cldr.supplemental([ "plurals-type-" + type, "{language}" ]);
cldr.off( "get", validateCldr );
MakePlural.rules = {};
MakePlural.rules[ type ] = cldr.supplemental( "plurals-type-" + type );
plural = new MakePlural( cldr.attributes.language, {
"ordinals": isOrdinal,
"cardinals": !isOrdinal
});
returnFn = pluralGeneratorFn( plural );
runtimeBind( args, cldr, returnFn, [ plural ] );
return returnFn;
};
return Globalize;
}));
@@ -0,0 +1,201 @@
/**
* Globalize v1.1.1
*
* http://github.com/jquery/globalize
*
* Copyright 2010, 2014 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2016-02-04T12:01Z
*/
/*!
* Globalize v1.1.1 2016-02-04T12:01Z Released under the MIT license
* http://git.io/TrdQbw
*/
(function( root, factory ) {
// UMD returnExports
if ( typeof define === "function" && define.amd ) {
// AMD
define([
"cldr",
"../globalize",
"./number",
"./plural",
"cldr/event",
"cldr/supplemental"
], factory );
} else if ( typeof exports === "object" ) {
// Node, CommonJS
module.exports = factory( require( "cldrjs" ), require( "globalize" ) );
} else {
// Extend global
factory( root.Cldr, root.Globalize );
}
}(this, function( Cldr, Globalize ) {
var formatMessage = Globalize._formatMessage,
runtimeBind = Globalize._runtimeBind,
validateCldr = Globalize._validateCldr,
validateDefaultLocale = Globalize._validateDefaultLocale,
validateParameterPresence = Globalize._validateParameterPresence,
validateParameterTypeString = Globalize._validateParameterTypeString,
validateParameterTypeNumber = Globalize._validateParameterTypeNumber;
/**
* format( value, numberFormatter, pluralGenerator, properties )
*
* @value [Number] The number to format
*
* @numberFormatter [String] A numberFormatter from Globalize.numberFormatter
*
* @pluralGenerator [String] A pluralGenerator from Globalize.pluralGenerator
*
* @properties [Object] containing relative time plural message.
*
* Format relative time.
*/
var relativeTimeFormat = function( value, numberFormatter, pluralGenerator, properties ) {
var relativeTime,
message = properties[ "relative-type-" + value ];
if ( message ) {
return message;
}
relativeTime = value <= 0 ? properties[ "relativeTime-type-past" ]
: properties[ "relativeTime-type-future" ];
value = Math.abs( value );
message = relativeTime[ "relativeTimePattern-count-" + pluralGenerator( value ) ];
return formatMessage( message, [ numberFormatter( value ) ] );
};
var relativeTimeFormatterFn = function( numberFormatter, pluralGenerator, properties ) {
return function relativeTimeFormatter( value ) {
validateParameterPresence( value, "value" );
validateParameterTypeNumber( value, "value" );
return relativeTimeFormat( value, numberFormatter, pluralGenerator, properties );
};
};
/**
* properties( unit, cldr, options )
*
* @unit [String] eg. "day", "week", "month", etc.
*
* @cldr [Cldr instance].
*
* @options [Object]
* - form: [String] eg. "short" or "narrow". Or falsy for default long form.
*
* Return relative time properties.
*/
var relativeTimeProperties = function( unit, cldr, options ) {
var form = options.form,
raw, properties, key, match;
if ( form ) {
unit = unit + "-" + form;
}
raw = cldr.main( [ "dates", "fields", unit ] );
properties = {
"relativeTime-type-future": raw[ "relativeTime-type-future" ],
"relativeTime-type-past": raw[ "relativeTime-type-past" ]
};
for ( key in raw ) {
if ( raw.hasOwnProperty( key ) ) {
match = /relative-type-(-?[0-9]+)/.exec( key );
if ( match ) {
properties[ key ] = raw[ key ];
}
}
}
return properties;
};
/**
* .formatRelativeTime( value, unit [, options] )
*
* @value [Number] The number of unit to format.
*
* @unit [String] see .relativeTimeFormatter() for details.
*
* @options [Object] see .relativeTimeFormatter() for details.
*
* Formats a relative time according to the given unit, options, and the default/instance locale.
*/
Globalize.formatRelativeTime =
Globalize.prototype.formatRelativeTime = function( value, unit, options ) {
validateParameterPresence( value, "value" );
validateParameterTypeNumber( value, "value" );
return this.relativeTimeFormatter( unit, options )( value );
};
/**
* .relativeTimeFormatter( unit [, options ])
*
* @unit [String] String value indicating the unit to be formatted. eg. "day", "week", "month", etc.
*
* @options [Object]
* - form: [String] eg. "short" or "narrow". Or falsy for default long form.
*
* Returns a function that formats a relative time according to the given unit, options, and the
* default/instance locale.
*/
Globalize.relativeTimeFormatter =
Globalize.prototype.relativeTimeFormatter = function( unit, options ) {
var args, cldr, numberFormatter, pluralGenerator, properties, returnFn;
validateParameterPresence( unit, "unit" );
validateParameterTypeString( unit, "unit" );
cldr = this.cldr;
options = options || {};
args = [ unit, options ];
validateDefaultLocale( cldr );
cldr.on( "get", validateCldr );
properties = relativeTimeProperties( unit, cldr, options );
cldr.off( "get", validateCldr );
numberFormatter = this.numberFormatter( options );
pluralGenerator = this.pluralGenerator();
returnFn = relativeTimeFormatterFn( numberFormatter, pluralGenerator, properties );
runtimeBind( args, cldr, returnFn, [ numberFormatter, pluralGenerator, properties ] );
return returnFn;
};
return Globalize;
}));
@@ -0,0 +1,300 @@
/**
* Globalize v1.1.1
*
* http://github.com/jquery/globalize
*
* Copyright 2010, 2014 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2016-02-04T12:01Z
*/
/*!
* Globalize v1.1.1 2016-02-04T12:01Z Released under the MIT license
* http://git.io/TrdQbw
*/
(function( root, factory ) {
// UMD returnExports
if ( typeof define === "function" && define.amd ) {
// AMD
define([
"cldr",
"../globalize",
"./number",
"./plural"
], factory );
} else if ( typeof exports === "object" ) {
// Node, CommonJS
module.exports = factory( require( "cldrjs" ), require( "globalize" ) );
} else {
// Extend global
factory( root.Cldr, root.Globalize );
}
}(this, function( Cldr, Globalize ) {
var formatMessage = Globalize._formatMessage,
runtimeBind = Globalize._runtimeBind,
validateParameterPresence = Globalize._validateParameterPresence,
validateParameterTypePlainObject = Globalize._validateParameterTypePlainObject,
validateParameterTypeNumber = Globalize._validateParameterTypeNumber,
validateParameterTypeString = Globalize._validateParameterTypeString;
/**
* format( value, numberFormatter, pluralGenerator, unitProperies )
*
* @value [Number]
*
* @numberFormatter [Object]: A numberFormatter from Globalize.numberFormatter.
*
* @pluralGenerator [Object]: A pluralGenerator from Globalize.pluralGenerator.
*
* @unitProperies [Object]: localized unit data from cldr.
*
* Format units such as seconds, minutes, days, weeks, etc.
*
* OBS:
*
* Unit Sequences are not implemented.
* http://www.unicode.org/reports/tr35/tr35-35/tr35-general.html#Unit_Sequences
*
* Duration Unit (for composed time unit durations) is not implemented.
* http://www.unicode.org/reports/tr35/tr35-35/tr35-general.html#durationUnit
*/
var unitFormat = function( value, numberFormatter, pluralGenerator, unitProperties ) {
var compoundUnitPattern = unitProperties.compoundUnitPattern, dividend, dividendProperties,
formattedValue, divisor, divisorProperties, message, pluralValue;
unitProperties = unitProperties.unitProperties;
formattedValue = numberFormatter( value );
pluralValue = pluralGenerator( value );
// computed compound unit, eg. "megabyte-per-second".
if ( unitProperties instanceof Array ) {
dividendProperties = unitProperties[ 0 ];
divisorProperties = unitProperties[ 1 ];
dividend = formatMessage( dividendProperties[ pluralValue ], [ value ] );
divisor = formatMessage( divisorProperties.one, [ "" ] ).trim();
return formatMessage( compoundUnitPattern, [ dividend, divisor ] );
}
message = unitProperties[ pluralValue ];
return formatMessage( message, [ formattedValue ] );
};
var unitFormatterFn = function( numberFormatter, pluralGenerator, unitProperties ) {
return function unitFormatter( value ) {
validateParameterPresence( value, "value" );
validateParameterTypeNumber( value, "value" );
return unitFormat( value, numberFormatter, pluralGenerator, unitProperties );
};
};
/**
* categories()
*
* Return all unit categories.
*/
var unitCategories = [ "acceleration", "angle", "area", "digital", "duration", "length", "mass", "power",
"pressure", "speed", "temperature", "volume" ];
function stripPluralGarbage( data ) {
var aux, pluralCount;
if ( data ) {
aux = {};
for ( pluralCount in data ) {
aux[ pluralCount.replace( /unitPattern-count-/, "" ) ] = data[ pluralCount ];
}
}
return aux;
}
/**
* get( unit, form, cldr )
*
* @unit [String] The full type-unit name (eg. duration-second), or the short unit name
* (eg. second).
*
* @form [String] A string describing the form of the unit representation (eg. long,
* short, narrow).
*
* @cldr [Cldr instance].
*
* Return the plural map of a unit, eg: "second"
* { "one": "{0} second",
* "other": "{0} seconds" }
* }
*
* Or the Array of plural maps of a compound-unit, eg: "foot-per-second"
* [ { "one": "{0} foot",
* "other": "{0} feet" },
* { "one": "{0} second",
* "other": "{0} seconds" } ]
*
* Uses the precomputed form of a compound-unit if available, eg: "mile-per-hour"
* { "displayName": "miles per hour",
* "unitPattern-count-one": "{0} mile per hour",
* "unitPattern-count-other": "{0} miles per hour"
* },
*
* Also supports "/" instead of "-per-", eg. "foot/second", using the precomputed form if
* available.
*
* Or the Array of plural maps of a compound-unit, eg: "foot-per-second"
* [ { "one": "{0} foot",
* "other": "{0} feet" },
* { "one": "{0} second",
* "other": "{0} seconds" } ]
*
* Or undefined in case the unit (or a unit of the compound-unit) doesn't exist.
*/
var get = function( unit, form, cldr ) {
var ret;
// Ensure that we get the 'precomputed' form, if present.
unit = unit.replace( /\//, "-per-" );
// Get unit or <category>-unit (eg. "duration-second").
[ "" ].concat( unitCategories ).some(function( category ) {
return ret = cldr.main([
"units",
form,
category.length ? category + "-" + unit : unit
]);
});
// Rename keys s/unitPattern-count-//g.
ret = stripPluralGarbage( ret );
// Compound Unit, eg. "foot-per-second" or "foot/second".
if ( !ret && ( /-per-/ ).test( unit ) ) {
// "Some units already have 'precomputed' forms, such as kilometer-per-hour;
// where such units exist, they should be used in preference" UTS#35.
// Note that precomputed form has already been handled above (!ret).
// Get both recursively.
unit = unit.split( "-per-" );
ret = unit.map(function( unit ) {
return get( unit, form, cldr );
});
if ( !ret[ 0 ] || !ret[ 1 ] ) {
return;
}
}
return ret;
};
var unitGet = get;
/**
* properties( unit, form, cldr )
*
* @unit [String] The full type-unit name (eg. duration-second), or the short unit name
* (eg. second).
*
* @form [String] A string describing the form of the unit representation (eg. long,
* short, narrow).
*
* @cldr [Cldr instance].
*/
var unitProperties = function( unit, form, cldr ) {
var compoundUnitPattern, unitProperties;
compoundUnitPattern = cldr.main( [ "units", form, "per/compoundUnitPattern" ] );
unitProperties = unitGet( unit, form, cldr );
return {
compoundUnitPattern: compoundUnitPattern,
unitProperties: unitProperties
};
};
/**
* Globalize.formatUnit( value, unit, options )
*
* @value [Number]
*
* @unit [String]: The unit (e.g "second", "day", "year")
*
* @options [Object]
* - form: [String] "long", "short" (default), or "narrow".
*
* Format units such as seconds, minutes, days, weeks, etc.
*/
Globalize.formatUnit =
Globalize.prototype.formatUnit = function( value, unit, options ) {
validateParameterPresence( value, "value" );
validateParameterTypeNumber( value, "value" );
return this.unitFormatter( unit, options )( value );
};
/**
* Globalize.unitFormatter( unit, options )
*
* @unit [String]: The unit (e.g "second", "day", "year")
*
* @options [Object]
* - form: [String] "long", "short" (default), or "narrow".
*
* - numberFormatter: [Function] a number formatter function. Defaults to Globalize
* `.numberFormatter()` for the current locale using the default options.
*/
Globalize.unitFormatter =
Globalize.prototype.unitFormatter = function( unit, options ) {
var args, form, numberFormatter, pluralGenerator, returnFn, properties;
validateParameterPresence( unit, "unit" );
validateParameterTypeString( unit, "unit" );
validateParameterTypePlainObject( options, "options" );
options = options || {};
args = [ unit, options ];
form = options.form || "long";
properties = unitProperties( unit, form, this.cldr );
numberFormatter = options.numberFormatter || this.numberFormatter();
pluralGenerator = this.pluralGenerator();
returnFn = unitFormatterFn( numberFormatter, pluralGenerator, properties );
runtimeBind( args, this.cldr, returnFn, [ numberFormatter, pluralGenerator, properties ] );
return returnFn;
};
return Globalize;
}));
Binary file not shown.