code
stringlengths
2
1.05M
//! moment.js //! version : 2.14.1 //! authors : Tim Wood, Iskren Chernev, Moment.js contributors //! license : MIT //! momentjs.com ; (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : global.moment = factory() }(this, function () { 'use strict'; var hookCallback; function utils_hooks__hooks() { return hookCallback.apply(null, arguments); } // This is done to register the method called with moment() // without creating circular dependencies. function setHookCallback(callback) { hookCallback = callback; } function isArray(input) { return input instanceof Array || Object.prototype.toString.call(input) === '[object Array]'; } function isObject(input) { return Object.prototype.toString.call(input) === '[object Object]'; } function isObjectEmpty(obj) { var k; for (k in obj) { // even if its not own property I'd still call it non-empty return false; } return true; } function isDate(input) { return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]'; } function map(arr, fn) { var res = [], i; for (i = 0; i < arr.length; ++i) { res.push(fn(arr[i], i)); } return res; } function hasOwnProp(a, b) { return Object.prototype.hasOwnProperty.call(a, b); } function extend(a, b) { for (var i in b) { if (hasOwnProp(b, i)) { a[i] = b[i]; } } if (hasOwnProp(b, 'toString')) { a.toString = b.toString; } if (hasOwnProp(b, 'valueOf')) { a.valueOf = b.valueOf; } return a; } function create_utc__createUTC(input, format, locale, strict) { return createLocalOrUTC(input, format, locale, strict, true).utc(); } function defaultParsingFlags() { // We need to deep clone this object. return { empty: false, unusedTokens: [], unusedInput: [], overflow: -2, charsLeftOver: 0, nullInput: false, invalidMonth: null, invalidFormat: false, userInvalidated: false, iso: false, parsedDateParts: [], meridiem: null }; } function getParsingFlags(m) { if (m._pf == null) { m._pf = defaultParsingFlags(); } return m._pf; } var some; if (Array.prototype.some) { some = Array.prototype.some; } else { some = function (fun) { var t = Object(this); var len = t.length >>> 0; for (var i = 0; i < len; i++) { if (i in t && fun.call(this, t[i], i, t)) { return true; } } return false; }; } function valid__isValid(m) { if (m._isValid == null) { var flags = getParsingFlags(m); var parsedParts = some.call(flags.parsedDateParts, function (i) { return i != null; }); m._isValid = !isNaN(m._d.getTime()) && flags.overflow < 0 && !flags.empty && !flags.invalidMonth && !flags.invalidWeekday && !flags.nullInput && !flags.invalidFormat && !flags.userInvalidated && (!flags.meridiem || (flags.meridiem && parsedParts)); if (m._strict) { m._isValid = m._isValid && flags.charsLeftOver === 0 && flags.unusedTokens.length === 0 && flags.bigHour === undefined; } } return m._isValid; } function valid__createInvalid(flags) { var m = create_utc__createUTC(NaN); if (flags != null) { extend(getParsingFlags(m), flags); } else { getParsingFlags(m).userInvalidated = true; } return m; } function isUndefined(input) { return input === void 0; } // Plugins that add properties should also add the key here (null value), // so we can properly clone ourselves. var momentProperties = utils_hooks__hooks.momentProperties = []; function copyConfig(to, from) { var i, prop, val; if (!isUndefined(from._isAMomentObject)) { to._isAMomentObject = from._isAMomentObject; } if (!isUndefined(from._i)) { to._i = from._i; } if (!isUndefined(from._f)) { to._f = from._f; } if (!isUndefined(from._l)) { to._l = from._l; } if (!isUndefined(from._strict)) { to._strict = from._strict; } if (!isUndefined(from._tzm)) { to._tzm = from._tzm; } if (!isUndefined(from._isUTC)) { to._isUTC = from._isUTC; } if (!isUndefined(from._offset)) { to._offset = from._offset; } if (!isUndefined(from._pf)) { to._pf = getParsingFlags(from); } if (!isUndefined(from._locale)) { to._locale = from._locale; } if (momentProperties.length > 0) { for (i in momentProperties) { prop = momentProperties[i]; val = from[prop]; if (!isUndefined(val)) { to[prop] = val; } } } return to; } var updateInProgress = false; // Moment prototype object function Moment(config) { copyConfig(this, config); this._d = new Date(config._d != null ? config._d.getTime() : NaN); // Prevent infinite loop in case updateOffset creates new moment // objects. if (updateInProgress === false) { updateInProgress = true; utils_hooks__hooks.updateOffset(this); updateInProgress = false; } } function isMoment(obj) { return obj instanceof Moment || (obj != null && obj._isAMomentObject != null); } function absFloor(number) { if (number < 0) { // -0 -> 0 return Math.ceil(number) || 0; } else { return Math.floor(number); } } function toInt(argumentForCoercion) { var coercedNumber = +argumentForCoercion, value = 0; if (coercedNumber !== 0 && isFinite(coercedNumber)) { value = absFloor(coercedNumber); } return value; } // compare two arrays, return the number of differences function compareArrays(array1, array2, dontConvert) { var len = Math.min(array1.length, array2.length), lengthDiff = Math.abs(array1.length - array2.length), diffs = 0, i; for (i = 0; i < len; i++) { if ((dontConvert && array1[i] !== array2[i]) || (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) { diffs++; } } return diffs + lengthDiff; } function warn(msg) { if (utils_hooks__hooks.suppressDeprecationWarnings === false && (typeof console !== 'undefined') && console.warn) { console.warn('Deprecation warning: ' + msg); } } function deprecate(msg, fn) { var firstTime = true; return extend(function () { if (utils_hooks__hooks.deprecationHandler != null) { utils_hooks__hooks.deprecationHandler(null, msg); } if (firstTime) { warn(msg + '\nArguments: ' + Array.prototype.slice.call(arguments).join(', ') + '\n' + (new Error()).stack); firstTime = false; } return fn.apply(this, arguments); }, fn); } var deprecations = {}; function deprecateSimple(name, msg) { if (utils_hooks__hooks.deprecationHandler != null) { utils_hooks__hooks.deprecationHandler(name, msg); } if (!deprecations[name]) { warn(msg); deprecations[name] = true; } } utils_hooks__hooks.suppressDeprecationWarnings = false; utils_hooks__hooks.deprecationHandler = null; function isFunction(input) { return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]'; } function locale_set__set(config) { var prop, i; for (i in config) { prop = config[i]; if (isFunction(prop)) { this[i] = prop; } else { this['_' + i] = prop; } } this._config = config; // Lenient ordinal parsing accepts just a number in addition to // number + (possibly) stuff coming from _ordinalParseLenient. this._ordinalParseLenient = new RegExp(this._ordinalParse.source + '|' + (/\d{1,2}/).source); } function mergeConfigs(parentConfig, childConfig) { var res = extend({}, parentConfig), prop; for (prop in childConfig) { if (hasOwnProp(childConfig, prop)) { if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) { res[prop] = {}; extend(res[prop], parentConfig[prop]); extend(res[prop], childConfig[prop]); } else if (childConfig[prop] != null) { res[prop] = childConfig[prop]; } else { delete res[prop]; } } } for (prop in parentConfig) { if (hasOwnProp(parentConfig, prop) && !hasOwnProp(childConfig, prop) && isObject(parentConfig[prop])) { // make sure changes to properties don't modify parent config res[prop] = extend({}, res[prop]); } } return res; } function Locale(config) { if (config != null) { this.set(config); } } var keys; if (Object.keys) { keys = Object.keys; } else { keys = function (obj) { var i, res = []; for (i in obj) { if (hasOwnProp(obj, i)) { res.push(i); } } return res; }; } var defaultCalendar = { sameDay: '[Today at] LT', nextDay: '[Tomorrow at] LT', nextWeek: 'dddd [at] LT', lastDay: '[Yesterday at] LT', lastWeek: '[Last] dddd [at] LT', sameElse: 'L' }; function locale_calendar__calendar(key, mom, now) { var output = this._calendar[key] || this._calendar['sameElse']; return isFunction(output) ? output.call(mom, now) : output; } var defaultLongDateFormat = { LTS: 'h:mm:ss A', LT: 'h:mm A', L: 'MM/DD/YYYY', LL: 'MMMM D, YYYY', LLL: 'MMMM D, YYYY h:mm A', LLLL: 'dddd, MMMM D, YYYY h:mm A' }; function longDateFormat(key) { var format = this._longDateFormat[key], formatUpper = this._longDateFormat[key.toUpperCase()]; if (format || !formatUpper) { return format; } this._longDateFormat[key] = formatUpper.replace(/MMMM|MM|DD|dddd/g, function (val) { return val.slice(1); }); return this._longDateFormat[key]; } var defaultInvalidDate = 'Invalid date'; function invalidDate() { return this._invalidDate; } var defaultOrdinal = '%d'; var defaultOrdinalParse = /\d{1,2}/; function ordinal(number) { return this._ordinal.replace('%d', number); } var defaultRelativeTime = { future: 'in %s', past: '%s ago', s: 'a few seconds', m: 'a minute', mm: '%d minutes', h: 'an hour', hh: '%d hours', d: 'a day', dd: '%d days', M: 'a month', MM: '%d months', y: 'a year', yy: '%d years' }; function relative__relativeTime(number, withoutSuffix, string, isFuture) { var output = this._relativeTime[string]; return (isFunction(output)) ? output(number, withoutSuffix, string, isFuture) : output.replace(/%d/i, number); } function pastFuture(diff, output) { var format = this._relativeTime[diff > 0 ? 'future' : 'past']; return isFunction(format) ? format(output) : format.replace(/%s/i, output); } var aliases = {}; function addUnitAlias(unit, shorthand) { var lowerCase = unit.toLowerCase(); aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit; } function normalizeUnits(units) { return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined; } function normalizeObjectUnits(inputObject) { var normalizedInput = {}, normalizedProp, prop; for (prop in inputObject) { if (hasOwnProp(inputObject, prop)) { normalizedProp = normalizeUnits(prop); if (normalizedProp) { normalizedInput[normalizedProp] = inputObject[prop]; } } } return normalizedInput; } var priorities = {}; function addUnitPriority(unit, priority) { priorities[unit] = priority; } function getPrioritizedUnits(unitsObj) { var units = []; for (var u in unitsObj) { units.push({ unit: u, priority: priorities[u] }); } units.sort(function (a, b) { return a.priority - b.priority; }); return units; } function makeGetSet(unit, keepTime) { return function (value) { if (value != null) { get_set__set(this, unit, value); utils_hooks__hooks.updateOffset(this, keepTime); return this; } else { return get_set__get(this, unit); } }; } function get_set__get(mom, unit) { return mom.isValid() ? mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN; } function get_set__set(mom, unit, value) { if (mom.isValid()) { mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value); } } // MOMENTS function stringGet(units) { units = normalizeUnits(units); if (isFunction(this[units])) { return this[units](); } return this; } function stringSet(units, value) { if (typeof units === 'object') { units = normalizeObjectUnits(units); var prioritized = getPrioritizedUnits(units); for (var i = 0; i < prioritized.length; i++) { this[prioritized[i].unit](units[prioritized[i].unit]); } } else { units = normalizeUnits(units); if (isFunction(this[units])) { return this[units](value); } } return this; } function zeroFill(number, targetLength, forceSign) { var absNumber = '' + Math.abs(number), zerosToFill = targetLength - absNumber.length, sign = number >= 0; return (sign ? (forceSign ? '+' : '') : '-') + Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber; } var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g; var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g; var formatFunctions = {}; var formatTokenFunctions = {}; // token: 'M' // padded: ['MM', 2] // ordinal: 'Mo' // callback: function () { this.month() + 1 } function addFormatToken(token, padded, ordinal, callback) { var func = callback; if (typeof callback === 'string') { func = function () { return this[callback](); }; } if (token) { formatTokenFunctions[token] = func; } if (padded) { formatTokenFunctions[padded[0]] = function () { return zeroFill(func.apply(this, arguments), padded[1], padded[2]); }; } if (ordinal) { formatTokenFunctions[ordinal] = function () { return this.localeData().ordinal(func.apply(this, arguments), token); }; } } function removeFormattingTokens(input) { if (input.match(/\[[\s\S]/)) { return input.replace(/^\[|\]$/g, ''); } return input.replace(/\\/g, ''); } function makeFormatFunction(format) { var array = format.match(formattingTokens), i, length; for (i = 0, length = array.length; i < length; i++) { if (formatTokenFunctions[array[i]]) { array[i] = formatTokenFunctions[array[i]]; } else { array[i] = removeFormattingTokens(array[i]); } } return function (mom) { var output = '', i; for (i = 0; i < length; i++) { output += array[i] instanceof Function ? array[i].call(mom, format) : array[i]; } return output; }; } // format date using native date object function formatMoment(m, format) { if (!m.isValid()) { return m.localeData().invalidDate(); } format = expandFormat(format, m.localeData()); formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format); return formatFunctions[format](m); } function expandFormat(format, locale) { var i = 5; function replaceLongDateFormatTokens(input) { return locale.longDateFormat(input) || input; } localFormattingTokens.lastIndex = 0; while (i >= 0 && localFormattingTokens.test(format)) { format = format.replace(localFormattingTokens, replaceLongDateFormatTokens); localFormattingTokens.lastIndex = 0; i -= 1; } return format; } var match1 = /\d/; // 0 - 9 var match2 = /\d\d/; // 00 - 99 var match3 = /\d{3}/; // 000 - 999 var match4 = /\d{4}/; // 0000 - 9999 var match6 = /[+-]?\d{6}/; // -999999 - 999999 var match1to2 = /\d\d?/; // 0 - 99 var match3to4 = /\d\d\d\d?/; // 999 - 9999 var match5to6 = /\d\d\d\d\d\d?/; // 99999 - 999999 var match1to3 = /\d{1,3}/; // 0 - 999 var match1to4 = /\d{1,4}/; // 0 - 9999 var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999 var matchUnsigned = /\d+/; // 0 - inf var matchSigned = /[+-]?\d+/; // -inf - inf var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi; // +00 -00 +00:00 -00:00 +0000 -0000 or Z var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123 // any word (or two) characters or numbers including two/three word month in arabic. // includes scottish gaelic two word and hyphenated months var matchWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i; var regexes = {}; function addRegexToken(token, regex, strictRegex) { regexes[token] = isFunction(regex) ? regex : function (isStrict, localeData) { return (isStrict && strictRegex) ? strictRegex : regex; }; } function getParseRegexForToken(token, config) { if (!hasOwnProp(regexes, token)) { return new RegExp(unescapeFormat(token)); } return regexes[token](config._strict, config._locale); } // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript function unescapeFormat(s) { return regexEscape(s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) { return p1 || p2 || p3 || p4; })); } function regexEscape(s) { return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); } var tokens = {}; function addParseToken(token, callback) { var i, func = callback; if (typeof token === 'string') { token = [token]; } if (typeof callback === 'number') { func = function (input, array) { array[callback] = toInt(input); }; } for (i = 0; i < token.length; i++) { tokens[token[i]] = func; } } function addWeekParseToken(token, callback) { addParseToken(token, function (input, array, config, token) { config._w = config._w || {}; callback(input, config._w, config, token); }); } function addTimeToArrayFromToken(token, input, config) { if (input != null && hasOwnProp(tokens, token)) { tokens[token](input, config._a, config, token); } } var YEAR = 0; var MONTH = 1; var DATE = 2; var HOUR = 3; var MINUTE = 4; var SECOND = 5; var MILLISECOND = 6; var WEEK = 7; var WEEKDAY = 8; var indexOf; if (Array.prototype.indexOf) { indexOf = Array.prototype.indexOf; } else { indexOf = function (o) { // I know var i; for (i = 0; i < this.length; ++i) { if (this[i] === o) { return i; } } return -1; }; } function daysInMonth(year, month) { return new Date(Date.UTC(year, month + 1, 0)).getUTCDate(); } // FORMATTING addFormatToken('M', ['MM', 2], 'Mo', function () { return this.month() + 1; }); addFormatToken('MMM', 0, 0, function (format) { return this.localeData().monthsShort(this, format); }); addFormatToken('MMMM', 0, 0, function (format) { return this.localeData().months(this, format); }); // ALIASES addUnitAlias('month', 'M'); // PRIORITY addUnitPriority('month', 8); // PARSING addRegexToken('M', match1to2); addRegexToken('MM', match1to2, match2); addRegexToken('MMM', function (isStrict, locale) { return locale.monthsShortRegex(isStrict); }); addRegexToken('MMMM', function (isStrict, locale) { return locale.monthsRegex(isStrict); }); addParseToken(['M', 'MM'], function (input, array) { array[MONTH] = toInt(input) - 1; }); addParseToken(['MMM', 'MMMM'], function (input, array, config, token) { var month = config._locale.monthsParse(input, token, config._strict); // if we didn't find a month name, mark the date as invalid. if (month != null) { array[MONTH] = month; } else { getParsingFlags(config).invalidMonth = input; } }); // LOCALES var MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/; var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'); function localeMonths(m, format) { return isArray(this._months) ? this._months[m.month()] : this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? 'format' : 'standalone'][m.month()]; } var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'); function localeMonthsShort(m, format) { return isArray(this._monthsShort) ? this._monthsShort[m.month()] : this._monthsShort[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()]; } function units_month__handleStrictParse(monthName, format, strict) { var i, ii, mom, llc = monthName.toLocaleLowerCase(); if (!this._monthsParse) { // this is not used this._monthsParse = []; this._longMonthsParse = []; this._shortMonthsParse = []; for (i = 0; i < 12; ++i) { mom = create_utc__createUTC([2000, i]); this._shortMonthsParse[i] = this.monthsShort(mom, '').toLocaleLowerCase(); this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase(); } } if (strict) { if (format === 'MMM') { ii = indexOf.call(this._shortMonthsParse, llc); return ii !== -1 ? ii : null; } else { ii = indexOf.call(this._longMonthsParse, llc); return ii !== -1 ? ii : null; } } else { if (format === 'MMM') { ii = indexOf.call(this._shortMonthsParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._longMonthsParse, llc); return ii !== -1 ? ii : null; } else { ii = indexOf.call(this._longMonthsParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._shortMonthsParse, llc); return ii !== -1 ? ii : null; } } } function localeMonthsParse(monthName, format, strict) { var i, mom, regex; if (this._monthsParseExact) { return units_month__handleStrictParse.call(this, monthName, format, strict); } if (!this._monthsParse) { this._monthsParse = []; this._longMonthsParse = []; this._shortMonthsParse = []; } // TODO: add sorting // Sorting makes sure if one month (or abbr) is a prefix of another // see sorting in computeMonthsParse for (i = 0; i < 12; i++) { // make the regex if we don't have it already mom = create_utc__createUTC([2000, i]); if (strict && !this._longMonthsParse[i]) { this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i'); this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i'); } if (!strict && !this._monthsParse[i]) { regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) { return i; } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) { return i; } else if (!strict && this._monthsParse[i].test(monthName)) { return i; } } } // MOMENTS function setMonth(mom, value) { var dayOfMonth; if (!mom.isValid()) { // No op return mom; } if (typeof value === 'string') { if (/^\d+$/.test(value)) { value = toInt(value); } else { value = mom.localeData().monthsParse(value); // TODO: Another silent failure? if (typeof value !== 'number') { return mom; } } } dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value)); mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth); return mom; } function getSetMonth(value) { if (value != null) { setMonth(this, value); utils_hooks__hooks.updateOffset(this, true); return this; } else { return get_set__get(this, 'Month'); } } function getDaysInMonth() { return daysInMonth(this.year(), this.month()); } var defaultMonthsShortRegex = matchWord; function monthsShortRegex(isStrict) { if (this._monthsParseExact) { if (!hasOwnProp(this, '_monthsRegex')) { computeMonthsParse.call(this); } if (isStrict) { return this._monthsShortStrictRegex; } else { return this._monthsShortRegex; } } else { if (!hasOwnProp(this, '_monthsShortRegex')) { this._monthsShortRegex = defaultMonthsShortRegex; } return this._monthsShortStrictRegex && isStrict ? this._monthsShortStrictRegex : this._monthsShortRegex; } } var defaultMonthsRegex = matchWord; function monthsRegex(isStrict) { if (this._monthsParseExact) { if (!hasOwnProp(this, '_monthsRegex')) { computeMonthsParse.call(this); } if (isStrict) { return this._monthsStrictRegex; } else { return this._monthsRegex; } } else { if (!hasOwnProp(this, '_monthsRegex')) { this._monthsRegex = defaultMonthsRegex; } return this._monthsStrictRegex && isStrict ? this._monthsStrictRegex : this._monthsRegex; } } function computeMonthsParse() { function cmpLenRev(a, b) { return b.length - a.length; } var shortPieces = [], longPieces = [], mixedPieces = [], i, mom; for (i = 0; i < 12; i++) { // make the regex if we don't have it already mom = create_utc__createUTC([2000, i]); shortPieces.push(this.monthsShort(mom, '')); longPieces.push(this.months(mom, '')); mixedPieces.push(this.months(mom, '')); mixedPieces.push(this.monthsShort(mom, '')); } // Sorting makes sure if one month (or abbr) is a prefix of another it // will match the longer piece. shortPieces.sort(cmpLenRev); longPieces.sort(cmpLenRev); mixedPieces.sort(cmpLenRev); for (i = 0; i < 12; i++) { shortPieces[i] = regexEscape(shortPieces[i]); longPieces[i] = regexEscape(longPieces[i]); } for (i = 0; i < 24; i++) { mixedPieces[i] = regexEscape(mixedPieces[i]); } this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); this._monthsShortRegex = this._monthsRegex; this._monthsStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i'); this._monthsShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i'); } // FORMATTING addFormatToken('Y', 0, 0, function () { var y = this.year(); return y <= 9999 ? '' + y : '+' + y; }); addFormatToken(0, ['YY', 2], 0, function () { return this.year() % 100; }); addFormatToken(0, ['YYYY', 4], 0, 'year'); addFormatToken(0, ['YYYYY', 5], 0, 'year'); addFormatToken(0, ['YYYYYY', 6, true], 0, 'year'); // ALIASES addUnitAlias('year', 'y'); // PRIORITIES addUnitPriority('year', 1); // PARSING addRegexToken('Y', matchSigned); addRegexToken('YY', match1to2, match2); addRegexToken('YYYY', match1to4, match4); addRegexToken('YYYYY', match1to6, match6); addRegexToken('YYYYYY', match1to6, match6); addParseToken(['YYYYY', 'YYYYYY'], YEAR); addParseToken('YYYY', function (input, array) { array[YEAR] = input.length === 2 ? utils_hooks__hooks.parseTwoDigitYear(input) : toInt(input); }); addParseToken('YY', function (input, array) { array[YEAR] = utils_hooks__hooks.parseTwoDigitYear(input); }); addParseToken('Y', function (input, array) { array[YEAR] = parseInt(input, 10); }); // HELPERS function daysInYear(year) { return isLeapYear(year) ? 366 : 365; } function isLeapYear(year) { return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; } // HOOKS utils_hooks__hooks.parseTwoDigitYear = function (input) { return toInt(input) + (toInt(input) > 68 ? 1900 : 2000); }; // MOMENTS var getSetYear = makeGetSet('FullYear', true); function getIsLeapYear() { return isLeapYear(this.year()); } function createDate(y, m, d, h, M, s, ms) { //can't just apply() to create a date: //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply var date = new Date(y, m, d, h, M, s, ms); //the date constructor remaps years 0-99 to 1900-1999 if (y < 100 && y >= 0 && isFinite(date.getFullYear())) { date.setFullYear(y); } return date; } function createUTCDate(y) { var date = new Date(Date.UTC.apply(null, arguments)); //the Date.UTC function remaps years 0-99 to 1900-1999 if (y < 100 && y >= 0 && isFinite(date.getUTCFullYear())) { date.setUTCFullYear(y); } return date; } // start-of-first-week - start-of-year function firstWeekOffset(year, dow, doy) { var // first-week day -- which january is always in the first week (4 for iso, 1 for other) fwd = 7 + dow - doy, // first-week day local weekday -- which local weekday is fwd fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7; return -fwdlw + fwd - 1; } //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday function dayOfYearFromWeeks(year, week, weekday, dow, doy) { var localWeekday = (7 + weekday - dow) % 7, weekOffset = firstWeekOffset(year, dow, doy), dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset, resYear, resDayOfYear; if (dayOfYear <= 0) { resYear = year - 1; resDayOfYear = daysInYear(resYear) + dayOfYear; } else if (dayOfYear > daysInYear(year)) { resYear = year + 1; resDayOfYear = dayOfYear - daysInYear(year); } else { resYear = year; resDayOfYear = dayOfYear; } return { year: resYear, dayOfYear: resDayOfYear }; } function weekOfYear(mom, dow, doy) { var weekOffset = firstWeekOffset(mom.year(), dow, doy), week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1, resWeek, resYear; if (week < 1) { resYear = mom.year() - 1; resWeek = week + weeksInYear(resYear, dow, doy); } else if (week > weeksInYear(mom.year(), dow, doy)) { resWeek = week - weeksInYear(mom.year(), dow, doy); resYear = mom.year() + 1; } else { resYear = mom.year(); resWeek = week; } return { week: resWeek, year: resYear }; } function weeksInYear(year, dow, doy) { var weekOffset = firstWeekOffset(year, dow, doy), weekOffsetNext = firstWeekOffset(year + 1, dow, doy); return (daysInYear(year) - weekOffset + weekOffsetNext) / 7; } // FORMATTING addFormatToken('w', ['ww', 2], 'wo', 'week'); addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek'); // ALIASES addUnitAlias('week', 'w'); addUnitAlias('isoWeek', 'W'); // PRIORITIES addUnitPriority('week', 5); addUnitPriority('isoWeek', 5); // PARSING addRegexToken('w', match1to2); addRegexToken('ww', match1to2, match2); addRegexToken('W', match1to2); addRegexToken('WW', match1to2, match2); addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) { week[token.substr(0, 1)] = toInt(input); }); // HELPERS // LOCALES function localeWeek(mom) { return weekOfYear(mom, this._week.dow, this._week.doy).week; } var defaultLocaleWeek = { dow: 0, // Sunday is the first day of the week. doy: 6 // The week that contains Jan 1st is the first week of the year. }; function localeFirstDayOfWeek() { return this._week.dow; } function localeFirstDayOfYear() { return this._week.doy; } // MOMENTS function getSetWeek(input) { var week = this.localeData().week(this); return input == null ? week : this.add((input - week) * 7, 'd'); } function getSetISOWeek(input) { var week = weekOfYear(this, 1, 4).week; return input == null ? week : this.add((input - week) * 7, 'd'); } // FORMATTING addFormatToken('d', 0, 'do', 'day'); addFormatToken('dd', 0, 0, function (format) { return this.localeData().weekdaysMin(this, format); }); addFormatToken('ddd', 0, 0, function (format) { return this.localeData().weekdaysShort(this, format); }); addFormatToken('dddd', 0, 0, function (format) { return this.localeData().weekdays(this, format); }); addFormatToken('e', 0, 0, 'weekday'); addFormatToken('E', 0, 0, 'isoWeekday'); // ALIASES addUnitAlias('day', 'd'); addUnitAlias('weekday', 'e'); addUnitAlias('isoWeekday', 'E'); // PRIORITY addUnitPriority('day', 11); addUnitPriority('weekday', 11); addUnitPriority('isoWeekday', 11); // PARSING addRegexToken('d', match1to2); addRegexToken('e', match1to2); addRegexToken('E', match1to2); addRegexToken('dd', function (isStrict, locale) { return locale.weekdaysMinRegex(isStrict); }); addRegexToken('ddd', function (isStrict, locale) { return locale.weekdaysShortRegex(isStrict); }); addRegexToken('dddd', function (isStrict, locale) { return locale.weekdaysRegex(isStrict); }); addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) { var weekday = config._locale.weekdaysParse(input, token, config._strict); // if we didn't get a weekday name, mark the date as invalid if (weekday != null) { week.d = weekday; } else { getParsingFlags(config).invalidWeekday = input; } }); addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) { week[token] = toInt(input); }); // HELPERS function parseWeekday(input, locale) { if (typeof input !== 'string') { return input; } if (!isNaN(input)) { return parseInt(input, 10); } input = locale.weekdaysParse(input); if (typeof input === 'number') { return input; } return null; } function parseIsoWeekday(input, locale) { if (typeof input === 'string') { return locale.weekdaysParse(input) % 7 || 7; } return isNaN(input) ? null : input; } // LOCALES var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'); function localeWeekdays(m, format) { return isArray(this._weekdays) ? this._weekdays[m.day()] : this._weekdays[this._weekdays.isFormat.test(format) ? 'format' : 'standalone'][m.day()]; } var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'); function localeWeekdaysShort(m) { return this._weekdaysShort[m.day()]; } var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'); function localeWeekdaysMin(m) { return this._weekdaysMin[m.day()]; } function day_of_week__handleStrictParse(weekdayName, format, strict) { var i, ii, mom, llc = weekdayName.toLocaleLowerCase(); if (!this._weekdaysParse) { this._weekdaysParse = []; this._shortWeekdaysParse = []; this._minWeekdaysParse = []; for (i = 0; i < 7; ++i) { mom = create_utc__createUTC([2000, 1]).day(i); this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase(); this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase(); this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase(); } } if (strict) { if (format === 'dddd') { ii = indexOf.call(this._weekdaysParse, llc); return ii !== -1 ? ii : null; } else if (format === 'ddd') { ii = indexOf.call(this._shortWeekdaysParse, llc); return ii !== -1 ? ii : null; } else { ii = indexOf.call(this._minWeekdaysParse, llc); return ii !== -1 ? ii : null; } } else { if (format === 'dddd') { ii = indexOf.call(this._weekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._shortWeekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._minWeekdaysParse, llc); return ii !== -1 ? ii : null; } else if (format === 'ddd') { ii = indexOf.call(this._shortWeekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._weekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._minWeekdaysParse, llc); return ii !== -1 ? ii : null; } else { ii = indexOf.call(this._minWeekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._weekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._shortWeekdaysParse, llc); return ii !== -1 ? ii : null; } } } function localeWeekdaysParse(weekdayName, format, strict) { var i, mom, regex; if (this._weekdaysParseExact) { return day_of_week__handleStrictParse.call(this, weekdayName, format, strict); } if (!this._weekdaysParse) { this._weekdaysParse = []; this._minWeekdaysParse = []; this._shortWeekdaysParse = []; this._fullWeekdaysParse = []; } for (i = 0; i < 7; i++) { // make the regex if we don't have it already mom = create_utc__createUTC([2000, 1]).day(i); if (strict && !this._fullWeekdaysParse[i]) { this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\.?') + '$', 'i'); this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\.?') + '$', 'i'); this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\.?') + '$', 'i'); } if (!this._weekdaysParse[i]) { regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, ''); this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) { return i; } else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) { return i; } else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) { return i; } else if (!strict && this._weekdaysParse[i].test(weekdayName)) { return i; } } } // MOMENTS function getSetDayOfWeek(input) { if (!this.isValid()) { return input != null ? this : NaN; } var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); if (input != null) { input = parseWeekday(input, this.localeData()); return this.add(input - day, 'd'); } else { return day; } } function getSetLocaleDayOfWeek(input) { if (!this.isValid()) { return input != null ? this : NaN; } var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7; return input == null ? weekday : this.add(input - weekday, 'd'); } function getSetISODayOfWeek(input) { if (!this.isValid()) { return input != null ? this : NaN; } // behaves the same as moment#day except // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) // as a setter, sunday should belong to the previous week. if (input != null) { var weekday = parseIsoWeekday(input, this.localeData()); return this.day(this.day() % 7 ? weekday : weekday - 7); } else { return this.day() || 7; } } var defaultWeekdaysRegex = matchWord; function weekdaysRegex(isStrict) { if (this._weekdaysParseExact) { if (!hasOwnProp(this, '_weekdaysRegex')) { computeWeekdaysParse.call(this); } if (isStrict) { return this._weekdaysStrictRegex; } else { return this._weekdaysRegex; } } else { if (!hasOwnProp(this, '_weekdaysRegex')) { this._weekdaysRegex = defaultWeekdaysRegex; } return this._weekdaysStrictRegex && isStrict ? this._weekdaysStrictRegex : this._weekdaysRegex; } } var defaultWeekdaysShortRegex = matchWord; function weekdaysShortRegex(isStrict) { if (this._weekdaysParseExact) { if (!hasOwnProp(this, '_weekdaysRegex')) { computeWeekdaysParse.call(this); } if (isStrict) { return this._weekdaysShortStrictRegex; } else { return this._weekdaysShortRegex; } } else { if (!hasOwnProp(this, '_weekdaysShortRegex')) { this._weekdaysShortRegex = defaultWeekdaysShortRegex; } return this._weekdaysShortStrictRegex && isStrict ? this._weekdaysShortStrictRegex : this._weekdaysShortRegex; } } var defaultWeekdaysMinRegex = matchWord; function weekdaysMinRegex(isStrict) { if (this._weekdaysParseExact) { if (!hasOwnProp(this, '_weekdaysRegex')) { computeWeekdaysParse.call(this); } if (isStrict) { return this._weekdaysMinStrictRegex; } else { return this._weekdaysMinRegex; } } else { if (!hasOwnProp(this, '_weekdaysMinRegex')) { this._weekdaysMinRegex = defaultWeekdaysMinRegex; } return this._weekdaysMinStrictRegex && isStrict ? this._weekdaysMinStrictRegex : this._weekdaysMinRegex; } } function computeWeekdaysParse() { function cmpLenRev(a, b) { return b.length - a.length; } var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [], i, mom, minp, shortp, longp; for (i = 0; i < 7; i++) { // make the regex if we don't have it already mom = create_utc__createUTC([2000, 1]).day(i); minp = this.weekdaysMin(mom, ''); shortp = this.weekdaysShort(mom, ''); longp = this.weekdays(mom, ''); minPieces.push(minp); shortPieces.push(shortp); longPieces.push(longp); mixedPieces.push(minp); mixedPieces.push(shortp); mixedPieces.push(longp); } // Sorting makes sure if one weekday (or abbr) is a prefix of another it // will match the longer piece. minPieces.sort(cmpLenRev); shortPieces.sort(cmpLenRev); longPieces.sort(cmpLenRev); mixedPieces.sort(cmpLenRev); for (i = 0; i < 7; i++) { shortPieces[i] = regexEscape(shortPieces[i]); longPieces[i] = regexEscape(longPieces[i]); mixedPieces[i] = regexEscape(mixedPieces[i]); } this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); this._weekdaysShortRegex = this._weekdaysRegex; this._weekdaysMinRegex = this._weekdaysRegex; this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i'); this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i'); this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i'); } // FORMATTING function hFormat() { return this.hours() % 12 || 12; } function kFormat() { return this.hours() || 24; } addFormatToken('H', ['HH', 2], 0, 'hour'); addFormatToken('h', ['hh', 2], 0, hFormat); addFormatToken('k', ['kk', 2], 0, kFormat); addFormatToken('hmm', 0, 0, function () { return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2); }); addFormatToken('hmmss', 0, 0, function () { return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2); }); addFormatToken('Hmm', 0, 0, function () { return '' + this.hours() + zeroFill(this.minutes(), 2); }); addFormatToken('Hmmss', 0, 0, function () { return '' + this.hours() + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2); }); function meridiem(token, lowercase) { addFormatToken(token, 0, 0, function () { return this.localeData().meridiem(this.hours(), this.minutes(), lowercase); }); } meridiem('a', true); meridiem('A', false); // ALIASES addUnitAlias('hour', 'h'); // PRIORITY addUnitPriority('hour', 13); // PARSING function matchMeridiem(isStrict, locale) { return locale._meridiemParse; } addRegexToken('a', matchMeridiem); addRegexToken('A', matchMeridiem); addRegexToken('H', match1to2); addRegexToken('h', match1to2); addRegexToken('HH', match1to2, match2); addRegexToken('hh', match1to2, match2); addRegexToken('hmm', match3to4); addRegexToken('hmmss', match5to6); addRegexToken('Hmm', match3to4); addRegexToken('Hmmss', match5to6); addParseToken(['H', 'HH'], HOUR); addParseToken(['a', 'A'], function (input, array, config) { config._isPm = config._locale.isPM(input); config._meridiem = input; }); addParseToken(['h', 'hh'], function (input, array, config) { array[HOUR] = toInt(input); getParsingFlags(config).bigHour = true; }); addParseToken('hmm', function (input, array, config) { var pos = input.length - 2; array[HOUR] = toInt(input.substr(0, pos)); array[MINUTE] = toInt(input.substr(pos)); getParsingFlags(config).bigHour = true; }); addParseToken('hmmss', function (input, array, config) { var pos1 = input.length - 4; var pos2 = input.length - 2; array[HOUR] = toInt(input.substr(0, pos1)); array[MINUTE] = toInt(input.substr(pos1, 2)); array[SECOND] = toInt(input.substr(pos2)); getParsingFlags(config).bigHour = true; }); addParseToken('Hmm', function (input, array, config) { var pos = input.length - 2; array[HOUR] = toInt(input.substr(0, pos)); array[MINUTE] = toInt(input.substr(pos)); }); addParseToken('Hmmss', function (input, array, config) { var pos1 = input.length - 4; var pos2 = input.length - 2; array[HOUR] = toInt(input.substr(0, pos1)); array[MINUTE] = toInt(input.substr(pos1, 2)); array[SECOND] = toInt(input.substr(pos2)); }); // LOCALES function localeIsPM(input) { // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays // Using charAt should be more compatible. return ((input + '').toLowerCase().charAt(0) === 'p'); } var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i; function localeMeridiem(hours, minutes, isLower) { if (hours > 11) { return isLower ? 'pm' : 'PM'; } else { return isLower ? 'am' : 'AM'; } } // MOMENTS // Setting the hour should keep the time, because the user explicitly // specified which hour he wants. So trying to maintain the same hour (in // a new timezone) makes sense. Adding/subtracting hours does not follow // this rule. var getSetHour = makeGetSet('Hours', true); var baseConfig = { calendar: defaultCalendar, longDateFormat: defaultLongDateFormat, invalidDate: defaultInvalidDate, ordinal: defaultOrdinal, ordinalParse: defaultOrdinalParse, relativeTime: defaultRelativeTime, months: defaultLocaleMonths, monthsShort: defaultLocaleMonthsShort, week: defaultLocaleWeek, weekdays: defaultLocaleWeekdays, weekdaysMin: defaultLocaleWeekdaysMin, weekdaysShort: defaultLocaleWeekdaysShort, meridiemParse: defaultLocaleMeridiemParse }; // internal storage for locale config files var locales = {}; var globalLocale; function normalizeLocale(key) { return key ? key.toLowerCase().replace('_', '-') : key; } // pick the locale from the array // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root function chooseLocale(names) { var i = 0, j, next, locale, split; while (i < names.length) { split = normalizeLocale(names[i]).split('-'); j = split.length; next = normalizeLocale(names[i + 1]); next = next ? next.split('-') : null; while (j > 0) { locale = loadLocale(split.slice(0, j).join('-')); if (locale) { return locale; } if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) { //the next array item is better than a shallower substring of this one break; } j--; } i++; } return null; } function loadLocale(name) { var oldLocale = null; // TODO: Find a better way to register and load all the locales in Node if (!locales[name] && (typeof module !== 'undefined') && module && module.exports) { try { oldLocale = globalLocale._abbr; require('./locale/' + name); // because defineLocale currently also sets the global locale, we // want to undo that for lazy loaded locales locale_locales__getSetGlobalLocale(oldLocale); } catch (e) { } } return locales[name]; } // This function will load locale and then set the global locale. If // no arguments are passed in, it will simply return the current global // locale key. function locale_locales__getSetGlobalLocale(key, values) { var data; if (key) { if (isUndefined(values)) { data = locale_locales__getLocale(key); } else { data = defineLocale(key, values); } if (data) { // moment.duration._locale = moment._locale = data; globalLocale = data; } } return globalLocale._abbr; } function defineLocale(name, config) { if (config !== null) { var parentConfig = baseConfig; config.abbr = name; if (locales[name] != null) { deprecateSimple('defineLocaleOverride', 'use moment.updateLocale(localeName, config) to change ' + 'an existing locale. moment.defineLocale(localeName, ' + 'config) should only be used for creating a new locale ' + 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.'); parentConfig = locales[name]._config; } else if (config.parentLocale != null) { if (locales[config.parentLocale] != null) { parentConfig = locales[config.parentLocale]._config; } else { // treat as if there is no base config deprecateSimple('parentLocaleUndefined', 'specified parentLocale is not defined yet. See http://momentjs.com/guides/#/warnings/parent-locale/'); } } locales[name] = new Locale(mergeConfigs(parentConfig, config)); // backwards compat for now: also set the locale locale_locales__getSetGlobalLocale(name); return locales[name]; } else { // useful for testing delete locales[name]; return null; } } function updateLocale(name, config) { if (config != null) { var locale, parentConfig = baseConfig; // MERGE if (locales[name] != null) { parentConfig = locales[name]._config; } config = mergeConfigs(parentConfig, config); locale = new Locale(config); locale.parentLocale = locales[name]; locales[name] = locale; // backwards compat for now: also set the locale locale_locales__getSetGlobalLocale(name); } else { // pass null for config to unupdate, useful for tests if (locales[name] != null) { if (locales[name].parentLocale != null) { locales[name] = locales[name].parentLocale; } else if (locales[name] != null) { delete locales[name]; } } } return locales[name]; } // returns locale data function locale_locales__getLocale(key) { var locale; if (key && key._locale && key._locale._abbr) { key = key._locale._abbr; } if (!key) { return globalLocale; } if (!isArray(key)) { //short-circuit everything else locale = loadLocale(key); if (locale) { return locale; } key = [key]; } return chooseLocale(key); } function locale_locales__listLocales() { return keys(locales); } function checkOverflow(m) { var overflow; var a = m._a; if (a && getParsingFlags(m).overflow === -2) { overflow = a[MONTH] < 0 || a[MONTH] > 11 ? MONTH : a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE : a[HOUR] < 0 || a[HOUR] > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR : a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE : a[SECOND] < 0 || a[SECOND] > 59 ? SECOND : a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND : -1; if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) { overflow = DATE; } if (getParsingFlags(m)._overflowWeeks && overflow === -1) { overflow = WEEK; } if (getParsingFlags(m)._overflowWeekday && overflow === -1) { overflow = WEEKDAY; } getParsingFlags(m).overflow = overflow; } return m; } // iso 8601 regex // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00) var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?/; var basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?/; var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/; var isoDates = [ ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/], ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/], ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/], ['GGGG-[W]WW', /\d{4}-W\d\d/, false], ['YYYY-DDD', /\d{4}-\d{3}/], ['YYYY-MM', /\d{4}-\d\d/, false], ['YYYYYYMMDD', /[+-]\d{10}/], ['YYYYMMDD', /\d{8}/], // YYYYMM is NOT allowed by the standard ['GGGG[W]WWE', /\d{4}W\d{3}/], ['GGGG[W]WW', /\d{4}W\d{2}/, false], ['YYYYDDD', /\d{7}/] ]; // iso time formats and regexes var isoTimes = [ ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/], ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/], ['HH:mm:ss', /\d\d:\d\d:\d\d/], ['HH:mm', /\d\d:\d\d/], ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/], ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/], ['HHmmss', /\d\d\d\d\d\d/], ['HHmm', /\d\d\d\d/], ['HH', /\d\d/] ]; var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i; // date from iso format function configFromISO(config) { var i, l, string = config._i, match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string), allowTime, dateFormat, timeFormat, tzFormat; if (match) { getParsingFlags(config).iso = true; for (i = 0, l = isoDates.length; i < l; i++) { if (isoDates[i][1].exec(match[1])) { dateFormat = isoDates[i][0]; allowTime = isoDates[i][2] !== false; break; } } if (dateFormat == null) { config._isValid = false; return; } if (match[3]) { for (i = 0, l = isoTimes.length; i < l; i++) { if (isoTimes[i][1].exec(match[3])) { // match[2] should be 'T' or space timeFormat = (match[2] || ' ') + isoTimes[i][0]; break; } } if (timeFormat == null) { config._isValid = false; return; } } if (!allowTime && timeFormat != null) { config._isValid = false; return; } if (match[4]) { if (tzRegex.exec(match[4])) { tzFormat = 'Z'; } else { config._isValid = false; return; } } config._f = dateFormat + (timeFormat || '') + (tzFormat || ''); configFromStringAndFormat(config); } else { config._isValid = false; } } // date from iso format or fallback function configFromString(config) { var matched = aspNetJsonRegex.exec(config._i); if (matched !== null) { config._d = new Date(+matched[1]); return; } configFromISO(config); if (config._isValid === false) { delete config._isValid; utils_hooks__hooks.createFromInputFallback(config); } } utils_hooks__hooks.createFromInputFallback = deprecate( 'moment construction falls back to js Date. This is ' + 'discouraged and will be removed in upcoming major ' + 'release. Please refer to ' + 'http://momentjs.com/guides/#/warnings/js-date/ for more info.', function (config) { config._d = new Date(config._i + (config._useUTC ? ' UTC' : '')); } ); // Pick the first defined of two or three arguments. function defaults(a, b, c) { if (a != null) { return a; } if (b != null) { return b; } return c; } function currentDateArray(config) { // hooks is actually the exported moment object var nowValue = new Date(utils_hooks__hooks.now()); if (config._useUTC) { return [nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate()]; } return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()]; } // convert an array to a date. // the array should mirror the parameters below // note: all values past the year are optional and will default to the lowest possible value. // [year, month, day , hour, minute, second, millisecond] function configFromArray(config) { var i, date, input = [], currentDate, yearToUse; if (config._d) { return; } currentDate = currentDateArray(config); //compute day of the year from weeks and weekdays if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { dayOfYearFromWeekInfo(config); } //if the day of the year is set, figure out what it is if (config._dayOfYear) { yearToUse = defaults(config._a[YEAR], currentDate[YEAR]); if (config._dayOfYear > daysInYear(yearToUse)) { getParsingFlags(config)._overflowDayOfYear = true; } date = createUTCDate(yearToUse, 0, config._dayOfYear); config._a[MONTH] = date.getUTCMonth(); config._a[DATE] = date.getUTCDate(); } // Default to current date. // * if no year, month, day of month are given, default to today // * if day of month is given, default month and year // * if month is given, default only year // * if year is given, don't default anything for (i = 0; i < 3 && config._a[i] == null; ++i) { config._a[i] = input[i] = currentDate[i]; } // Zero out whatever was not defaulted, including time for (; i < 7; i++) { config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i]; } // Check for 24:00:00.000 if (config._a[HOUR] === 24 && config._a[MINUTE] === 0 && config._a[SECOND] === 0 && config._a[MILLISECOND] === 0) { config._nextDay = true; config._a[HOUR] = 0; } config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input); // Apply timezone offset from input. The actual utcOffset can be changed // with parseZone. if (config._tzm != null) { config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); } if (config._nextDay) { config._a[HOUR] = 24; } } function dayOfYearFromWeekInfo(config) { var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow; w = config._w; if (w.GG != null || w.W != null || w.E != null) { dow = 1; doy = 4; // TODO: We need to take the current isoWeekYear, but that depends on // how we interpret now (local, utc, fixed offset). So create // a now version of current config (take local/utc/offset flags, and // create now). weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(local__createLocal(), 1, 4).year); week = defaults(w.W, 1); weekday = defaults(w.E, 1); if (weekday < 1 || weekday > 7) { weekdayOverflow = true; } } else { dow = config._locale._week.dow; doy = config._locale._week.doy; weekYear = defaults(w.gg, config._a[YEAR], weekOfYear(local__createLocal(), dow, doy).year); week = defaults(w.w, 1); if (w.d != null) { // weekday -- low day numbers are considered next week weekday = w.d; if (weekday < 0 || weekday > 6) { weekdayOverflow = true; } } else if (w.e != null) { // local weekday -- counting starts from begining of week weekday = w.e + dow; if (w.e < 0 || w.e > 6) { weekdayOverflow = true; } } else { // default to begining of week weekday = dow; } } if (week < 1 || week > weeksInYear(weekYear, dow, doy)) { getParsingFlags(config)._overflowWeeks = true; } else if (weekdayOverflow != null) { getParsingFlags(config)._overflowWeekday = true; } else { temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy); config._a[YEAR] = temp.year; config._dayOfYear = temp.dayOfYear; } } // constant that refers to the ISO standard utils_hooks__hooks.ISO_8601 = function () { }; // date from string and format string function configFromStringAndFormat(config) { // TODO: Move this to another part of the creation flow to prevent circular deps if (config._f === utils_hooks__hooks.ISO_8601) { configFromISO(config); return; } config._a = []; getParsingFlags(config).empty = true; // This array is used to make a Date, either with `new Date` or `Date.UTC` var string = '' + config._i, i, parsedInput, tokens, token, skipped, stringLength = string.length, totalParsedInputLength = 0; tokens = expandFormat(config._f, config._locale).match(formattingTokens) || []; for (i = 0; i < tokens.length; i++) { token = tokens[i]; parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0]; // console.log('token', token, 'parsedInput', parsedInput, // 'regex', getParseRegexForToken(token, config)); if (parsedInput) { skipped = string.substr(0, string.indexOf(parsedInput)); if (skipped.length > 0) { getParsingFlags(config).unusedInput.push(skipped); } string = string.slice(string.indexOf(parsedInput) + parsedInput.length); totalParsedInputLength += parsedInput.length; } // don't parse if it's not a known token if (formatTokenFunctions[token]) { if (parsedInput) { getParsingFlags(config).empty = false; } else { getParsingFlags(config).unusedTokens.push(token); } addTimeToArrayFromToken(token, parsedInput, config); } else if (config._strict && !parsedInput) { getParsingFlags(config).unusedTokens.push(token); } } // add remaining unparsed input length to the string getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength; if (string.length > 0) { getParsingFlags(config).unusedInput.push(string); } // clear _12h flag if hour is <= 12 if (config._a[HOUR] <= 12 && getParsingFlags(config).bigHour === true && config._a[HOUR] > 0) { getParsingFlags(config).bigHour = undefined; } getParsingFlags(config).parsedDateParts = config._a.slice(0); getParsingFlags(config).meridiem = config._meridiem; // handle meridiem config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem); configFromArray(config); checkOverflow(config); } function meridiemFixWrap(locale, hour, meridiem) { var isPm; if (meridiem == null) { // nothing to do return hour; } if (locale.meridiemHour != null) { return locale.meridiemHour(hour, meridiem); } else if (locale.isPM != null) { // Fallback isPm = locale.isPM(meridiem); if (isPm && hour < 12) { hour += 12; } if (!isPm && hour === 12) { hour = 0; } return hour; } else { // this is not supposed to happen return hour; } } // date from string and array of format strings function configFromStringAndArray(config) { var tempConfig, bestMoment, scoreToBeat, i, currentScore; if (config._f.length === 0) { getParsingFlags(config).invalidFormat = true; config._d = new Date(NaN); return; } for (i = 0; i < config._f.length; i++) { currentScore = 0; tempConfig = copyConfig({}, config); if (config._useUTC != null) { tempConfig._useUTC = config._useUTC; } tempConfig._f = config._f[i]; configFromStringAndFormat(tempConfig); if (!valid__isValid(tempConfig)) { continue; } // if there is any input that was not parsed add a penalty for that format currentScore += getParsingFlags(tempConfig).charsLeftOver; //or tokens currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10; getParsingFlags(tempConfig).score = currentScore; if (scoreToBeat == null || currentScore < scoreToBeat) { scoreToBeat = currentScore; bestMoment = tempConfig; } } extend(config, bestMoment || tempConfig); } function configFromObject(config) { if (config._d) { return; } var i = normalizeObjectUnits(config._i); config._a = map([i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond], function (obj) { return obj && parseInt(obj, 10); }); configFromArray(config); } function createFromConfig(config) { var res = new Moment(checkOverflow(prepareConfig(config))); if (res._nextDay) { // Adding is smart enough around DST res.add(1, 'd'); res._nextDay = undefined; } return res; } function prepareConfig(config) { var input = config._i, format = config._f; config._locale = config._locale || locale_locales__getLocale(config._l); if (input === null || (format === undefined && input === '')) { return valid__createInvalid({ nullInput: true }); } if (typeof input === 'string') { config._i = input = config._locale.preparse(input); } if (isMoment(input)) { return new Moment(checkOverflow(input)); } else if (isArray(format)) { configFromStringAndArray(config); } else if (isDate(input)) { config._d = input; } else if (format) { configFromStringAndFormat(config); } else { configFromInput(config); } if (!valid__isValid(config)) { config._d = null; } return config; } function configFromInput(config) { var input = config._i; if (input === undefined) { config._d = new Date(utils_hooks__hooks.now()); } else if (isDate(input)) { config._d = new Date(input.valueOf()); } else if (typeof input === 'string') { configFromString(config); } else if (isArray(input)) { config._a = map(input.slice(0), function (obj) { return parseInt(obj, 10); }); configFromArray(config); } else if (typeof (input) === 'object') { configFromObject(config); } else if (typeof (input) === 'number') { // from milliseconds config._d = new Date(input); } else { utils_hooks__hooks.createFromInputFallback(config); } } function createLocalOrUTC(input, format, locale, strict, isUTC) { var c = {}; if (typeof (locale) === 'boolean') { strict = locale; locale = undefined; } if ((isObject(input) && isObjectEmpty(input)) || (isArray(input) && input.length === 0)) { input = undefined; } // object construction must be done this way. // https://github.com/moment/moment/issues/1423 c._isAMomentObject = true; c._useUTC = c._isUTC = isUTC; c._l = locale; c._i = input; c._f = format; c._strict = strict; return createFromConfig(c); } function local__createLocal(input, format, locale, strict) { return createLocalOrUTC(input, format, locale, strict, false); } var prototypeMin = deprecate( 'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/', function () { var other = local__createLocal.apply(null, arguments); if (this.isValid() && other.isValid()) { return other < this ? this : other; } else { return valid__createInvalid(); } } ); var prototypeMax = deprecate( 'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/', function () { var other = local__createLocal.apply(null, arguments); if (this.isValid() && other.isValid()) { return other > this ? this : other; } else { return valid__createInvalid(); } } ); // Pick a moment m from moments so that m[fn](other) is true for all // other. This relies on the function fn to be transitive. // // moments should either be an array of moment objects or an array, whose // first element is an array of moment objects. function pickBy(fn, moments) { var res, i; if (moments.length === 1 && isArray(moments[0])) { moments = moments[0]; } if (!moments.length) { return local__createLocal(); } res = moments[0]; for (i = 1; i < moments.length; ++i) { if (!moments[i].isValid() || moments[i][fn](res)) { res = moments[i]; } } return res; } // TODO: Use [].sort instead? function min() { var args = [].slice.call(arguments, 0); return pickBy('isBefore', args); } function max() { var args = [].slice.call(arguments, 0); return pickBy('isAfter', args); } var now = function () { return Date.now ? Date.now() : +(new Date()); }; function Duration(duration) { var normalizedInput = normalizeObjectUnits(duration), years = normalizedInput.year || 0, quarters = normalizedInput.quarter || 0, months = normalizedInput.month || 0, weeks = normalizedInput.week || 0, days = normalizedInput.day || 0, hours = normalizedInput.hour || 0, minutes = normalizedInput.minute || 0, seconds = normalizedInput.second || 0, milliseconds = normalizedInput.millisecond || 0; // representation for dateAddRemove this._milliseconds = +milliseconds + seconds * 1e3 + // 1000 minutes * 6e4 + // 1000 * 60 hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978 // Because of dateAddRemove treats 24 hours as different from a // day when working around DST, we need to store them separately this._days = +days + weeks * 7; // It is impossible translate months into days without knowing // which months you are are talking about, so we have to store // it separately. this._months = +months + quarters * 3 + years * 12; this._data = {}; this._locale = locale_locales__getLocale(); this._bubble(); } function isDuration(obj) { return obj instanceof Duration; } // FORMATTING function offset(token, separator) { addFormatToken(token, 0, 0, function () { var offset = this.utcOffset(); var sign = '+'; if (offset < 0) { offset = -offset; sign = '-'; } return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2); }); } offset('Z', ':'); offset('ZZ', ''); // PARSING addRegexToken('Z', matchShortOffset); addRegexToken('ZZ', matchShortOffset); addParseToken(['Z', 'ZZ'], function (input, array, config) { config._useUTC = true; config._tzm = offsetFromString(matchShortOffset, input); }); // HELPERS // timezone chunker // '+10:00' > ['10', '00'] // '-1530' > ['-15', '30'] var chunkOffset = /([\+\-]|\d\d)/gi; function offsetFromString(matcher, string) { var matches = ((string || '').match(matcher) || []); var chunk = matches[matches.length - 1] || []; var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0]; var minutes = +(parts[1] * 60) + toInt(parts[2]); return parts[0] === '+' ? minutes : -minutes; } // Return a moment from input, that is local/utc/zone equivalent to model. function cloneWithOffset(input, model) { var res, diff; if (model._isUTC) { res = model.clone(); diff = (isMoment(input) || isDate(input) ? input.valueOf() : local__createLocal(input).valueOf()) - res.valueOf(); // Use low-level api, because this fn is low-level api. res._d.setTime(res._d.valueOf() + diff); utils_hooks__hooks.updateOffset(res, false); return res; } else { return local__createLocal(input).local(); } } function getDateOffset(m) { // On Firefox.24 Date#getTimezoneOffset returns a floating point. // https://github.com/moment/moment/pull/1871 return -Math.round(m._d.getTimezoneOffset() / 15) * 15; } // HOOKS // This function will be called whenever a moment is mutated. // It is intended to keep the offset in sync with the timezone. utils_hooks__hooks.updateOffset = function () { }; // MOMENTS // keepLocalTime = true means only change the timezone, without // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]--> // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset // +0200, so we adjust the time as needed, to be valid. // // Keeping the time actually adds/subtracts (one hour) // from the actual represented time. That is why we call updateOffset // a second time. In case it wants us to change the offset again // _changeInProgress == true case, then we have to adjust, because // there is no such time in the given timezone. function getSetOffset(input, keepLocalTime) { var offset = this._offset || 0, localAdjust; if (!this.isValid()) { return input != null ? this : NaN; } if (input != null) { if (typeof input === 'string') { input = offsetFromString(matchShortOffset, input); } else if (Math.abs(input) < 16) { input = input * 60; } if (!this._isUTC && keepLocalTime) { localAdjust = getDateOffset(this); } this._offset = input; this._isUTC = true; if (localAdjust != null) { this.add(localAdjust, 'm'); } if (offset !== input) { if (!keepLocalTime || this._changeInProgress) { add_subtract__addSubtract(this, create__createDuration(input - offset, 'm'), 1, false); } else if (!this._changeInProgress) { this._changeInProgress = true; utils_hooks__hooks.updateOffset(this, true); this._changeInProgress = null; } } return this; } else { return this._isUTC ? offset : getDateOffset(this); } } function getSetZone(input, keepLocalTime) { if (input != null) { if (typeof input !== 'string') { input = -input; } this.utcOffset(input, keepLocalTime); return this; } else { return -this.utcOffset(); } } function setOffsetToUTC(keepLocalTime) { return this.utcOffset(0, keepLocalTime); } function setOffsetToLocal(keepLocalTime) { if (this._isUTC) { this.utcOffset(0, keepLocalTime); this._isUTC = false; if (keepLocalTime) { this.subtract(getDateOffset(this), 'm'); } } return this; } function setOffsetToParsedOffset() { if (this._tzm) { this.utcOffset(this._tzm); } else if (typeof this._i === 'string') { this.utcOffset(offsetFromString(matchOffset, this._i)); } return this; } function hasAlignedHourOffset(input) { if (!this.isValid()) { return false; } input = input ? local__createLocal(input).utcOffset() : 0; return (this.utcOffset() - input) % 60 === 0; } function isDaylightSavingTime() { return ( this.utcOffset() > this.clone().month(0).utcOffset() || this.utcOffset() > this.clone().month(5).utcOffset() ); } function isDaylightSavingTimeShifted() { if (!isUndefined(this._isDSTShifted)) { return this._isDSTShifted; } var c = {}; copyConfig(c, this); c = prepareConfig(c); if (c._a) { var other = c._isUTC ? create_utc__createUTC(c._a) : local__createLocal(c._a); this._isDSTShifted = this.isValid() && compareArrays(c._a, other.toArray()) > 0; } else { this._isDSTShifted = false; } return this._isDSTShifted; } function isLocal() { return this.isValid() ? !this._isUTC : false; } function isUtcOffset() { return this.isValid() ? this._isUTC : false; } function isUtc() { return this.isValid() ? this._isUTC && this._offset === 0 : false; } // ASP.NET json date format regex var aspNetRegex = /^(\-)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?\d*)?$/; // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere // and further modified to allow for strings containing both week and day var isoRegex = /^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/; function create__createDuration(input, key) { var duration = input, // matching against regexp is expensive, do it on demand match = null, sign, ret, diffRes; if (isDuration(input)) { duration = { ms: input._milliseconds, d: input._days, M: input._months }; } else if (typeof input === 'number') { duration = {}; if (key) { duration[key] = input; } else { duration.milliseconds = input; } } else if (!!(match = aspNetRegex.exec(input))) { sign = (match[1] === '-') ? -1 : 1; duration = { y: 0, d: toInt(match[DATE]) * sign, h: toInt(match[HOUR]) * sign, m: toInt(match[MINUTE]) * sign, s: toInt(match[SECOND]) * sign, ms: toInt(match[MILLISECOND]) * sign }; } else if (!!(match = isoRegex.exec(input))) { sign = (match[1] === '-') ? -1 : 1; duration = { y: parseIso(match[2], sign), M: parseIso(match[3], sign), w: parseIso(match[4], sign), d: parseIso(match[5], sign), h: parseIso(match[6], sign), m: parseIso(match[7], sign), s: parseIso(match[8], sign) }; } else if (duration == null) {// checks for null or undefined duration = {}; } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) { diffRes = momentsDifference(local__createLocal(duration.from), local__createLocal(duration.to)); duration = {}; duration.ms = diffRes.milliseconds; duration.M = diffRes.months; } ret = new Duration(duration); if (isDuration(input) && hasOwnProp(input, '_locale')) { ret._locale = input._locale; } return ret; } create__createDuration.fn = Duration.prototype; function parseIso(inp, sign) { // We'd normally use ~~inp for this, but unfortunately it also // converts floats to ints. // inp may be undefined, so careful calling replace on it. var res = inp && parseFloat(inp.replace(',', '.')); // apply sign while we're at it return (isNaN(res) ? 0 : res) * sign; } function positiveMomentsDifference(base, other) { var res = { milliseconds: 0, months: 0 }; res.months = other.month() - base.month() + (other.year() - base.year()) * 12; if (base.clone().add(res.months, 'M').isAfter(other)) { --res.months; } res.milliseconds = +other - +(base.clone().add(res.months, 'M')); return res; } function momentsDifference(base, other) { var res; if (!(base.isValid() && other.isValid())) { return { milliseconds: 0, months: 0 }; } other = cloneWithOffset(other, base); if (base.isBefore(other)) { res = positiveMomentsDifference(base, other); } else { res = positiveMomentsDifference(other, base); res.milliseconds = -res.milliseconds; res.months = -res.months; } return res; } function absRound(number) { if (number < 0) { return Math.round(-1 * number) * -1; } else { return Math.round(number); } } // TODO: remove 'name' arg after deprecation is removed function createAdder(direction, name) { return function (val, period) { var dur, tmp; //invert the arguments, but complain about it if (period !== null && !isNaN(+period)) { deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period). ' + 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.'); tmp = val; val = period; period = tmp; } val = typeof val === 'string' ? +val : val; dur = create__createDuration(val, period); add_subtract__addSubtract(this, dur, direction); return this; }; } function add_subtract__addSubtract(mom, duration, isAdding, updateOffset) { var milliseconds = duration._milliseconds, days = absRound(duration._days), months = absRound(duration._months); if (!mom.isValid()) { // No op return; } updateOffset = updateOffset == null ? true : updateOffset; if (milliseconds) { mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding); } if (days) { get_set__set(mom, 'Date', get_set__get(mom, 'Date') + days * isAdding); } if (months) { setMonth(mom, get_set__get(mom, 'Month') + months * isAdding); } if (updateOffset) { utils_hooks__hooks.updateOffset(mom, days || months); } } var add_subtract__add = createAdder(1, 'add'); var add_subtract__subtract = createAdder(-1, 'subtract'); function getCalendarFormat(myMoment, now) { var diff = myMoment.diff(now, 'days', true); return diff < -6 ? 'sameElse' : diff < -1 ? 'lastWeek' : diff < 0 ? 'lastDay' : diff < 1 ? 'sameDay' : diff < 2 ? 'nextDay' : diff < 7 ? 'nextWeek' : 'sameElse'; } function moment_calendar__calendar(time, formats) { // We want to compare the start of today, vs this. // Getting start-of-today depends on whether we're local/utc/offset or not. var now = time || local__createLocal(), sod = cloneWithOffset(now, this).startOf('day'), format = utils_hooks__hooks.calendarFormat(this, sod) || 'sameElse'; var output = formats && (isFunction(formats[format]) ? formats[format].call(this, now) : formats[format]); return this.format(output || this.localeData().calendar(format, this, local__createLocal(now))); } function clone() { return new Moment(this); } function isAfter(input, units) { var localInput = isMoment(input) ? input : local__createLocal(input); if (!(this.isValid() && localInput.isValid())) { return false; } units = normalizeUnits(!isUndefined(units) ? units : 'millisecond'); if (units === 'millisecond') { return this.valueOf() > localInput.valueOf(); } else { return localInput.valueOf() < this.clone().startOf(units).valueOf(); } } function isBefore(input, units) { var localInput = isMoment(input) ? input : local__createLocal(input); if (!(this.isValid() && localInput.isValid())) { return false; } units = normalizeUnits(!isUndefined(units) ? units : 'millisecond'); if (units === 'millisecond') { return this.valueOf() < localInput.valueOf(); } else { return this.clone().endOf(units).valueOf() < localInput.valueOf(); } } function isBetween(from, to, units, inclusivity) { inclusivity = inclusivity || '()'; return (inclusivity[0] === '(' ? this.isAfter(from, units) : !this.isBefore(from, units)) && (inclusivity[1] === ')' ? this.isBefore(to, units) : !this.isAfter(to, units)); } function isSame(input, units) { var localInput = isMoment(input) ? input : local__createLocal(input), inputMs; if (!(this.isValid() && localInput.isValid())) { return false; } units = normalizeUnits(units || 'millisecond'); if (units === 'millisecond') { return this.valueOf() === localInput.valueOf(); } else { inputMs = localInput.valueOf(); return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf(); } } function isSameOrAfter(input, units) { return this.isSame(input, units) || this.isAfter(input, units); } function isSameOrBefore(input, units) { return this.isSame(input, units) || this.isBefore(input, units); } function diff(input, units, asFloat) { var that, zoneDelta, delta, output; if (!this.isValid()) { return NaN; } that = cloneWithOffset(input, this); if (!that.isValid()) { return NaN; } zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4; units = normalizeUnits(units); if (units === 'year' || units === 'month' || units === 'quarter') { output = monthDiff(this, that); if (units === 'quarter') { output = output / 3; } else if (units === 'year') { output = output / 12; } } else { delta = this - that; output = units === 'second' ? delta / 1e3 : // 1000 units === 'minute' ? delta / 6e4 : // 1000 * 60 units === 'hour' ? delta / 36e5 : // 1000 * 60 * 60 units === 'day' ? (delta - zoneDelta) / 864e5 : // 1000 * 60 * 60 * 24, negate dst units === 'week' ? (delta - zoneDelta) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst delta; } return asFloat ? output : absFloor(output); } function monthDiff(a, b) { // difference in months var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()), // b is in (anchor - 1 month, anchor + 1 month) anchor = a.clone().add(wholeMonthDiff, 'months'), anchor2, adjust; if (b - anchor < 0) { anchor2 = a.clone().add(wholeMonthDiff - 1, 'months'); // linear across the month adjust = (b - anchor) / (anchor - anchor2); } else { anchor2 = a.clone().add(wholeMonthDiff + 1, 'months'); // linear across the month adjust = (b - anchor) / (anchor2 - anchor); } //check for negative zero, return zero if negative zero return -(wholeMonthDiff + adjust) || 0; } utils_hooks__hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ'; utils_hooks__hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]'; function toString() { return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ'); } function moment_format__toISOString() { var m = this.clone().utc(); if (0 < m.year() && m.year() <= 9999) { if (isFunction(Date.prototype.toISOString)) { // native implementation is ~50x faster, use it when we can return this.toDate().toISOString(); } else { return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); } } else { return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); } } function moment_format__format(inputString) { if (!inputString) { inputString = this.isUtc() ? utils_hooks__hooks.defaultFormatUtc : utils_hooks__hooks.defaultFormat; } var output = formatMoment(this, inputString); return this.localeData().postformat(output); } function from(time, withoutSuffix) { if (this.isValid() && ((isMoment(time) && time.isValid()) || local__createLocal(time).isValid())) { return create__createDuration({ to: this, from: time }).locale(this.locale()).humanize(!withoutSuffix); } else { return this.localeData().invalidDate(); } } function fromNow(withoutSuffix) { return this.from(local__createLocal(), withoutSuffix); } function to(time, withoutSuffix) { if (this.isValid() && ((isMoment(time) && time.isValid()) || local__createLocal(time).isValid())) { return create__createDuration({ from: this, to: time }).locale(this.locale()).humanize(!withoutSuffix); } else { return this.localeData().invalidDate(); } } function toNow(withoutSuffix) { return this.to(local__createLocal(), withoutSuffix); } // If passed a locale key, it will set the locale for this // instance. Otherwise, it will return the locale configuration // variables for this instance. function locale(key) { var newLocaleData; if (key === undefined) { return this._locale._abbr; } else { newLocaleData = locale_locales__getLocale(key); if (newLocaleData != null) { this._locale = newLocaleData; } return this; } } var lang = deprecate( 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.', function (key) { if (key === undefined) { return this.localeData(); } else { return this.locale(key); } } ); function localeData() { return this._locale; } function startOf(units) { units = normalizeUnits(units); // the following switch intentionally omits break keywords // to utilize falling through the cases. switch (units) { case 'year': this.month(0); /* falls through */ case 'quarter': case 'month': this.date(1); /* falls through */ case 'week': case 'isoWeek': case 'day': case 'date': this.hours(0); /* falls through */ case 'hour': this.minutes(0); /* falls through */ case 'minute': this.seconds(0); /* falls through */ case 'second': this.milliseconds(0); } // weeks are a special case if (units === 'week') { this.weekday(0); } if (units === 'isoWeek') { this.isoWeekday(1); } // quarters are also special if (units === 'quarter') { this.month(Math.floor(this.month() / 3) * 3); } return this; } function endOf(units) { units = normalizeUnits(units); if (units === undefined || units === 'millisecond') { return this; } // 'date' is an alias for 'day', so it should be considered as such. if (units === 'date') { units = 'day'; } return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms'); } function to_type__valueOf() { return this._d.valueOf() - ((this._offset || 0) * 60000); } function unix() { return Math.floor(this.valueOf() / 1000); } function toDate() { return new Date(this.valueOf()); } function toArray() { var m = this; return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()]; } function toObject() { var m = this; return { years: m.year(), months: m.month(), date: m.date(), hours: m.hours(), minutes: m.minutes(), seconds: m.seconds(), milliseconds: m.milliseconds() }; } function toJSON() { // new Date(NaN).toJSON() === null return this.isValid() ? this.toISOString() : null; } function moment_valid__isValid() { return valid__isValid(this); } function parsingFlags() { return extend({}, getParsingFlags(this)); } function invalidAt() { return getParsingFlags(this).overflow; } function creationData() { return { input: this._i, format: this._f, locale: this._locale, isUTC: this._isUTC, strict: this._strict }; } // FORMATTING addFormatToken(0, ['gg', 2], 0, function () { return this.weekYear() % 100; }); addFormatToken(0, ['GG', 2], 0, function () { return this.isoWeekYear() % 100; }); function addWeekYearFormatToken(token, getter) { addFormatToken(0, [token, token.length], 0, getter); } addWeekYearFormatToken('gggg', 'weekYear'); addWeekYearFormatToken('ggggg', 'weekYear'); addWeekYearFormatToken('GGGG', 'isoWeekYear'); addWeekYearFormatToken('GGGGG', 'isoWeekYear'); // ALIASES addUnitAlias('weekYear', 'gg'); addUnitAlias('isoWeekYear', 'GG'); // PRIORITY addUnitPriority('weekYear', 1); addUnitPriority('isoWeekYear', 1); // PARSING addRegexToken('G', matchSigned); addRegexToken('g', matchSigned); addRegexToken('GG', match1to2, match2); addRegexToken('gg', match1to2, match2); addRegexToken('GGGG', match1to4, match4); addRegexToken('gggg', match1to4, match4); addRegexToken('GGGGG', match1to6, match6); addRegexToken('ggggg', match1to6, match6); addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) { week[token.substr(0, 2)] = toInt(input); }); addWeekParseToken(['gg', 'GG'], function (input, week, config, token) { week[token] = utils_hooks__hooks.parseTwoDigitYear(input); }); // MOMENTS function getSetWeekYear(input) { return getSetWeekYearHelper.call(this, input, this.week(), this.weekday(), this.localeData()._week.dow, this.localeData()._week.doy); } function getSetISOWeekYear(input) { return getSetWeekYearHelper.call(this, input, this.isoWeek(), this.isoWeekday(), 1, 4); } function getISOWeeksInYear() { return weeksInYear(this.year(), 1, 4); } function getWeeksInYear() { var weekInfo = this.localeData()._week; return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy); } function getSetWeekYearHelper(input, week, weekday, dow, doy) { var weeksTarget; if (input == null) { return weekOfYear(this, dow, doy).year; } else { weeksTarget = weeksInYear(input, dow, doy); if (week > weeksTarget) { week = weeksTarget; } return setWeekAll.call(this, input, week, weekday, dow, doy); } } function setWeekAll(weekYear, week, weekday, dow, doy) { var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy), date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear); this.year(date.getUTCFullYear()); this.month(date.getUTCMonth()); this.date(date.getUTCDate()); return this; } // FORMATTING addFormatToken('Q', 0, 'Qo', 'quarter'); // ALIASES addUnitAlias('quarter', 'Q'); // PRIORITY addUnitPriority('quarter', 7); // PARSING addRegexToken('Q', match1); addParseToken('Q', function (input, array) { array[MONTH] = (toInt(input) - 1) * 3; }); // MOMENTS function getSetQuarter(input) { return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3); } // FORMATTING addFormatToken('D', ['DD', 2], 'Do', 'date'); // ALIASES addUnitAlias('date', 'D'); // PRIOROITY addUnitPriority('date', 9); // PARSING addRegexToken('D', match1to2); addRegexToken('DD', match1to2, match2); addRegexToken('Do', function (isStrict, locale) { return isStrict ? locale._ordinalParse : locale._ordinalParseLenient; }); addParseToken(['D', 'DD'], DATE); addParseToken('Do', function (input, array) { array[DATE] = toInt(input.match(match1to2)[0], 10); }); // MOMENTS var getSetDayOfMonth = makeGetSet('Date', true); // FORMATTING addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear'); // ALIASES addUnitAlias('dayOfYear', 'DDD'); // PRIORITY addUnitPriority('dayOfYear', 4); // PARSING addRegexToken('DDD', match1to3); addRegexToken('DDDD', match3); addParseToken(['DDD', 'DDDD'], function (input, array, config) { config._dayOfYear = toInt(input); }); // HELPERS // MOMENTS function getSetDayOfYear(input) { var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1; return input == null ? dayOfYear : this.add((input - dayOfYear), 'd'); } // FORMATTING addFormatToken('m', ['mm', 2], 0, 'minute'); // ALIASES addUnitAlias('minute', 'm'); // PRIORITY addUnitPriority('minute', 14); // PARSING addRegexToken('m', match1to2); addRegexToken('mm', match1to2, match2); addParseToken(['m', 'mm'], MINUTE); // MOMENTS var getSetMinute = makeGetSet('Minutes', false); // FORMATTING addFormatToken('s', ['ss', 2], 0, 'second'); // ALIASES addUnitAlias('second', 's'); // PRIORITY addUnitPriority('second', 15); // PARSING addRegexToken('s', match1to2); addRegexToken('ss', match1to2, match2); addParseToken(['s', 'ss'], SECOND); // MOMENTS var getSetSecond = makeGetSet('Seconds', false); // FORMATTING addFormatToken('S', 0, 0, function () { return ~~(this.millisecond() / 100); }); addFormatToken(0, ['SS', 2], 0, function () { return ~~(this.millisecond() / 10); }); addFormatToken(0, ['SSS', 3], 0, 'millisecond'); addFormatToken(0, ['SSSS', 4], 0, function () { return this.millisecond() * 10; }); addFormatToken(0, ['SSSSS', 5], 0, function () { return this.millisecond() * 100; }); addFormatToken(0, ['SSSSSS', 6], 0, function () { return this.millisecond() * 1000; }); addFormatToken(0, ['SSSSSSS', 7], 0, function () { return this.millisecond() * 10000; }); addFormatToken(0, ['SSSSSSSS', 8], 0, function () { return this.millisecond() * 100000; }); addFormatToken(0, ['SSSSSSSSS', 9], 0, function () { return this.millisecond() * 1000000; }); // ALIASES addUnitAlias('millisecond', 'ms'); // PRIORITY addUnitPriority('millisecond', 16); // PARSING addRegexToken('S', match1to3, match1); addRegexToken('SS', match1to3, match2); addRegexToken('SSS', match1to3, match3); var token; for (token = 'SSSS'; token.length <= 9; token += 'S') { addRegexToken(token, matchUnsigned); } function parseMs(input, array) { array[MILLISECOND] = toInt(('0.' + input) * 1000); } for (token = 'S'; token.length <= 9; token += 'S') { addParseToken(token, parseMs); } // MOMENTS var getSetMillisecond = makeGetSet('Milliseconds', false); // FORMATTING addFormatToken('z', 0, 0, 'zoneAbbr'); addFormatToken('zz', 0, 0, 'zoneName'); // MOMENTS function getZoneAbbr() { return this._isUTC ? 'UTC' : ''; } function getZoneName() { return this._isUTC ? 'Coordinated Universal Time' : ''; } var momentPrototype__proto = Moment.prototype; momentPrototype__proto.add = add_subtract__add; momentPrototype__proto.calendar = moment_calendar__calendar; momentPrototype__proto.clone = clone; momentPrototype__proto.diff = diff; momentPrototype__proto.endOf = endOf; momentPrototype__proto.format = moment_format__format; momentPrototype__proto.from = from; momentPrototype__proto.fromNow = fromNow; momentPrototype__proto.to = to; momentPrototype__proto.toNow = toNow; momentPrototype__proto.get = stringGet; momentPrototype__proto.invalidAt = invalidAt; momentPrototype__proto.isAfter = isAfter; momentPrototype__proto.isBefore = isBefore; momentPrototype__proto.isBetween = isBetween; momentPrototype__proto.isSame = isSame; momentPrototype__proto.isSameOrAfter = isSameOrAfter; momentPrototype__proto.isSameOrBefore = isSameOrBefore; momentPrototype__proto.isValid = moment_valid__isValid; momentPrototype__proto.lang = lang; momentPrototype__proto.locale = locale; momentPrototype__proto.localeData = localeData; momentPrototype__proto.max = prototypeMax; momentPrototype__proto.min = prototypeMin; momentPrototype__proto.parsingFlags = parsingFlags; momentPrototype__proto.set = stringSet; momentPrototype__proto.startOf = startOf; momentPrototype__proto.subtract = add_subtract__subtract; momentPrototype__proto.toArray = toArray; momentPrototype__proto.toObject = toObject; momentPrototype__proto.toDate = toDate; momentPrototype__proto.toISOString = moment_format__toISOString; momentPrototype__proto.toJSON = toJSON; momentPrototype__proto.toString = toString; momentPrototype__proto.unix = unix; momentPrototype__proto.valueOf = to_type__valueOf; momentPrototype__proto.creationData = creationData; // Year momentPrototype__proto.year = getSetYear; momentPrototype__proto.isLeapYear = getIsLeapYear; // Week Year momentPrototype__proto.weekYear = getSetWeekYear; momentPrototype__proto.isoWeekYear = getSetISOWeekYear; // Quarter momentPrototype__proto.quarter = momentPrototype__proto.quarters = getSetQuarter; // Month momentPrototype__proto.month = getSetMonth; momentPrototype__proto.daysInMonth = getDaysInMonth; // Week momentPrototype__proto.week = momentPrototype__proto.weeks = getSetWeek; momentPrototype__proto.isoWeek = momentPrototype__proto.isoWeeks = getSetISOWeek; momentPrototype__proto.weeksInYear = getWeeksInYear; momentPrototype__proto.isoWeeksInYear = getISOWeeksInYear; // Day momentPrototype__proto.date = getSetDayOfMonth; momentPrototype__proto.day = momentPrototype__proto.days = getSetDayOfWeek; momentPrototype__proto.weekday = getSetLocaleDayOfWeek; momentPrototype__proto.isoWeekday = getSetISODayOfWeek; momentPrototype__proto.dayOfYear = getSetDayOfYear; // Hour momentPrototype__proto.hour = momentPrototype__proto.hours = getSetHour; // Minute momentPrototype__proto.minute = momentPrototype__proto.minutes = getSetMinute; // Second momentPrototype__proto.second = momentPrototype__proto.seconds = getSetSecond; // Millisecond momentPrototype__proto.millisecond = momentPrototype__proto.milliseconds = getSetMillisecond; // Offset momentPrototype__proto.utcOffset = getSetOffset; momentPrototype__proto.utc = setOffsetToUTC; momentPrototype__proto.local = setOffsetToLocal; momentPrototype__proto.parseZone = setOffsetToParsedOffset; momentPrototype__proto.hasAlignedHourOffset = hasAlignedHourOffset; momentPrototype__proto.isDST = isDaylightSavingTime; momentPrototype__proto.isLocal = isLocal; momentPrototype__proto.isUtcOffset = isUtcOffset; momentPrototype__proto.isUtc = isUtc; momentPrototype__proto.isUTC = isUtc; // Timezone momentPrototype__proto.zoneAbbr = getZoneAbbr; momentPrototype__proto.zoneName = getZoneName; // Deprecations momentPrototype__proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth); momentPrototype__proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth); momentPrototype__proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear); momentPrototype__proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', getSetZone); momentPrototype__proto.isDSTShifted = deprecate('isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', isDaylightSavingTimeShifted); var momentPrototype = momentPrototype__proto; function moment_moment__createUnix(input) { return local__createLocal(input * 1000); } function moment_moment__createInZone() { return local__createLocal.apply(null, arguments).parseZone(); } function preParsePostFormat(string) { return string; } var prototype__proto = Locale.prototype; prototype__proto.calendar = locale_calendar__calendar; prototype__proto.longDateFormat = longDateFormat; prototype__proto.invalidDate = invalidDate; prototype__proto.ordinal = ordinal; prototype__proto.preparse = preParsePostFormat; prototype__proto.postformat = preParsePostFormat; prototype__proto.relativeTime = relative__relativeTime; prototype__proto.pastFuture = pastFuture; prototype__proto.set = locale_set__set; // Month prototype__proto.months = localeMonths; prototype__proto.monthsShort = localeMonthsShort; prototype__proto.monthsParse = localeMonthsParse; prototype__proto.monthsRegex = monthsRegex; prototype__proto.monthsShortRegex = monthsShortRegex; // Week prototype__proto.week = localeWeek; prototype__proto.firstDayOfYear = localeFirstDayOfYear; prototype__proto.firstDayOfWeek = localeFirstDayOfWeek; // Day of Week prototype__proto.weekdays = localeWeekdays; prototype__proto.weekdaysMin = localeWeekdaysMin; prototype__proto.weekdaysShort = localeWeekdaysShort; prototype__proto.weekdaysParse = localeWeekdaysParse; prototype__proto.weekdaysRegex = weekdaysRegex; prototype__proto.weekdaysShortRegex = weekdaysShortRegex; prototype__proto.weekdaysMinRegex = weekdaysMinRegex; // Hours prototype__proto.isPM = localeIsPM; prototype__proto.meridiem = localeMeridiem; function lists__get(format, index, field, setter) { var locale = locale_locales__getLocale(); var utc = create_utc__createUTC().set(setter, index); return locale[field](utc, format); } function listMonthsImpl(format, index, field) { if (typeof format === 'number') { index = format; format = undefined; } format = format || ''; if (index != null) { return lists__get(format, index, field, 'month'); } var i; var out = []; for (i = 0; i < 12; i++) { out[i] = lists__get(format, i, field, 'month'); } return out; } // () // (5) // (fmt, 5) // (fmt) // (true) // (true, 5) // (true, fmt, 5) // (true, fmt) function listWeekdaysImpl(localeSorted, format, index, field) { if (typeof localeSorted === 'boolean') { if (typeof format === 'number') { index = format; format = undefined; } format = format || ''; } else { format = localeSorted; index = format; localeSorted = false; if (typeof format === 'number') { index = format; format = undefined; } format = format || ''; } var locale = locale_locales__getLocale(), shift = localeSorted ? locale._week.dow : 0; if (index != null) { return lists__get(format, (index + shift) % 7, field, 'day'); } var i; var out = []; for (i = 0; i < 7; i++) { out[i] = lists__get(format, (i + shift) % 7, field, 'day'); } return out; } function lists__listMonths(format, index) { return listMonthsImpl(format, index, 'months'); } function lists__listMonthsShort(format, index) { return listMonthsImpl(format, index, 'monthsShort'); } function lists__listWeekdays(localeSorted, format, index) { return listWeekdaysImpl(localeSorted, format, index, 'weekdays'); } function lists__listWeekdaysShort(localeSorted, format, index) { return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort'); } function lists__listWeekdaysMin(localeSorted, format, index) { return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin'); } locale_locales__getSetGlobalLocale('en', { ordinalParse: /\d{1,2}(th|st|nd|rd)/, ordinal: function (number) { var b = number % 10, output = (toInt(number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; } }); // Side effect imports utils_hooks__hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', locale_locales__getSetGlobalLocale); utils_hooks__hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', locale_locales__getLocale); var mathAbs = Math.abs; function duration_abs__abs() { var data = this._data; this._milliseconds = mathAbs(this._milliseconds); this._days = mathAbs(this._days); this._months = mathAbs(this._months); data.milliseconds = mathAbs(data.milliseconds); data.seconds = mathAbs(data.seconds); data.minutes = mathAbs(data.minutes); data.hours = mathAbs(data.hours); data.months = mathAbs(data.months); data.years = mathAbs(data.years); return this; } function duration_add_subtract__addSubtract(duration, input, value, direction) { var other = create__createDuration(input, value); duration._milliseconds += direction * other._milliseconds; duration._days += direction * other._days; duration._months += direction * other._months; return duration._bubble(); } // supports only 2.0-style add(1, 's') or add(duration) function duration_add_subtract__add(input, value) { return duration_add_subtract__addSubtract(this, input, value, 1); } // supports only 2.0-style subtract(1, 's') or subtract(duration) function duration_add_subtract__subtract(input, value) { return duration_add_subtract__addSubtract(this, input, value, -1); } function absCeil(number) { if (number < 0) { return Math.floor(number); } else { return Math.ceil(number); } } function bubble() { var milliseconds = this._milliseconds; var days = this._days; var months = this._months; var data = this._data; var seconds, minutes, hours, years, monthsFromDays; // if we have a mix of positive and negative values, bubble down first // check: https://github.com/moment/moment/issues/2166 if (!((milliseconds >= 0 && days >= 0 && months >= 0) || (milliseconds <= 0 && days <= 0 && months <= 0))) { milliseconds += absCeil(monthsToDays(months) + days) * 864e5; days = 0; months = 0; } // The following code bubbles up values, see the tests for // examples of what that means. data.milliseconds = milliseconds % 1000; seconds = absFloor(milliseconds / 1000); data.seconds = seconds % 60; minutes = absFloor(seconds / 60); data.minutes = minutes % 60; hours = absFloor(minutes / 60); data.hours = hours % 24; days += absFloor(hours / 24); // convert days to months monthsFromDays = absFloor(daysToMonths(days)); months += monthsFromDays; days -= absCeil(monthsToDays(monthsFromDays)); // 12 months -> 1 year years = absFloor(months / 12); months %= 12; data.days = days; data.months = months; data.years = years; return this; } function daysToMonths(days) { // 400 years have 146097 days (taking into account leap year rules) // 400 years have 12 months === 4800 return days * 4800 / 146097; } function monthsToDays(months) { // the reverse of daysToMonths return months * 146097 / 4800; } function as(units) { var days; var months; var milliseconds = this._milliseconds; units = normalizeUnits(units); if (units === 'month' || units === 'year') { days = this._days + milliseconds / 864e5; months = this._months + daysToMonths(days); return units === 'month' ? months : months / 12; } else { // handle milliseconds separately because of floating point math errors (issue #1867) days = this._days + Math.round(monthsToDays(this._months)); switch (units) { case 'week': return days / 7 + milliseconds / 6048e5; case 'day': return days + milliseconds / 864e5; case 'hour': return days * 24 + milliseconds / 36e5; case 'minute': return days * 1440 + milliseconds / 6e4; case 'second': return days * 86400 + milliseconds / 1000; // Math.floor prevents floating point math errors here case 'millisecond': return Math.floor(days * 864e5) + milliseconds; default: throw new Error('Unknown unit ' + units); } } } // TODO: Use this.as('ms')? function duration_as__valueOf() { return ( this._milliseconds + this._days * 864e5 + (this._months % 12) * 2592e6 + toInt(this._months / 12) * 31536e6 ); } function makeAs(alias) { return function () { return this.as(alias); }; } var asMilliseconds = makeAs('ms'); var asSeconds = makeAs('s'); var asMinutes = makeAs('m'); var asHours = makeAs('h'); var asDays = makeAs('d'); var asWeeks = makeAs('w'); var asMonths = makeAs('M'); var asYears = makeAs('y'); function duration_get__get(units) { units = normalizeUnits(units); return this[units + 's'](); } function makeGetter(name) { return function () { return this._data[name]; }; } var milliseconds = makeGetter('milliseconds'); var seconds = makeGetter('seconds'); var minutes = makeGetter('minutes'); var hours = makeGetter('hours'); var days = makeGetter('days'); var duration_get__months = makeGetter('months'); var years = makeGetter('years'); function weeks() { return absFloor(this.days() / 7); } var round = Math.round; var thresholds = { s: 45, // seconds to minute m: 45, // minutes to hour h: 22, // hours to day d: 26, // days to month M: 11 // months to year }; // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) { return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture); } function duration_humanize__relativeTime(posNegDuration, withoutSuffix, locale) { var duration = create__createDuration(posNegDuration).abs(); var seconds = round(duration.as('s')); var minutes = round(duration.as('m')); var hours = round(duration.as('h')); var days = round(duration.as('d')); var months = round(duration.as('M')); var years = round(duration.as('y')); var a = seconds < thresholds.s && ['s', seconds] || minutes <= 1 && ['m'] || minutes < thresholds.m && ['mm', minutes] || hours <= 1 && ['h'] || hours < thresholds.h && ['hh', hours] || days <= 1 && ['d'] || days < thresholds.d && ['dd', days] || months <= 1 && ['M'] || months < thresholds.M && ['MM', months] || years <= 1 && ['y'] || ['yy', years]; a[2] = withoutSuffix; a[3] = +posNegDuration > 0; a[4] = locale; return substituteTimeAgo.apply(null, a); } // This function allows you to set the rounding function for relative time strings function duration_humanize__getSetRelativeTimeRounding(roundingFunction) { if (roundingFunction === undefined) { return round; } if (typeof (roundingFunction) === 'function') { round = roundingFunction; return true; } return false; } // This function allows you to set a threshold for relative time strings function duration_humanize__getSetRelativeTimeThreshold(threshold, limit) { if (thresholds[threshold] === undefined) { return false; } if (limit === undefined) { return thresholds[threshold]; } thresholds[threshold] = limit; return true; } function humanize(withSuffix) { var locale = this.localeData(); var output = duration_humanize__relativeTime(this, !withSuffix, locale); if (withSuffix) { output = locale.pastFuture(+this, output); } return locale.postformat(output); } var iso_string__abs = Math.abs; function iso_string__toISOString() { // for ISO strings we do not use the normal bubbling rules: // * milliseconds bubble up until they become hours // * days do not bubble at all // * months bubble up until they become years // This is because there is no context-free conversion between hours and days // (think of clock changes) // and also not between days and months (28-31 days per month) var seconds = iso_string__abs(this._milliseconds) / 1000; var days = iso_string__abs(this._days); var months = iso_string__abs(this._months); var minutes, hours, years; // 3600 seconds -> 60 minutes -> 1 hour minutes = absFloor(seconds / 60); hours = absFloor(minutes / 60); seconds %= 60; minutes %= 60; // 12 months -> 1 year years = absFloor(months / 12); months %= 12; // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js var Y = years; var M = months; var D = days; var h = hours; var m = minutes; var s = seconds; var total = this.asSeconds(); if (!total) { // this is the same as C#'s (Noda) and python (isodate)... // but not other JS (goog.date) return 'P0D'; } return (total < 0 ? '-' : '') + 'P' + (Y ? Y + 'Y' : '') + (M ? M + 'M' : '') + (D ? D + 'D' : '') + ((h || m || s) ? 'T' : '') + (h ? h + 'H' : '') + (m ? m + 'M' : '') + (s ? s + 'S' : ''); } var duration_prototype__proto = Duration.prototype; duration_prototype__proto.abs = duration_abs__abs; duration_prototype__proto.add = duration_add_subtract__add; duration_prototype__proto.subtract = duration_add_subtract__subtract; duration_prototype__proto.as = as; duration_prototype__proto.asMilliseconds = asMilliseconds; duration_prototype__proto.asSeconds = asSeconds; duration_prototype__proto.asMinutes = asMinutes; duration_prototype__proto.asHours = asHours; duration_prototype__proto.asDays = asDays; duration_prototype__proto.asWeeks = asWeeks; duration_prototype__proto.asMonths = asMonths; duration_prototype__proto.asYears = asYears; duration_prototype__proto.valueOf = duration_as__valueOf; duration_prototype__proto._bubble = bubble; duration_prototype__proto.get = duration_get__get; duration_prototype__proto.milliseconds = milliseconds; duration_prototype__proto.seconds = seconds; duration_prototype__proto.minutes = minutes; duration_prototype__proto.hours = hours; duration_prototype__proto.days = days; duration_prototype__proto.weeks = weeks; duration_prototype__proto.months = duration_get__months; duration_prototype__proto.years = years; duration_prototype__proto.humanize = humanize; duration_prototype__proto.toISOString = iso_string__toISOString; duration_prototype__proto.toString = iso_string__toISOString; duration_prototype__proto.toJSON = iso_string__toISOString; duration_prototype__proto.locale = locale; duration_prototype__proto.localeData = localeData; // Deprecations duration_prototype__proto.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', iso_string__toISOString); duration_prototype__proto.lang = lang; // Side effect imports // FORMATTING addFormatToken('X', 0, 0, 'unix'); addFormatToken('x', 0, 0, 'valueOf'); // PARSING addRegexToken('x', matchSigned); addRegexToken('X', matchTimestamp); addParseToken('X', function (input, array, config) { config._d = new Date(parseFloat(input, 10) * 1000); }); addParseToken('x', function (input, array, config) { config._d = new Date(toInt(input)); }); // Side effect imports ; utils_hooks__hooks.version = '2.14.1'; setHookCallback(local__createLocal); utils_hooks__hooks.fn = momentPrototype; utils_hooks__hooks.min = min; utils_hooks__hooks.max = max; utils_hooks__hooks.now = now; utils_hooks__hooks.utc = create_utc__createUTC; utils_hooks__hooks.unix = moment_moment__createUnix; utils_hooks__hooks.months = lists__listMonths; utils_hooks__hooks.isDate = isDate; utils_hooks__hooks.locale = locale_locales__getSetGlobalLocale; utils_hooks__hooks.invalid = valid__createInvalid; utils_hooks__hooks.duration = create__createDuration; utils_hooks__hooks.isMoment = isMoment; utils_hooks__hooks.weekdays = lists__listWeekdays; utils_hooks__hooks.parseZone = moment_moment__createInZone; utils_hooks__hooks.localeData = locale_locales__getLocale; utils_hooks__hooks.isDuration = isDuration; utils_hooks__hooks.monthsShort = lists__listMonthsShort; utils_hooks__hooks.weekdaysMin = lists__listWeekdaysMin; utils_hooks__hooks.defineLocale = defineLocale; utils_hooks__hooks.updateLocale = updateLocale; utils_hooks__hooks.locales = locale_locales__listLocales; utils_hooks__hooks.weekdaysShort = lists__listWeekdaysShort; utils_hooks__hooks.normalizeUnits = normalizeUnits; utils_hooks__hooks.relativeTimeRounding = duration_humanize__getSetRelativeTimeRounding; utils_hooks__hooks.relativeTimeThreshold = duration_humanize__getSetRelativeTimeThreshold; utils_hooks__hooks.calendarFormat = getCalendarFormat; utils_hooks__hooks.prototype = momentPrototype; var moment__default = utils_hooks__hooks; var af = moment__default.defineLocale('af', { months: 'Januarie_Februarie_Maart_April_Mei_Junie_Julie_Augustus_September_Oktober_November_Desember'.split('_'), monthsShort: 'Jan_Feb_Mrt_Apr_Mei_Jun_Jul_Aug_Sep_Okt_Nov_Des'.split('_'), weekdays: 'Sondag_Maandag_Dinsdag_Woensdag_Donderdag_Vrydag_Saterdag'.split('_'), weekdaysShort: 'Son_Maa_Din_Woe_Don_Vry_Sat'.split('_'), weekdaysMin: 'So_Ma_Di_Wo_Do_Vr_Sa'.split('_'), meridiemParse: /vm|nm/i, isPM: function (input) { return /^nm$/i.test(input); }, meridiem: function (hours, minutes, isLower) { if (hours < 12) { return isLower ? 'vm' : 'VM'; } else { return isLower ? 'nm' : 'NM'; } }, longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'dddd, D MMMM YYYY HH:mm' }, calendar: { sameDay: '[Vandag om] LT', nextDay: '[Môre om] LT', nextWeek: 'dddd [om] LT', lastDay: '[Gister om] LT', lastWeek: '[Laas] dddd [om] LT', sameElse: 'L' }, relativeTime: { future: 'oor %s', past: '%s gelede', s: '\'n paar sekondes', m: '\'n minuut', mm: '%d minute', h: '\'n uur', hh: '%d ure', d: '\'n dag', dd: '%d dae', M: '\'n maand', MM: '%d maande', y: '\'n jaar', yy: '%d jaar' }, ordinalParse: /\d{1,2}(ste|de)/, ordinal: function (number) { return number + ((number === 1 || number === 8 || number >= 20) ? 'ste' : 'de'); // Thanks to Joris Röling : https://github.com/jjupiter }, week: { dow: 1, // Maandag is die eerste dag van die week. doy: 4 // Die week wat die 4de Januarie bevat is die eerste week van die jaar. } }); var ar_ma = moment__default.defineLocale('ar-ma', { months: 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split('_'), monthsShort: 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split('_'), weekdays: 'الأحد_الإتنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), weekdaysShort: 'احد_اتنين_ثلاثاء_اربعاء_خميس_جمعة_سبت'.split('_'), weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'dddd D MMMM YYYY HH:mm' }, calendar: { sameDay: '[اليوم على الساعة] LT', nextDay: '[غدا على الساعة] LT', nextWeek: 'dddd [على الساعة] LT', lastDay: '[أمس على الساعة] LT', lastWeek: 'dddd [على الساعة] LT', sameElse: 'L' }, relativeTime: { future: 'في %s', past: 'منذ %s', s: 'ثوان', m: 'دقيقة', mm: '%d دقائق', h: 'ساعة', hh: '%d ساعات', d: 'يوم', dd: '%d أيام', M: 'شهر', MM: '%d أشهر', y: 'سنة', yy: '%d سنوات' }, week: { dow: 6, // Saturday is the first day of the week. doy: 12 // The week that contains Jan 1st is the first week of the year. } }); var ar_sa__symbolMap = { '1': '١', '2': '٢', '3': '٣', '4': '٤', '5': '٥', '6': '٦', '7': '٧', '8': '٨', '9': '٩', '0': '٠' }, ar_sa__numberMap = { '١': '1', '٢': '2', '٣': '3', '٤': '4', '٥': '5', '٦': '6', '٧': '7', '٨': '8', '٩': '9', '٠': '0' }; var ar_sa = moment__default.defineLocale('ar-sa', { months: 'يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'), monthsShort: 'يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'), weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), weekdaysShort: 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'), weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'dddd D MMMM YYYY HH:mm' }, meridiemParse: /ص|م/, isPM: function (input) { return 'م' === input; }, meridiem: function (hour, minute, isLower) { if (hour < 12) { return 'ص'; } else { return 'م'; } }, calendar: { sameDay: '[اليوم على الساعة] LT', nextDay: '[غدا على الساعة] LT', nextWeek: 'dddd [على الساعة] LT', lastDay: '[أمس على الساعة] LT', lastWeek: 'dddd [على الساعة] LT', sameElse: 'L' }, relativeTime: { future: 'في %s', past: 'منذ %s', s: 'ثوان', m: 'دقيقة', mm: '%d دقائق', h: 'ساعة', hh: '%d ساعات', d: 'يوم', dd: '%d أيام', M: 'شهر', MM: '%d أشهر', y: 'سنة', yy: '%d سنوات' }, preparse: function (string) { return string.replace(/[١٢٣٤٥٦٧٨٩٠]/g, function (match) { return ar_sa__numberMap[match]; }).replace(/،/g, ','); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return ar_sa__symbolMap[match]; }).replace(/,/g, '،'); }, week: { dow: 6, // Saturday is the first day of the week. doy: 12 // The week that contains Jan 1st is the first week of the year. } }); var ar_tn = moment__default.defineLocale('ar-tn', { months: 'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'), monthsShort: 'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'), weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), weekdaysShort: 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'), weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'dddd D MMMM YYYY HH:mm' }, calendar: { sameDay: '[اليوم على الساعة] LT', nextDay: '[غدا على الساعة] LT', nextWeek: 'dddd [على الساعة] LT', lastDay: '[أمس على الساعة] LT', lastWeek: 'dddd [على الساعة] LT', sameElse: 'L' }, relativeTime: { future: 'في %s', past: 'منذ %s', s: 'ثوان', m: 'دقيقة', mm: '%d دقائق', h: 'ساعة', hh: '%d ساعات', d: 'يوم', dd: '%d أيام', M: 'شهر', MM: '%d أشهر', y: 'سنة', yy: '%d سنوات' }, week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); var ar__symbolMap = { '1': '١', '2': '٢', '3': '٣', '4': '٤', '5': '٥', '6': '٦', '7': '٧', '8': '٨', '9': '٩', '0': '٠' }, ar__numberMap = { '١': '1', '٢': '2', '٣': '3', '٤': '4', '٥': '5', '٦': '6', '٧': '7', '٨': '8', '٩': '9', '٠': '0' }, pluralForm = function (n) { return n === 0 ? 0 : n === 1 ? 1 : n === 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5; }, plurals = { s: ['أقل من ثانية', 'ثانية واحدة', ['ثانيتان', 'ثانيتين'], '%d ثوان', '%d ثانية', '%d ثانية'], m: ['أقل من دقيقة', 'دقيقة واحدة', ['دقيقتان', 'دقيقتين'], '%d دقائق', '%d دقيقة', '%d دقيقة'], h: ['أقل من ساعة', 'ساعة واحدة', ['ساعتان', 'ساعتين'], '%d ساعات', '%d ساعة', '%d ساعة'], d: ['أقل من يوم', 'يوم واحد', ['يومان', 'يومين'], '%d أيام', '%d يومًا', '%d يوم'], M: ['أقل من شهر', 'شهر واحد', ['شهران', 'شهرين'], '%d أشهر', '%d شهرا', '%d شهر'], y: ['أقل من عام', 'عام واحد', ['عامان', 'عامين'], '%d أعوام', '%d عامًا', '%d عام'] }, pluralize = function (u) { return function (number, withoutSuffix, string, isFuture) { var f = pluralForm(number), str = plurals[u][pluralForm(number)]; if (f === 2) { str = str[withoutSuffix ? 0 : 1]; } return str.replace(/%d/i, number); }; }, ar__months = [ 'كانون الثاني يناير', 'شباط فبراير', 'آذار مارس', 'نيسان أبريل', 'أيار مايو', 'حزيران يونيو', 'تموز يوليو', 'آب أغسطس', 'أيلول سبتمبر', 'تشرين الأول أكتوبر', 'تشرين الثاني نوفمبر', 'كانون الأول ديسمبر' ]; var ar = moment__default.defineLocale('ar', { months: ar__months, monthsShort: ar__months, weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), weekdaysShort: 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'), weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'D/\u200FM/\u200FYYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'dddd D MMMM YYYY HH:mm' }, meridiemParse: /ص|م/, isPM: function (input) { return 'م' === input; }, meridiem: function (hour, minute, isLower) { if (hour < 12) { return 'ص'; } else { return 'م'; } }, calendar: { sameDay: '[اليوم عند الساعة] LT', nextDay: '[غدًا عند الساعة] LT', nextWeek: 'dddd [عند الساعة] LT', lastDay: '[أمس عند الساعة] LT', lastWeek: 'dddd [عند الساعة] LT', sameElse: 'L' }, relativeTime: { future: 'بعد %s', past: 'منذ %s', s: pluralize('s'), m: pluralize('m'), mm: pluralize('m'), h: pluralize('h'), hh: pluralize('h'), d: pluralize('d'), dd: pluralize('d'), M: pluralize('M'), MM: pluralize('M'), y: pluralize('y'), yy: pluralize('y') }, preparse: function (string) { return string.replace(/\u200f/g, '').replace(/[١٢٣٤٥٦٧٨٩٠]/g, function (match) { return ar__numberMap[match]; }).replace(/،/g, ','); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return ar__symbolMap[match]; }).replace(/,/g, '،'); }, week: { dow: 6, // Saturday is the first day of the week. doy: 12 // The week that contains Jan 1st is the first week of the year. } }); var az__suffixes = { 1: '-inci', 5: '-inci', 8: '-inci', 70: '-inci', 80: '-inci', 2: '-nci', 7: '-nci', 20: '-nci', 50: '-nci', 3: '-üncü', 4: '-üncü', 100: '-üncü', 6: '-ncı', 9: '-uncu', 10: '-uncu', 30: '-uncu', 60: '-ıncı', 90: '-ıncı' }; var az = moment__default.defineLocale('az', { months: 'yanvar_fevral_mart_aprel_may_iyun_iyul_avqust_sentyabr_oktyabr_noyabr_dekabr'.split('_'), monthsShort: 'yan_fev_mar_apr_may_iyn_iyl_avq_sen_okt_noy_dek'.split('_'), weekdays: 'Bazar_Bazar ertəsi_Çərşənbə axşamı_Çərşənbə_Cümə axşamı_Cümə_Şənbə'.split('_'), weekdaysShort: 'Baz_BzE_ÇAx_Çər_CAx_Cüm_Şən'.split('_'), weekdaysMin: 'Bz_BE_ÇA_Çə_CA_Cü_Şə'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD.MM.YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'dddd, D MMMM YYYY HH:mm' }, calendar: { sameDay: '[bugün saat] LT', nextDay: '[sabah saat] LT', nextWeek: '[gələn həftə] dddd [saat] LT', lastDay: '[dünən] LT', lastWeek: '[keçən həftə] dddd [saat] LT', sameElse: 'L' }, relativeTime: { future: '%s sonra', past: '%s əvvəl', s: 'birneçə saniyyə', m: 'bir dəqiqə', mm: '%d dəqiqə', h: 'bir saat', hh: '%d saat', d: 'bir gün', dd: '%d gün', M: 'bir ay', MM: '%d ay', y: 'bir il', yy: '%d il' }, meridiemParse: /gecə|səhər|gündüz|axşam/, isPM: function (input) { return /^(gündüz|axşam)$/.test(input); }, meridiem: function (hour, minute, isLower) { if (hour < 4) { return 'gecə'; } else if (hour < 12) { return 'səhər'; } else if (hour < 17) { return 'gündüz'; } else { return 'axşam'; } }, ordinalParse: /\d{1,2}-(ıncı|inci|nci|üncü|ncı|uncu)/, ordinal: function (number) { if (number === 0) { // special case for zero return number + '-ıncı'; } var a = number % 10, b = number % 100 - a, c = number >= 100 ? 100 : null; return number + (az__suffixes[a] || az__suffixes[b] || az__suffixes[c]); }, week: { dow: 1, // Monday is the first day of the week. doy: 7 // The week that contains Jan 1st is the first week of the year. } }); function be__plural(word, num) { var forms = word.split('_'); return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]); } function be__relativeTimeWithPlural(number, withoutSuffix, key) { var format = { 'mm': withoutSuffix ? 'хвіліна_хвіліны_хвілін' : 'хвіліну_хвіліны_хвілін', 'hh': withoutSuffix ? 'гадзіна_гадзіны_гадзін' : 'гадзіну_гадзіны_гадзін', 'dd': 'дзень_дні_дзён', 'MM': 'месяц_месяцы_месяцаў', 'yy': 'год_гады_гадоў' }; if (key === 'm') { return withoutSuffix ? 'хвіліна' : 'хвіліну'; } else if (key === 'h') { return withoutSuffix ? 'гадзіна' : 'гадзіну'; } else { return number + ' ' + be__plural(format[key], +number); } } var be = moment__default.defineLocale('be', { months: { format: 'студзеня_лютага_сакавіка_красавіка_траўня_чэрвеня_ліпеня_жніўня_верасня_кастрычніка_лістапада_снежня'.split('_'), standalone: 'студзень_люты_сакавік_красавік_травень_чэрвень_ліпень_жнівень_верасень_кастрычнік_лістапад_снежань'.split('_') }, monthsShort: 'студ_лют_сак_крас_трав_чэрв_ліп_жнів_вер_каст_ліст_снеж'.split('_'), weekdays: { format: 'нядзелю_панядзелак_аўторак_сераду_чацвер_пятніцу_суботу'.split('_'), standalone: 'нядзеля_панядзелак_аўторак_серада_чацвер_пятніца_субота'.split('_'), isFormat: /\[ ?[Вв] ?(?:мінулую|наступную)? ?\] ?dddd/ }, weekdaysShort: 'нд_пн_ат_ср_чц_пт_сб'.split('_'), weekdaysMin: 'нд_пн_ат_ср_чц_пт_сб'.split('_'), longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD.MM.YYYY', LL: 'D MMMM YYYY г.', LLL: 'D MMMM YYYY г., HH:mm', LLLL: 'dddd, D MMMM YYYY г., HH:mm' }, calendar: { sameDay: '[Сёння ў] LT', nextDay: '[Заўтра ў] LT', lastDay: '[Учора ў] LT', nextWeek: function () { return '[У] dddd [ў] LT'; }, lastWeek: function () { switch (this.day()) { case 0: case 3: case 5: case 6: return '[У мінулую] dddd [ў] LT'; case 1: case 2: case 4: return '[У мінулы] dddd [ў] LT'; } }, sameElse: 'L' }, relativeTime: { future: 'праз %s', past: '%s таму', s: 'некалькі секунд', m: be__relativeTimeWithPlural, mm: be__relativeTimeWithPlural, h: be__relativeTimeWithPlural, hh: be__relativeTimeWithPlural, d: 'дзень', dd: be__relativeTimeWithPlural, M: 'месяц', MM: be__relativeTimeWithPlural, y: 'год', yy: be__relativeTimeWithPlural }, meridiemParse: /ночы|раніцы|дня|вечара/, isPM: function (input) { return /^(дня|вечара)$/.test(input); }, meridiem: function (hour, minute, isLower) { if (hour < 4) { return 'ночы'; } else if (hour < 12) { return 'раніцы'; } else if (hour < 17) { return 'дня'; } else { return 'вечара'; } }, ordinalParse: /\d{1,2}-(і|ы|га)/, ordinal: function (number, period) { switch (period) { case 'M': case 'd': case 'DDD': case 'w': case 'W': return (number % 10 === 2 || number % 10 === 3) && (number % 100 !== 12 && number % 100 !== 13) ? number + '-і' : number + '-ы'; case 'D': return number + '-га'; default: return number; } }, week: { dow: 1, // Monday is the first day of the week. doy: 7 // The week that contains Jan 1st is the first week of the year. } }); var bg = moment__default.defineLocale('bg', { months: 'януари_февруари_март_април_май_юни_юли_август_септември_октомври_ноември_декември'.split('_'), monthsShort: 'янр_фев_мар_апр_май_юни_юли_авг_сеп_окт_ное_дек'.split('_'), weekdays: 'неделя_понеделник_вторник_сряда_четвъртък_петък_събота'.split('_'), weekdaysShort: 'нед_пон_вто_сря_чет_пет_съб'.split('_'), weekdaysMin: 'нд_пн_вт_ср_чт_пт_сб'.split('_'), longDateFormat: { LT: 'H:mm', LTS: 'H:mm:ss', L: 'D.MM.YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY H:mm', LLLL: 'dddd, D MMMM YYYY H:mm' }, calendar: { sameDay: '[Днес в] LT', nextDay: '[Утре в] LT', nextWeek: 'dddd [в] LT', lastDay: '[Вчера в] LT', lastWeek: function () { switch (this.day()) { case 0: case 3: case 6: return '[В изминалата] dddd [в] LT'; case 1: case 2: case 4: case 5: return '[В изминалия] dddd [в] LT'; } }, sameElse: 'L' }, relativeTime: { future: 'след %s', past: 'преди %s', s: 'няколко секунди', m: 'минута', mm: '%d минути', h: 'час', hh: '%d часа', d: 'ден', dd: '%d дни', M: 'месец', MM: '%d месеца', y: 'година', yy: '%d години' }, ordinalParse: /\d{1,2}-(ев|ен|ти|ви|ри|ми)/, ordinal: function (number) { var lastDigit = number % 10, last2Digits = number % 100; if (number === 0) { return number + '-ев'; } else if (last2Digits === 0) { return number + '-ен'; } else if (last2Digits > 10 && last2Digits < 20) { return number + '-ти'; } else if (lastDigit === 1) { return number + '-ви'; } else if (lastDigit === 2) { return number + '-ри'; } else if (lastDigit === 7 || lastDigit === 8) { return number + '-ми'; } else { return number + '-ти'; } }, week: { dow: 1, // Monday is the first day of the week. doy: 7 // The week that contains Jan 1st is the first week of the year. } }); var bn__symbolMap = { '1': '১', '2': '২', '3': '৩', '4': '৪', '5': '৫', '6': '৬', '7': '৭', '8': '৮', '9': '৯', '0': '০' }, bn__numberMap = { '১': '1', '২': '2', '৩': '3', '৪': '4', '৫': '5', '৬': '6', '৭': '7', '৮': '8', '৯': '9', '০': '0' }; var bn = moment__default.defineLocale('bn', { months: 'জানুয়ারী_ফেবুয়ারী_মার্চ_এপ্রিল_মে_জুন_জুলাই_অগাস্ট_সেপ্টেম্বর_অক্টোবর_নভেম্বর_ডিসেম্বর'.split('_'), monthsShort: 'জানু_ফেব_মার্চ_এপর_মে_জুন_জুল_অগ_সেপ্ট_অক্টো_নভ_ডিসেম্'.split('_'), weekdays: 'রবিবার_সোমবার_মঙ্গলবার_বুধবার_বৃহস্পত্তিবার_শুক্রবার_শনিবার'.split('_'), weekdaysShort: 'রবি_সোম_মঙ্গল_বুধ_বৃহস্পত্তি_শুক্র_শনি'.split('_'), weekdaysMin: 'রব_সম_মঙ্গ_বু_ব্রিহ_শু_শনি'.split('_'), longDateFormat: { LT: 'A h:mm সময়', LTS: 'A h:mm:ss সময়', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY, A h:mm সময়', LLLL: 'dddd, D MMMM YYYY, A h:mm সময়' }, calendar: { sameDay: '[আজ] LT', nextDay: '[আগামীকাল] LT', nextWeek: 'dddd, LT', lastDay: '[গতকাল] LT', lastWeek: '[গত] dddd, LT', sameElse: 'L' }, relativeTime: { future: '%s পরে', past: '%s আগে', s: 'কয়েক সেকেন্ড', m: 'এক মিনিট', mm: '%d মিনিট', h: 'এক ঘন্টা', hh: '%d ঘন্টা', d: 'এক দিন', dd: '%d দিন', M: 'এক মাস', MM: '%d মাস', y: 'এক বছর', yy: '%d বছর' }, preparse: function (string) { return string.replace(/[১২৩৪৫৬৭৮৯০]/g, function (match) { return bn__numberMap[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return bn__symbolMap[match]; }); }, meridiemParse: /রাত|সকাল|দুপুর|বিকাল|রাত/, meridiemHour: function (hour, meridiem) { if (hour === 12) { hour = 0; } if ((meridiem === 'রাত' && hour >= 4) || (meridiem === 'দুপুর' && hour < 5) || meridiem === 'বিকাল') { return hour + 12; } else { return hour; } }, meridiem: function (hour, minute, isLower) { if (hour < 4) { return 'রাত'; } else if (hour < 10) { return 'সকাল'; } else if (hour < 17) { return 'দুপুর'; } else if (hour < 20) { return 'বিকাল'; } else { return 'রাত'; } }, week: { dow: 0, // Sunday is the first day of the week. doy: 6 // The week that contains Jan 1st is the first week of the year. } }); var bo__symbolMap = { '1': '༡', '2': '༢', '3': '༣', '4': '༤', '5': '༥', '6': '༦', '7': '༧', '8': '༨', '9': '༩', '0': '༠' }, bo__numberMap = { '༡': '1', '༢': '2', '༣': '3', '༤': '4', '༥': '5', '༦': '6', '༧': '7', '༨': '8', '༩': '9', '༠': '0' }; var bo = moment__default.defineLocale('bo', { months: 'ཟླ་བ་དང་པོ_ཟླ་བ་གཉིས་པ_ཟླ་བ་གསུམ་པ_ཟླ་བ་བཞི་པ_ཟླ་བ་ལྔ་པ_ཟླ་བ་དྲུག་པ_ཟླ་བ་བདུན་པ_ཟླ་བ་བརྒྱད་པ_ཟླ་བ་དགུ་པ_ཟླ་བ་བཅུ་པ_ཟླ་བ་བཅུ་གཅིག་པ_ཟླ་བ་བཅུ་གཉིས་པ'.split('_'), monthsShort: 'ཟླ་བ་དང་པོ_ཟླ་བ་གཉིས་པ_ཟླ་བ་གསུམ་པ_ཟླ་བ་བཞི་པ_ཟླ་བ་ལྔ་པ_ཟླ་བ་དྲུག་པ_ཟླ་བ་བདུན་པ_ཟླ་བ་བརྒྱད་པ_ཟླ་བ་དགུ་པ_ཟླ་བ་བཅུ་པ_ཟླ་བ་བཅུ་གཅིག་པ_ཟླ་བ་བཅུ་གཉིས་པ'.split('_'), weekdays: 'གཟའ་ཉི་མ་_གཟའ་ཟླ་བ་_གཟའ་མིག་དམར་_གཟའ་ལྷག་པ་_གཟའ་ཕུར་བུ_གཟའ་པ་སངས་_གཟའ་སྤེན་པ་'.split('_'), weekdaysShort: 'ཉི་མ་_ཟླ་བ་_མིག་དམར་_ལྷག་པ་_ཕུར་བུ_པ་སངས་_སྤེན་པ་'.split('_'), weekdaysMin: 'ཉི་མ་_ཟླ་བ་_མིག་དམར་_ལྷག་པ་_ཕུར་བུ_པ་སངས་_སྤེན་པ་'.split('_'), longDateFormat: { LT: 'A h:mm', LTS: 'A h:mm:ss', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY, A h:mm', LLLL: 'dddd, D MMMM YYYY, A h:mm' }, calendar: { sameDay: '[དི་རིང] LT', nextDay: '[སང་ཉིན] LT', nextWeek: '[བདུན་ཕྲག་རྗེས་མ], LT', lastDay: '[ཁ་སང] LT', lastWeek: '[བདུན་ཕྲག་མཐའ་མ] dddd, LT', sameElse: 'L' }, relativeTime: { future: '%s ལ་', past: '%s སྔན་ལ', s: 'ལམ་སང', m: 'སྐར་མ་གཅིག', mm: '%d སྐར་མ', h: 'ཆུ་ཚོད་གཅིག', hh: '%d ཆུ་ཚོད', d: 'ཉིན་གཅིག', dd: '%d ཉིན་', M: 'ཟླ་བ་གཅིག', MM: '%d ཟླ་བ', y: 'ལོ་གཅིག', yy: '%d ལོ' }, preparse: function (string) { return string.replace(/[༡༢༣༤༥༦༧༨༩༠]/g, function (match) { return bo__numberMap[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return bo__symbolMap[match]; }); }, meridiemParse: /མཚན་མོ|ཞོགས་ཀས|ཉིན་གུང|དགོང་དག|མཚན་མོ/, meridiemHour: function (hour, meridiem) { if (hour === 12) { hour = 0; } if ((meridiem === 'མཚན་མོ' && hour >= 4) || (meridiem === 'ཉིན་གུང' && hour < 5) || meridiem === 'དགོང་དག') { return hour + 12; } else { return hour; } }, meridiem: function (hour, minute, isLower) { if (hour < 4) { return 'མཚན་མོ'; } else if (hour < 10) { return 'ཞོགས་ཀས'; } else if (hour < 17) { return 'ཉིན་གུང'; } else if (hour < 20) { return 'དགོང་དག'; } else { return 'མཚན་མོ'; } }, week: { dow: 0, // Sunday is the first day of the week. doy: 6 // The week that contains Jan 1st is the first week of the year. } }); function relativeTimeWithMutation(number, withoutSuffix, key) { var format = { 'mm': 'munutenn', 'MM': 'miz', 'dd': 'devezh' }; return number + ' ' + mutation(format[key], number); } function specialMutationForYears(number) { switch (lastNumber(number)) { case 1: case 3: case 4: case 5: case 9: return number + ' bloaz'; default: return number + ' vloaz'; } } function lastNumber(number) { if (number > 9) { return lastNumber(number % 10); } return number; } function mutation(text, number) { if (number === 2) { return softMutation(text); } return text; } function softMutation(text) { var mutationTable = { 'm': 'v', 'b': 'v', 'd': 'z' }; if (mutationTable[text.charAt(0)] === undefined) { return text; } return mutationTable[text.charAt(0)] + text.substring(1); } var br = moment__default.defineLocale('br', { months: 'Genver_C\'hwevrer_Meurzh_Ebrel_Mae_Mezheven_Gouere_Eost_Gwengolo_Here_Du_Kerzu'.split('_'), monthsShort: 'Gen_C\'hwe_Meu_Ebr_Mae_Eve_Gou_Eos_Gwe_Her_Du_Ker'.split('_'), weekdays: 'Sul_Lun_Meurzh_Merc\'her_Yaou_Gwener_Sadorn'.split('_'), weekdaysShort: 'Sul_Lun_Meu_Mer_Yao_Gwe_Sad'.split('_'), weekdaysMin: 'Su_Lu_Me_Mer_Ya_Gw_Sa'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'h[e]mm A', LTS: 'h[e]mm:ss A', L: 'DD/MM/YYYY', LL: 'D [a viz] MMMM YYYY', LLL: 'D [a viz] MMMM YYYY h[e]mm A', LLLL: 'dddd, D [a viz] MMMM YYYY h[e]mm A' }, calendar: { sameDay: '[Hiziv da] LT', nextDay: '[Warc\'hoazh da] LT', nextWeek: 'dddd [da] LT', lastDay: '[Dec\'h da] LT', lastWeek: 'dddd [paset da] LT', sameElse: 'L' }, relativeTime: { future: 'a-benn %s', past: '%s \'zo', s: 'un nebeud segondennoù', m: 'ur vunutenn', mm: relativeTimeWithMutation, h: 'un eur', hh: '%d eur', d: 'un devezh', dd: relativeTimeWithMutation, M: 'ur miz', MM: relativeTimeWithMutation, y: 'ur bloaz', yy: specialMutationForYears }, ordinalParse: /\d{1,2}(añ|vet)/, ordinal: function (number) { var output = (number === 1) ? 'añ' : 'vet'; return number + output; }, week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); function bs__translate(number, withoutSuffix, key) { var result = number + ' '; switch (key) { case 'm': return withoutSuffix ? 'jedna minuta' : 'jedne minute'; case 'mm': if (number === 1) { result += 'minuta'; } else if (number === 2 || number === 3 || number === 4) { result += 'minute'; } else { result += 'minuta'; } return result; case 'h': return withoutSuffix ? 'jedan sat' : 'jednog sata'; case 'hh': if (number === 1) { result += 'sat'; } else if (number === 2 || number === 3 || number === 4) { result += 'sata'; } else { result += 'sati'; } return result; case 'dd': if (number === 1) { result += 'dan'; } else { result += 'dana'; } return result; case 'MM': if (number === 1) { result += 'mjesec'; } else if (number === 2 || number === 3 || number === 4) { result += 'mjeseca'; } else { result += 'mjeseci'; } return result; case 'yy': if (number === 1) { result += 'godina'; } else if (number === 2 || number === 3 || number === 4) { result += 'godine'; } else { result += 'godina'; } return result; } } var bs = moment__default.defineLocale('bs', { months: 'januar_februar_mart_april_maj_juni_juli_august_septembar_oktobar_novembar_decembar'.split('_'), monthsShort: 'jan._feb._mar._apr._maj._jun._jul._aug._sep._okt._nov._dec.'.split('_'), monthsParseExact: true, weekdays: 'nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota'.split('_'), weekdaysShort: 'ned._pon._uto._sri._čet._pet._sub.'.split('_'), weekdaysMin: 'ne_po_ut_sr_če_pe_su'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'H:mm', LTS: 'H:mm:ss', L: 'DD. MM. YYYY', LL: 'D. MMMM YYYY', LLL: 'D. MMMM YYYY H:mm', LLLL: 'dddd, D. MMMM YYYY H:mm' }, calendar: { sameDay: '[danas u] LT', nextDay: '[sutra u] LT', nextWeek: function () { switch (this.day()) { case 0: return '[u] [nedjelju] [u] LT'; case 3: return '[u] [srijedu] [u] LT'; case 6: return '[u] [subotu] [u] LT'; case 1: case 2: case 4: case 5: return '[u] dddd [u] LT'; } }, lastDay: '[jučer u] LT', lastWeek: function () { switch (this.day()) { case 0: case 3: return '[prošlu] dddd [u] LT'; case 6: return '[prošle] [subote] [u] LT'; case 1: case 2: case 4: case 5: return '[prošli] dddd [u] LT'; } }, sameElse: 'L' }, relativeTime: { future: 'za %s', past: 'prije %s', s: 'par sekundi', m: bs__translate, mm: bs__translate, h: bs__translate, hh: bs__translate, d: 'dan', dd: bs__translate, M: 'mjesec', MM: bs__translate, y: 'godinu', yy: bs__translate }, ordinalParse: /\d{1,2}\./, ordinal: '%d.', week: { dow: 1, // Monday is the first day of the week. doy: 7 // The week that contains Jan 1st is the first week of the year. } }); var ca = moment__default.defineLocale('ca', { months: 'gener_febrer_març_abril_maig_juny_juliol_agost_setembre_octubre_novembre_desembre'.split('_'), monthsShort: 'gen._febr._mar._abr._mai._jun._jul._ag._set._oct._nov._des.'.split('_'), monthsParseExact: true, weekdays: 'diumenge_dilluns_dimarts_dimecres_dijous_divendres_dissabte'.split('_'), weekdaysShort: 'dg._dl._dt._dc._dj._dv._ds.'.split('_'), weekdaysMin: 'Dg_Dl_Dt_Dc_Dj_Dv_Ds'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'H:mm', LTS: 'H:mm:ss', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY H:mm', LLLL: 'dddd D MMMM YYYY H:mm' }, calendar: { sameDay: function () { return '[avui a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; }, nextDay: function () { return '[demà a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; }, nextWeek: function () { return 'dddd [a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; }, lastDay: function () { return '[ahir a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; }, lastWeek: function () { return '[el] dddd [passat a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; }, sameElse: 'L' }, relativeTime: { future: 'en %s', past: 'fa %s', s: 'uns segons', m: 'un minut', mm: '%d minuts', h: 'una hora', hh: '%d hores', d: 'un dia', dd: '%d dies', M: 'un mes', MM: '%d mesos', y: 'un any', yy: '%d anys' }, ordinalParse: /\d{1,2}(r|n|t|è|a)/, ordinal: function (number, period) { var output = (number === 1) ? 'r' : (number === 2) ? 'n' : (number === 3) ? 'r' : (number === 4) ? 't' : 'è'; if (period === 'w' || period === 'W') { output = 'a'; } return number + output; }, week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); var cs__months = 'leden_únor_březen_duben_květen_červen_červenec_srpen_září_říjen_listopad_prosinec'.split('_'), cs__monthsShort = 'led_úno_bře_dub_kvě_čvn_čvc_srp_zář_říj_lis_pro'.split('_'); function cs__plural(n) { return (n > 1) && (n < 5) && (~~(n / 10) !== 1); } function cs__translate(number, withoutSuffix, key, isFuture) { var result = number + ' '; switch (key) { case 's': // a few seconds / in a few seconds / a few seconds ago return (withoutSuffix || isFuture) ? 'pár sekund' : 'pár sekundami'; case 'm': // a minute / in a minute / a minute ago return withoutSuffix ? 'minuta' : (isFuture ? 'minutu' : 'minutou'); case 'mm': // 9 minutes / in 9 minutes / 9 minutes ago if (withoutSuffix || isFuture) { return result + (cs__plural(number) ? 'minuty' : 'minut'); } else { return result + 'minutami'; } break; case 'h': // an hour / in an hour / an hour ago return withoutSuffix ? 'hodina' : (isFuture ? 'hodinu' : 'hodinou'); case 'hh': // 9 hours / in 9 hours / 9 hours ago if (withoutSuffix || isFuture) { return result + (cs__plural(number) ? 'hodiny' : 'hodin'); } else { return result + 'hodinami'; } break; case 'd': // a day / in a day / a day ago return (withoutSuffix || isFuture) ? 'den' : 'dnem'; case 'dd': // 9 days / in 9 days / 9 days ago if (withoutSuffix || isFuture) { return result + (cs__plural(number) ? 'dny' : 'dní'); } else { return result + 'dny'; } break; case 'M': // a month / in a month / a month ago return (withoutSuffix || isFuture) ? 'měsíc' : 'měsícem'; case 'MM': // 9 months / in 9 months / 9 months ago if (withoutSuffix || isFuture) { return result + (cs__plural(number) ? 'měsíce' : 'měsíců'); } else { return result + 'měsíci'; } break; case 'y': // a year / in a year / a year ago return (withoutSuffix || isFuture) ? 'rok' : 'rokem'; case 'yy': // 9 years / in 9 years / 9 years ago if (withoutSuffix || isFuture) { return result + (cs__plural(number) ? 'roky' : 'let'); } else { return result + 'lety'; } break; } } var cs = moment__default.defineLocale('cs', { months: cs__months, monthsShort: cs__monthsShort, monthsParse: (function (months, monthsShort) { var i, _monthsParse = []; for (i = 0; i < 12; i++) { // use custom parser to solve problem with July (červenec) _monthsParse[i] = new RegExp('^' + months[i] + '$|^' + monthsShort[i] + '$', 'i'); } return _monthsParse; }(cs__months, cs__monthsShort)), shortMonthsParse: (function (monthsShort) { var i, _shortMonthsParse = []; for (i = 0; i < 12; i++) { _shortMonthsParse[i] = new RegExp('^' + monthsShort[i] + '$', 'i'); } return _shortMonthsParse; }(cs__monthsShort)), longMonthsParse: (function (months) { var i, _longMonthsParse = []; for (i = 0; i < 12; i++) { _longMonthsParse[i] = new RegExp('^' + months[i] + '$', 'i'); } return _longMonthsParse; }(cs__months)), weekdays: 'neděle_pondělí_úterý_středa_čtvrtek_pátek_sobota'.split('_'), weekdaysShort: 'ne_po_út_st_čt_pá_so'.split('_'), weekdaysMin: 'ne_po_út_st_čt_pá_so'.split('_'), longDateFormat: { LT: 'H:mm', LTS: 'H:mm:ss', L: 'DD.MM.YYYY', LL: 'D. MMMM YYYY', LLL: 'D. MMMM YYYY H:mm', LLLL: 'dddd D. MMMM YYYY H:mm', l: 'D. M. YYYY' }, calendar: { sameDay: '[dnes v] LT', nextDay: '[zítra v] LT', nextWeek: function () { switch (this.day()) { case 0: return '[v neděli v] LT'; case 1: case 2: return '[v] dddd [v] LT'; case 3: return '[ve středu v] LT'; case 4: return '[ve čtvrtek v] LT'; case 5: return '[v pátek v] LT'; case 6: return '[v sobotu v] LT'; } }, lastDay: '[včera v] LT', lastWeek: function () { switch (this.day()) { case 0: return '[minulou neděli v] LT'; case 1: case 2: return '[minulé] dddd [v] LT'; case 3: return '[minulou středu v] LT'; case 4: case 5: return '[minulý] dddd [v] LT'; case 6: return '[minulou sobotu v] LT'; } }, sameElse: 'L' }, relativeTime: { future: 'za %s', past: 'před %s', s: cs__translate, m: cs__translate, mm: cs__translate, h: cs__translate, hh: cs__translate, d: cs__translate, dd: cs__translate, M: cs__translate, MM: cs__translate, y: cs__translate, yy: cs__translate }, ordinalParse: /\d{1,2}\./, ordinal: '%d.', week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); var cv = moment__default.defineLocale('cv', { months: 'кӑрлач_нарӑс_пуш_ака_май_ҫӗртме_утӑ_ҫурла_авӑн_юпа_чӳк_раштав'.split('_'), monthsShort: 'кӑр_нар_пуш_ака_май_ҫӗр_утӑ_ҫур_авн_юпа_чӳк_раш'.split('_'), weekdays: 'вырсарникун_тунтикун_ытларикун_юнкун_кӗҫнерникун_эрнекун_шӑматкун'.split('_'), weekdaysShort: 'выр_тун_ытл_юн_кӗҫ_эрн_шӑм'.split('_'), weekdaysMin: 'вр_тн_ыт_юн_кҫ_эр_шм'.split('_'), longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD-MM-YYYY', LL: 'YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ]', LLL: 'YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ], HH:mm', LLLL: 'dddd, YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ], HH:mm' }, calendar: { sameDay: '[Паян] LT [сехетре]', nextDay: '[Ыран] LT [сехетре]', lastDay: '[Ӗнер] LT [сехетре]', nextWeek: '[Ҫитес] dddd LT [сехетре]', lastWeek: '[Иртнӗ] dddd LT [сехетре]', sameElse: 'L' }, relativeTime: { future: function (output) { var affix = /сехет$/i.exec(output) ? 'рен' : /ҫул$/i.exec(output) ? 'тан' : 'ран'; return output + affix; }, past: '%s каялла', s: 'пӗр-ик ҫеккунт', m: 'пӗр минут', mm: '%d минут', h: 'пӗр сехет', hh: '%d сехет', d: 'пӗр кун', dd: '%d кун', M: 'пӗр уйӑх', MM: '%d уйӑх', y: 'пӗр ҫул', yy: '%d ҫул' }, ordinalParse: /\d{1,2}-мӗш/, ordinal: '%d-мӗш', week: { dow: 1, // Monday is the first day of the week. doy: 7 // The week that contains Jan 1st is the first week of the year. } }); var cy = moment__default.defineLocale('cy', { months: 'Ionawr_Chwefror_Mawrth_Ebrill_Mai_Mehefin_Gorffennaf_Awst_Medi_Hydref_Tachwedd_Rhagfyr'.split('_'), monthsShort: 'Ion_Chwe_Maw_Ebr_Mai_Meh_Gor_Aws_Med_Hyd_Tach_Rhag'.split('_'), weekdays: 'Dydd Sul_Dydd Llun_Dydd Mawrth_Dydd Mercher_Dydd Iau_Dydd Gwener_Dydd Sadwrn'.split('_'), weekdaysShort: 'Sul_Llun_Maw_Mer_Iau_Gwe_Sad'.split('_'), weekdaysMin: 'Su_Ll_Ma_Me_Ia_Gw_Sa'.split('_'), weekdaysParseExact: true, // time formats are the same as en-gb longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'dddd, D MMMM YYYY HH:mm' }, calendar: { sameDay: '[Heddiw am] LT', nextDay: '[Yfory am] LT', nextWeek: 'dddd [am] LT', lastDay: '[Ddoe am] LT', lastWeek: 'dddd [diwethaf am] LT', sameElse: 'L' }, relativeTime: { future: 'mewn %s', past: '%s yn ôl', s: 'ychydig eiliadau', m: 'munud', mm: '%d munud', h: 'awr', hh: '%d awr', d: 'diwrnod', dd: '%d diwrnod', M: 'mis', MM: '%d mis', y: 'blwyddyn', yy: '%d flynedd' }, ordinalParse: /\d{1,2}(fed|ain|af|il|ydd|ed|eg)/, // traditional ordinal numbers above 31 are not commonly used in colloquial Welsh ordinal: function (number) { var b = number, output = '', lookup = [ '', 'af', 'il', 'ydd', 'ydd', 'ed', 'ed', 'ed', 'fed', 'fed', 'fed', // 1af to 10fed 'eg', 'fed', 'eg', 'eg', 'fed', 'eg', 'eg', 'fed', 'eg', 'fed' // 11eg to 20fed ]; if (b > 20) { if (b === 40 || b === 50 || b === 60 || b === 80 || b === 100) { output = 'fed'; // not 30ain, 70ain or 90ain } else { output = 'ain'; } } else if (b > 0) { output = lookup[b]; } return number + output; }, week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); var da = moment__default.defineLocale('da', { months: 'januar_februar_marts_april_maj_juni_juli_august_september_oktober_november_december'.split('_'), monthsShort: 'jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec'.split('_'), weekdays: 'søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag'.split('_'), weekdaysShort: 'søn_man_tir_ons_tor_fre_lør'.split('_'), weekdaysMin: 'sø_ma_ti_on_to_fr_lø'.split('_'), longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD/MM/YYYY', LL: 'D. MMMM YYYY', LLL: 'D. MMMM YYYY HH:mm', LLLL: 'dddd [d.] D. MMMM YYYY HH:mm' }, calendar: { sameDay: '[I dag kl.] LT', nextDay: '[I morgen kl.] LT', nextWeek: 'dddd [kl.] LT', lastDay: '[I går kl.] LT', lastWeek: '[sidste] dddd [kl] LT', sameElse: 'L' }, relativeTime: { future: 'om %s', past: '%s siden', s: 'få sekunder', m: 'et minut', mm: '%d minutter', h: 'en time', hh: '%d timer', d: 'en dag', dd: '%d dage', M: 'en måned', MM: '%d måneder', y: 'et år', yy: '%d år' }, ordinalParse: /\d{1,2}\./, ordinal: '%d.', week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); function de_at__processRelativeTime(number, withoutSuffix, key, isFuture) { var format = { 'm': ['eine Minute', 'einer Minute'], 'h': ['eine Stunde', 'einer Stunde'], 'd': ['ein Tag', 'einem Tag'], 'dd': [number + ' Tage', number + ' Tagen'], 'M': ['ein Monat', 'einem Monat'], 'MM': [number + ' Monate', number + ' Monaten'], 'y': ['ein Jahr', 'einem Jahr'], 'yy': [number + ' Jahre', number + ' Jahren'] }; return withoutSuffix ? format[key][0] : format[key][1]; } var de_at = moment__default.defineLocale('de-at', { months: 'Jänner_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'), monthsShort: 'Jän._Febr._Mrz._Apr._Mai_Jun._Jul._Aug._Sept._Okt._Nov._Dez.'.split('_'), monthsParseExact: true, weekdays: 'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split('_'), weekdaysShort: 'So._Mo._Di._Mi._Do._Fr._Sa.'.split('_'), weekdaysMin: 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD.MM.YYYY', LL: 'D. MMMM YYYY', LLL: 'D. MMMM YYYY HH:mm', LLLL: 'dddd, D. MMMM YYYY HH:mm' }, calendar: { sameDay: '[heute um] LT [Uhr]', sameElse: 'L', nextDay: '[morgen um] LT [Uhr]', nextWeek: 'dddd [um] LT [Uhr]', lastDay: '[gestern um] LT [Uhr]', lastWeek: '[letzten] dddd [um] LT [Uhr]' }, relativeTime: { future: 'in %s', past: 'vor %s', s: 'ein paar Sekunden', m: de_at__processRelativeTime, mm: '%d Minuten', h: de_at__processRelativeTime, hh: '%d Stunden', d: de_at__processRelativeTime, dd: de_at__processRelativeTime, M: de_at__processRelativeTime, MM: de_at__processRelativeTime, y: de_at__processRelativeTime, yy: de_at__processRelativeTime }, ordinalParse: /\d{1,2}\./, ordinal: '%d.', week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); function de__processRelativeTime(number, withoutSuffix, key, isFuture) { var format = { 'm': ['eine Minute', 'einer Minute'], 'h': ['eine Stunde', 'einer Stunde'], 'd': ['ein Tag', 'einem Tag'], 'dd': [number + ' Tage', number + ' Tagen'], 'M': ['ein Monat', 'einem Monat'], 'MM': [number + ' Monate', number + ' Monaten'], 'y': ['ein Jahr', 'einem Jahr'], 'yy': [number + ' Jahre', number + ' Jahren'] }; return withoutSuffix ? format[key][0] : format[key][1]; } var de = moment__default.defineLocale('de', { months: 'Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'), monthsShort: 'Jan._Febr._Mrz._Apr._Mai_Jun._Jul._Aug._Sept._Okt._Nov._Dez.'.split('_'), monthsParseExact: true, weekdays: 'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split('_'), weekdaysShort: 'So._Mo._Di._Mi._Do._Fr._Sa.'.split('_'), weekdaysMin: 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD.MM.YYYY', LL: 'D. MMMM YYYY', LLL: 'D. MMMM YYYY HH:mm', LLLL: 'dddd, D. MMMM YYYY HH:mm' }, calendar: { sameDay: '[heute um] LT [Uhr]', sameElse: 'L', nextDay: '[morgen um] LT [Uhr]', nextWeek: 'dddd [um] LT [Uhr]', lastDay: '[gestern um] LT [Uhr]', lastWeek: '[letzten] dddd [um] LT [Uhr]' }, relativeTime: { future: 'in %s', past: 'vor %s', s: 'ein paar Sekunden', m: de__processRelativeTime, mm: '%d Minuten', h: de__processRelativeTime, hh: '%d Stunden', d: de__processRelativeTime, dd: de__processRelativeTime, M: de__processRelativeTime, MM: de__processRelativeTime, y: de__processRelativeTime, yy: de__processRelativeTime }, ordinalParse: /\d{1,2}\./, ordinal: '%d.', week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); var dv__months = [ 'ޖެނުއަރީ', 'ފެބްރުއަރީ', 'މާރިޗު', 'އޭޕްރީލު', 'މޭ', 'ޖޫން', 'ޖުލައި', 'އޯގަސްޓު', 'ސެޕްޓެމްބަރު', 'އޮކްޓޯބަރު', 'ނޮވެމްބަރު', 'ޑިސެމްބަރު' ], dv__weekdays = [ 'އާދިއްތަ', 'ހޯމަ', 'އަންގާރަ', 'ބުދަ', 'ބުރާސްފަތި', 'ހުކުރު', 'ހޮނިހިރު' ]; var dv = moment__default.defineLocale('dv', { months: dv__months, monthsShort: dv__months, weekdays: dv__weekdays, weekdaysShort: dv__weekdays, weekdaysMin: 'އާދި_ހޯމަ_އަން_ބުދަ_ބުރާ_ހުކު_ހޮނި'.split('_'), longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'D/M/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'dddd D MMMM YYYY HH:mm' }, meridiemParse: /މކ|މފ/, isPM: function (input) { return 'މފ' === input; }, meridiem: function (hour, minute, isLower) { if (hour < 12) { return 'މކ'; } else { return 'މފ'; } }, calendar: { sameDay: '[މިއަދު] LT', nextDay: '[މާދަމާ] LT', nextWeek: 'dddd LT', lastDay: '[އިއްޔެ] LT', lastWeek: '[ފާއިތުވި] dddd LT', sameElse: 'L' }, relativeTime: { future: 'ތެރޭގައި %s', past: 'ކުރިން %s', s: 'ސިކުންތުކޮޅެއް', m: 'މިނިޓެއް', mm: 'މިނިޓު %d', h: 'ގަޑިއިރެއް', hh: 'ގަޑިއިރު %d', d: 'ދުވަހެއް', dd: 'ދުވަސް %d', M: 'މަހެއް', MM: 'މަސް %d', y: 'އަހަރެއް', yy: 'އަހަރު %d' }, preparse: function (string) { return string.replace(/،/g, ','); }, postformat: function (string) { return string.replace(/,/g, '،'); }, week: { dow: 7, // Sunday is the first day of the week. doy: 12 // The week that contains Jan 1st is the first week of the year. } }); var el = moment__default.defineLocale('el', { monthsNominativeEl: 'Ιανουάριος_Φεβρουάριος_Μάρτιος_Απρίλιος_Μάιος_Ιούνιος_Ιούλιος_Αύγουστος_Σεπτέμβριος_Οκτώβριος_Νοέμβριος_Δεκέμβριος'.split('_'), monthsGenitiveEl: 'Ιανουαρίου_Φεβρουαρίου_Μαρτίου_Απριλίου_Μαΐου_Ιουνίου_Ιουλίου_Αυγούστου_Σεπτεμβρίου_Οκτωβρίου_Νοεμβρίου_Δεκεμβρίου'.split('_'), months: function (momentToFormat, format) { if (/D/.test(format.substring(0, format.indexOf('MMMM')))) { // if there is a day number before 'MMMM' return this._monthsGenitiveEl[momentToFormat.month()]; } else { return this._monthsNominativeEl[momentToFormat.month()]; } }, monthsShort: 'Ιαν_Φεβ_Μαρ_Απρ_Μαϊ_Ιουν_Ιουλ_Αυγ_Σεπ_Οκτ_Νοε_Δεκ'.split('_'), weekdays: 'Κυριακή_Δευτέρα_Τρίτη_Τετάρτη_Πέμπτη_Παρασκευή_Σάββατο'.split('_'), weekdaysShort: 'Κυρ_Δευ_Τρι_Τετ_Πεμ_Παρ_Σαβ'.split('_'), weekdaysMin: 'Κυ_Δε_Τρ_Τε_Πε_Πα_Σα'.split('_'), meridiem: function (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'μμ' : 'ΜΜ'; } else { return isLower ? 'πμ' : 'ΠΜ'; } }, isPM: function (input) { return ((input + '').toLowerCase()[0] === 'μ'); }, meridiemParse: /[ΠΜ]\.?Μ?\.?/i, longDateFormat: { LT: 'h:mm A', LTS: 'h:mm:ss A', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY h:mm A', LLLL: 'dddd, D MMMM YYYY h:mm A' }, calendarEl: { sameDay: '[Σήμερα {}] LT', nextDay: '[Αύριο {}] LT', nextWeek: 'dddd [{}] LT', lastDay: '[Χθες {}] LT', lastWeek: function () { switch (this.day()) { case 6: return '[το προηγούμενο] dddd [{}] LT'; default: return '[την προηγούμενη] dddd [{}] LT'; } }, sameElse: 'L' }, calendar: function (key, mom) { var output = this._calendarEl[key], hours = mom && mom.hours(); if (isFunction(output)) { output = output.apply(mom); } return output.replace('{}', (hours % 12 === 1 ? 'στη' : 'στις')); }, relativeTime: { future: 'σε %s', past: '%s πριν', s: 'λίγα δευτερόλεπτα', m: 'ένα λεπτό', mm: '%d λεπτά', h: 'μία ώρα', hh: '%d ώρες', d: 'μία μέρα', dd: '%d μέρες', M: 'ένας μήνας', MM: '%d μήνες', y: 'ένας χρόνος', yy: '%d χρόνια' }, ordinalParse: /\d{1,2}η/, ordinal: '%dη', week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4st is the first week of the year. } }); var en_au = moment__default.defineLocale('en-au', { months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), weekdaysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), weekdaysMin: 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), longDateFormat: { LT: 'h:mm A', LTS: 'h:mm:ss A', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY h:mm A', LLLL: 'dddd, D MMMM YYYY h:mm A' }, calendar: { sameDay: '[Today at] LT', nextDay: '[Tomorrow at] LT', nextWeek: 'dddd [at] LT', lastDay: '[Yesterday at] LT', lastWeek: '[Last] dddd [at] LT', sameElse: 'L' }, relativeTime: { future: 'in %s', past: '%s ago', s: 'a few seconds', m: 'a minute', mm: '%d minutes', h: 'an hour', hh: '%d hours', d: 'a day', dd: '%d days', M: 'a month', MM: '%d months', y: 'a year', yy: '%d years' }, ordinalParse: /\d{1,2}(st|nd|rd|th)/, ordinal: function (number) { var b = number % 10, output = (~~(number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; }, week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); var en_ca = moment__default.defineLocale('en-ca', { months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), weekdaysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), weekdaysMin: 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), longDateFormat: { LT: 'h:mm A', LTS: 'h:mm:ss A', L: 'YYYY-MM-DD', LL: 'MMMM D, YYYY', LLL: 'MMMM D, YYYY h:mm A', LLLL: 'dddd, MMMM D, YYYY h:mm A' }, calendar: { sameDay: '[Today at] LT', nextDay: '[Tomorrow at] LT', nextWeek: 'dddd [at] LT', lastDay: '[Yesterday at] LT', lastWeek: '[Last] dddd [at] LT', sameElse: 'L' }, relativeTime: { future: 'in %s', past: '%s ago', s: 'a few seconds', m: 'a minute', mm: '%d minutes', h: 'an hour', hh: '%d hours', d: 'a day', dd: '%d days', M: 'a month', MM: '%d months', y: 'a year', yy: '%d years' }, ordinalParse: /\d{1,2}(st|nd|rd|th)/, ordinal: function (number) { var b = number % 10, output = (~~(number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; } }); var en_gb = moment__default.defineLocale('en-gb', { months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), weekdaysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), weekdaysMin: 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'dddd, D MMMM YYYY HH:mm' }, calendar: { sameDay: '[Today at] LT', nextDay: '[Tomorrow at] LT', nextWeek: 'dddd [at] LT', lastDay: '[Yesterday at] LT', lastWeek: '[Last] dddd [at] LT', sameElse: 'L' }, relativeTime: { future: 'in %s', past: '%s ago', s: 'a few seconds', m: 'a minute', mm: '%d minutes', h: 'an hour', hh: '%d hours', d: 'a day', dd: '%d days', M: 'a month', MM: '%d months', y: 'a year', yy: '%d years' }, ordinalParse: /\d{1,2}(st|nd|rd|th)/, ordinal: function (number) { var b = number % 10, output = (~~(number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; }, week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); var en_ie = moment__default.defineLocale('en-ie', { months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), weekdaysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), weekdaysMin: 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD-MM-YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'dddd D MMMM YYYY HH:mm' }, calendar: { sameDay: '[Today at] LT', nextDay: '[Tomorrow at] LT', nextWeek: 'dddd [at] LT', lastDay: '[Yesterday at] LT', lastWeek: '[Last] dddd [at] LT', sameElse: 'L' }, relativeTime: { future: 'in %s', past: '%s ago', s: 'a few seconds', m: 'a minute', mm: '%d minutes', h: 'an hour', hh: '%d hours', d: 'a day', dd: '%d days', M: 'a month', MM: '%d months', y: 'a year', yy: '%d years' }, ordinalParse: /\d{1,2}(st|nd|rd|th)/, ordinal: function (number) { var b = number % 10, output = (~~(number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; }, week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); var en_nz = moment__default.defineLocale('en-nz', { months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), weekdaysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), weekdaysMin: 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), longDateFormat: { LT: 'h:mm A', LTS: 'h:mm:ss A', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY h:mm A', LLLL: 'dddd, D MMMM YYYY h:mm A' }, calendar: { sameDay: '[Today at] LT', nextDay: '[Tomorrow at] LT', nextWeek: 'dddd [at] LT', lastDay: '[Yesterday at] LT', lastWeek: '[Last] dddd [at] LT', sameElse: 'L' }, relativeTime: { future: 'in %s', past: '%s ago', s: 'a few seconds', m: 'a minute', mm: '%d minutes', h: 'an hour', hh: '%d hours', d: 'a day', dd: '%d days', M: 'a month', MM: '%d months', y: 'a year', yy: '%d years' }, ordinalParse: /\d{1,2}(st|nd|rd|th)/, ordinal: function (number) { var b = number % 10, output = (~~(number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; }, week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); var eo = moment__default.defineLocale('eo', { months: 'januaro_februaro_marto_aprilo_majo_junio_julio_aŭgusto_septembro_oktobro_novembro_decembro'.split('_'), monthsShort: 'jan_feb_mar_apr_maj_jun_jul_aŭg_sep_okt_nov_dec'.split('_'), weekdays: 'Dimanĉo_Lundo_Mardo_Merkredo_Ĵaŭdo_Vendredo_Sabato'.split('_'), weekdaysShort: 'Dim_Lun_Mard_Merk_Ĵaŭ_Ven_Sab'.split('_'), weekdaysMin: 'Di_Lu_Ma_Me_Ĵa_Ve_Sa'.split('_'), longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'YYYY-MM-DD', LL: 'D[-an de] MMMM, YYYY', LLL: 'D[-an de] MMMM, YYYY HH:mm', LLLL: 'dddd, [la] D[-an de] MMMM, YYYY HH:mm' }, meridiemParse: /[ap]\.t\.m/i, isPM: function (input) { return input.charAt(0).toLowerCase() === 'p'; }, meridiem: function (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'p.t.m.' : 'P.T.M.'; } else { return isLower ? 'a.t.m.' : 'A.T.M.'; } }, calendar: { sameDay: '[Hodiaŭ je] LT', nextDay: '[Morgaŭ je] LT', nextWeek: 'dddd [je] LT', lastDay: '[Hieraŭ je] LT', lastWeek: '[pasinta] dddd [je] LT', sameElse: 'L' }, relativeTime: { future: 'je %s', past: 'antaŭ %s', s: 'sekundoj', m: 'minuto', mm: '%d minutoj', h: 'horo', hh: '%d horoj', d: 'tago',//ne 'diurno', ĉar estas uzita por proksimumo dd: '%d tagoj', M: 'monato', MM: '%d monatoj', y: 'jaro', yy: '%d jaroj' }, ordinalParse: /\d{1,2}a/, ordinal: '%da', week: { dow: 1, // Monday is the first day of the week. doy: 7 // The week that contains Jan 1st is the first week of the year. } }); var es_do__monthsShortDot = 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split('_'), es_do__monthsShort = 'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_'); var es_do = moment__default.defineLocale('es-do', { months: 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split('_'), monthsShort: function (m, format) { if (/-MMM-/.test(format)) { return es_do__monthsShort[m.month()]; } else { return es_do__monthsShortDot[m.month()]; } }, monthsParseExact: true, weekdays: 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'), weekdaysShort: 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'), weekdaysMin: 'do_lu_ma_mi_ju_vi_sá'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'h:mm A', LTS: 'h:mm:ss A', L: 'DD/MM/YYYY', LL: 'D [de] MMMM [de] YYYY', LLL: 'D [de] MMMM [de] YYYY h:mm A', LLLL: 'dddd, D [de] MMMM [de] YYYY h:mm A' }, calendar: { sameDay: function () { return '[hoy a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, nextDay: function () { return '[mañana a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, nextWeek: function () { return 'dddd [a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, lastDay: function () { return '[ayer a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, lastWeek: function () { return '[el] dddd [pasado a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, sameElse: 'L' }, relativeTime: { future: 'en %s', past: 'hace %s', s: 'unos segundos', m: 'un minuto', mm: '%d minutos', h: 'una hora', hh: '%d horas', d: 'un día', dd: '%d días', M: 'un mes', MM: '%d meses', y: 'un año', yy: '%d años' }, ordinalParse: /\d{1,2}º/, ordinal: '%dº', week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); var es__monthsShortDot = 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split('_'), es__monthsShort = 'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_'); var es = moment__default.defineLocale('es', { months: 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split('_'), monthsShort: function (m, format) { if (/-MMM-/.test(format)) { return es__monthsShort[m.month()]; } else { return es__monthsShortDot[m.month()]; } }, monthsParseExact: true, weekdays: 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'), weekdaysShort: 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'), weekdaysMin: 'do_lu_ma_mi_ju_vi_sá'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'H:mm', LTS: 'H:mm:ss', L: 'DD/MM/YYYY', LL: 'D [de] MMMM [de] YYYY', LLL: 'D [de] MMMM [de] YYYY H:mm', LLLL: 'dddd, D [de] MMMM [de] YYYY H:mm' }, calendar: { sameDay: function () { return '[hoy a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, nextDay: function () { return '[mañana a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, nextWeek: function () { return 'dddd [a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, lastDay: function () { return '[ayer a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, lastWeek: function () { return '[el] dddd [pasado a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, sameElse: 'L' }, relativeTime: { future: 'en %s', past: 'hace %s', s: 'unos segundos', m: 'un minuto', mm: '%d minutos', h: 'una hora', hh: '%d horas', d: 'un día', dd: '%d días', M: 'un mes', MM: '%d meses', y: 'un año', yy: '%d años' }, ordinalParse: /\d{1,2}º/, ordinal: '%dº', week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); function et__processRelativeTime(number, withoutSuffix, key, isFuture) { var format = { 's': ['mõne sekundi', 'mõni sekund', 'paar sekundit'], 'm': ['ühe minuti', 'üks minut'], 'mm': [number + ' minuti', number + ' minutit'], 'h': ['ühe tunni', 'tund aega', 'üks tund'], 'hh': [number + ' tunni', number + ' tundi'], 'd': ['ühe päeva', 'üks päev'], 'M': ['kuu aja', 'kuu aega', 'üks kuu'], 'MM': [number + ' kuu', number + ' kuud'], 'y': ['ühe aasta', 'aasta', 'üks aasta'], 'yy': [number + ' aasta', number + ' aastat'] }; if (withoutSuffix) { return format[key][2] ? format[key][2] : format[key][1]; } return isFuture ? format[key][0] : format[key][1]; } var et = moment__default.defineLocale('et', { months: 'jaanuar_veebruar_märts_aprill_mai_juuni_juuli_august_september_oktoober_november_detsember'.split('_'), monthsShort: 'jaan_veebr_märts_apr_mai_juuni_juuli_aug_sept_okt_nov_dets'.split('_'), weekdays: 'pühapäev_esmaspäev_teisipäev_kolmapäev_neljapäev_reede_laupäev'.split('_'), weekdaysShort: 'P_E_T_K_N_R_L'.split('_'), weekdaysMin: 'P_E_T_K_N_R_L'.split('_'), longDateFormat: { LT: 'H:mm', LTS: 'H:mm:ss', L: 'DD.MM.YYYY', LL: 'D. MMMM YYYY', LLL: 'D. MMMM YYYY H:mm', LLLL: 'dddd, D. MMMM YYYY H:mm' }, calendar: { sameDay: '[Täna,] LT', nextDay: '[Homme,] LT', nextWeek: '[Järgmine] dddd LT', lastDay: '[Eile,] LT', lastWeek: '[Eelmine] dddd LT', sameElse: 'L' }, relativeTime: { future: '%s pärast', past: '%s tagasi', s: et__processRelativeTime, m: et__processRelativeTime, mm: et__processRelativeTime, h: et__processRelativeTime, hh: et__processRelativeTime, d: et__processRelativeTime, dd: '%d päeva', M: et__processRelativeTime, MM: et__processRelativeTime, y: et__processRelativeTime, yy: et__processRelativeTime }, ordinalParse: /\d{1,2}\./, ordinal: '%d.', week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); var eu = moment__default.defineLocale('eu', { months: 'urtarrila_otsaila_martxoa_apirila_maiatza_ekaina_uztaila_abuztua_iraila_urria_azaroa_abendua'.split('_'), monthsShort: 'urt._ots._mar._api._mai._eka._uzt._abu._ira._urr._aza._abe.'.split('_'), monthsParseExact: true, weekdays: 'igandea_astelehena_asteartea_asteazkena_osteguna_ostirala_larunbata'.split('_'), weekdaysShort: 'ig._al._ar._az._og._ol._lr.'.split('_'), weekdaysMin: 'ig_al_ar_az_og_ol_lr'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'YYYY-MM-DD', LL: 'YYYY[ko] MMMM[ren] D[a]', LLL: 'YYYY[ko] MMMM[ren] D[a] HH:mm', LLLL: 'dddd, YYYY[ko] MMMM[ren] D[a] HH:mm', l: 'YYYY-M-D', ll: 'YYYY[ko] MMM D[a]', lll: 'YYYY[ko] MMM D[a] HH:mm', llll: 'ddd, YYYY[ko] MMM D[a] HH:mm' }, calendar: { sameDay: '[gaur] LT[etan]', nextDay: '[bihar] LT[etan]', nextWeek: 'dddd LT[etan]', lastDay: '[atzo] LT[etan]', lastWeek: '[aurreko] dddd LT[etan]', sameElse: 'L' }, relativeTime: { future: '%s barru', past: 'duela %s', s: 'segundo batzuk', m: 'minutu bat', mm: '%d minutu', h: 'ordu bat', hh: '%d ordu', d: 'egun bat', dd: '%d egun', M: 'hilabete bat', MM: '%d hilabete', y: 'urte bat', yy: '%d urte' }, ordinalParse: /\d{1,2}\./, ordinal: '%d.', week: { dow: 1, // Monday is the first day of the week. doy: 7 // The week that contains Jan 1st is the first week of the year. } }); var fa__symbolMap = { '1': '۱', '2': '۲', '3': '۳', '4': '۴', '5': '۵', '6': '۶', '7': '۷', '8': '۸', '9': '۹', '0': '۰' }, fa__numberMap = { '۱': '1', '۲': '2', '۳': '3', '۴': '4', '۵': '5', '۶': '6', '۷': '7', '۸': '8', '۹': '9', '۰': '0' }; var fa = moment__default.defineLocale('fa', { months: 'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split('_'), monthsShort: 'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split('_'), weekdays: 'یک\u200cشنبه_دوشنبه_سه\u200cشنبه_چهارشنبه_پنج\u200cشنبه_جمعه_شنبه'.split('_'), weekdaysShort: 'یک\u200cشنبه_دوشنبه_سه\u200cشنبه_چهارشنبه_پنج\u200cشنبه_جمعه_شنبه'.split('_'), weekdaysMin: 'ی_د_س_چ_پ_ج_ش'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'dddd, D MMMM YYYY HH:mm' }, meridiemParse: /قبل از ظهر|بعد از ظهر/, isPM: function (input) { return /بعد از ظهر/.test(input); }, meridiem: function (hour, minute, isLower) { if (hour < 12) { return 'قبل از ظهر'; } else { return 'بعد از ظهر'; } }, calendar: { sameDay: '[امروز ساعت] LT', nextDay: '[فردا ساعت] LT', nextWeek: 'dddd [ساعت] LT', lastDay: '[دیروز ساعت] LT', lastWeek: 'dddd [پیش] [ساعت] LT', sameElse: 'L' }, relativeTime: { future: 'در %s', past: '%s پیش', s: 'چندین ثانیه', m: 'یک دقیقه', mm: '%d دقیقه', h: 'یک ساعت', hh: '%d ساعت', d: 'یک روز', dd: '%d روز', M: 'یک ماه', MM: '%d ماه', y: 'یک سال', yy: '%d سال' }, preparse: function (string) { return string.replace(/[۰-۹]/g, function (match) { return fa__numberMap[match]; }).replace(/،/g, ','); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return fa__symbolMap[match]; }).replace(/,/g, '،'); }, ordinalParse: /\d{1,2}م/, ordinal: '%dم', week: { dow: 6, // Saturday is the first day of the week. doy: 12 // The week that contains Jan 1st is the first week of the year. } }); var numbersPast = 'nolla yksi kaksi kolme neljä viisi kuusi seitsemän kahdeksan yhdeksän'.split(' '), numbersFuture = [ 'nolla', 'yhden', 'kahden', 'kolmen', 'neljän', 'viiden', 'kuuden', numbersPast[7], numbersPast[8], numbersPast[9] ]; function fi__translate(number, withoutSuffix, key, isFuture) { var result = ''; switch (key) { case 's': return isFuture ? 'muutaman sekunnin' : 'muutama sekunti'; case 'm': return isFuture ? 'minuutin' : 'minuutti'; case 'mm': result = isFuture ? 'minuutin' : 'minuuttia'; break; case 'h': return isFuture ? 'tunnin' : 'tunti'; case 'hh': result = isFuture ? 'tunnin' : 'tuntia'; break; case 'd': return isFuture ? 'päivän' : 'päivä'; case 'dd': result = isFuture ? 'päivän' : 'päivää'; break; case 'M': return isFuture ? 'kuukauden' : 'kuukausi'; case 'MM': result = isFuture ? 'kuukauden' : 'kuukautta'; break; case 'y': return isFuture ? 'vuoden' : 'vuosi'; case 'yy': result = isFuture ? 'vuoden' : 'vuotta'; break; } result = verbalNumber(number, isFuture) + ' ' + result; return result; } function verbalNumber(number, isFuture) { return number < 10 ? (isFuture ? numbersFuture[number] : numbersPast[number]) : number; } var fi = moment__default.defineLocale('fi', { months: 'tammikuu_helmikuu_maaliskuu_huhtikuu_toukokuu_kesäkuu_heinäkuu_elokuu_syyskuu_lokakuu_marraskuu_joulukuu'.split('_'), monthsShort: 'tammi_helmi_maalis_huhti_touko_kesä_heinä_elo_syys_loka_marras_joulu'.split('_'), weekdays: 'sunnuntai_maanantai_tiistai_keskiviikko_torstai_perjantai_lauantai'.split('_'), weekdaysShort: 'su_ma_ti_ke_to_pe_la'.split('_'), weekdaysMin: 'su_ma_ti_ke_to_pe_la'.split('_'), longDateFormat: { LT: 'HH.mm', LTS: 'HH.mm.ss', L: 'DD.MM.YYYY', LL: 'Do MMMM[ta] YYYY', LLL: 'Do MMMM[ta] YYYY, [klo] HH.mm', LLLL: 'dddd, Do MMMM[ta] YYYY, [klo] HH.mm', l: 'D.M.YYYY', ll: 'Do MMM YYYY', lll: 'Do MMM YYYY, [klo] HH.mm', llll: 'ddd, Do MMM YYYY, [klo] HH.mm' }, calendar: { sameDay: '[tänään] [klo] LT', nextDay: '[huomenna] [klo] LT', nextWeek: 'dddd [klo] LT', lastDay: '[eilen] [klo] LT', lastWeek: '[viime] dddd[na] [klo] LT', sameElse: 'L' }, relativeTime: { future: '%s päästä', past: '%s sitten', s: fi__translate, m: fi__translate, mm: fi__translate, h: fi__translate, hh: fi__translate, d: fi__translate, dd: fi__translate, M: fi__translate, MM: fi__translate, y: fi__translate, yy: fi__translate }, ordinalParse: /\d{1,2}\./, ordinal: '%d.', week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); var fo = moment__default.defineLocale('fo', { months: 'januar_februar_mars_apríl_mai_juni_juli_august_september_oktober_november_desember'.split('_'), monthsShort: 'jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des'.split('_'), weekdays: 'sunnudagur_mánadagur_týsdagur_mikudagur_hósdagur_fríggjadagur_leygardagur'.split('_'), weekdaysShort: 'sun_mán_týs_mik_hós_frí_ley'.split('_'), weekdaysMin: 'su_má_tý_mi_hó_fr_le'.split('_'), longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'dddd D. MMMM, YYYY HH:mm' }, calendar: { sameDay: '[Í dag kl.] LT', nextDay: '[Í morgin kl.] LT', nextWeek: 'dddd [kl.] LT', lastDay: '[Í gjár kl.] LT', lastWeek: '[síðstu] dddd [kl] LT', sameElse: 'L' }, relativeTime: { future: 'um %s', past: '%s síðani', s: 'fá sekund', m: 'ein minutt', mm: '%d minuttir', h: 'ein tími', hh: '%d tímar', d: 'ein dagur', dd: '%d dagar', M: 'ein mánaði', MM: '%d mánaðir', y: 'eitt ár', yy: '%d ár' }, ordinalParse: /\d{1,2}\./, ordinal: '%d.', week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); var fr_ca = moment__default.defineLocale('fr-ca', { months: 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_'), monthsShort: 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split('_'), monthsParseExact: true, weekdays: 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'), weekdaysShort: 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'), weekdaysMin: 'Di_Lu_Ma_Me_Je_Ve_Sa'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'YYYY-MM-DD', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'dddd D MMMM YYYY HH:mm' }, calendar: { sameDay: '[Aujourd\'hui à] LT', nextDay: '[Demain à] LT', nextWeek: 'dddd [à] LT', lastDay: '[Hier à] LT', lastWeek: 'dddd [dernier à] LT', sameElse: 'L' }, relativeTime: { future: 'dans %s', past: 'il y a %s', s: 'quelques secondes', m: 'une minute', mm: '%d minutes', h: 'une heure', hh: '%d heures', d: 'un jour', dd: '%d jours', M: 'un mois', MM: '%d mois', y: 'un an', yy: '%d ans' }, ordinalParse: /\d{1,2}(er|e)/, ordinal: function (number) { return number + (number === 1 ? 'er' : 'e'); } }); var fr_ch = moment__default.defineLocale('fr-ch', { months: 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_'), monthsShort: 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split('_'), monthsParseExact: true, weekdays: 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'), weekdaysShort: 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'), weekdaysMin: 'Di_Lu_Ma_Me_Je_Ve_Sa'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD.MM.YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'dddd D MMMM YYYY HH:mm' }, calendar: { sameDay: '[Aujourd\'hui à] LT', nextDay: '[Demain à] LT', nextWeek: 'dddd [à] LT', lastDay: '[Hier à] LT', lastWeek: 'dddd [dernier à] LT', sameElse: 'L' }, relativeTime: { future: 'dans %s', past: 'il y a %s', s: 'quelques secondes', m: 'une minute', mm: '%d minutes', h: 'une heure', hh: '%d heures', d: 'un jour', dd: '%d jours', M: 'un mois', MM: '%d mois', y: 'un an', yy: '%d ans' }, ordinalParse: /\d{1,2}(er|e)/, ordinal: function (number) { return number + (number === 1 ? 'er' : 'e'); }, week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); var fr = moment__default.defineLocale('fr', { months: 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_'), monthsShort: 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split('_'), monthsParseExact: true, weekdays: 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'), weekdaysShort: 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'), weekdaysMin: 'Di_Lu_Ma_Me_Je_Ve_Sa'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'dddd D MMMM YYYY HH:mm' }, calendar: { sameDay: '[Aujourd\'hui à] LT', nextDay: '[Demain à] LT', nextWeek: 'dddd [à] LT', lastDay: '[Hier à] LT', lastWeek: 'dddd [dernier à] LT', sameElse: 'L' }, relativeTime: { future: 'dans %s', past: 'il y a %s', s: 'quelques secondes', m: 'une minute', mm: '%d minutes', h: 'une heure', hh: '%d heures', d: 'un jour', dd: '%d jours', M: 'un mois', MM: '%d mois', y: 'un an', yy: '%d ans' }, ordinalParse: /\d{1,2}(er|)/, ordinal: function (number) { return number + (number === 1 ? 'er' : ''); }, week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); var fy__monthsShortWithDots = 'jan._feb._mrt._apr._mai_jun._jul._aug._sep._okt._nov._des.'.split('_'), fy__monthsShortWithoutDots = 'jan_feb_mrt_apr_mai_jun_jul_aug_sep_okt_nov_des'.split('_'); var fy = moment__default.defineLocale('fy', { months: 'jannewaris_febrewaris_maart_april_maaie_juny_july_augustus_septimber_oktober_novimber_desimber'.split('_'), monthsShort: function (m, format) { if (/-MMM-/.test(format)) { return fy__monthsShortWithoutDots[m.month()]; } else { return fy__monthsShortWithDots[m.month()]; } }, monthsParseExact: true, weekdays: 'snein_moandei_tiisdei_woansdei_tongersdei_freed_sneon'.split('_'), weekdaysShort: 'si._mo._ti._wo._to._fr._so.'.split('_'), weekdaysMin: 'Si_Mo_Ti_Wo_To_Fr_So'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD-MM-YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'dddd D MMMM YYYY HH:mm' }, calendar: { sameDay: '[hjoed om] LT', nextDay: '[moarn om] LT', nextWeek: 'dddd [om] LT', lastDay: '[juster om] LT', lastWeek: '[ôfrûne] dddd [om] LT', sameElse: 'L' }, relativeTime: { future: 'oer %s', past: '%s lyn', s: 'in pear sekonden', m: 'ien minút', mm: '%d minuten', h: 'ien oere', hh: '%d oeren', d: 'ien dei', dd: '%d dagen', M: 'ien moanne', MM: '%d moannen', y: 'ien jier', yy: '%d jierren' }, ordinalParse: /\d{1,2}(ste|de)/, ordinal: function (number) { return number + ((number === 1 || number === 8 || number >= 20) ? 'ste' : 'de'); }, week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); var gd__months = [ 'Am Faoilleach', 'An Gearran', 'Am Màrt', 'An Giblean', 'An Cèitean', 'An t-Ògmhios', 'An t-Iuchar', 'An Lùnastal', 'An t-Sultain', 'An Dàmhair', 'An t-Samhain', 'An Dùbhlachd' ]; var gd__monthsShort = ['Faoi', 'Gear', 'Màrt', 'Gibl', 'Cèit', 'Ògmh', 'Iuch', 'Lùn', 'Sult', 'Dàmh', 'Samh', 'Dùbh']; var gd__weekdays = ['Didòmhnaich', 'Diluain', 'Dimàirt', 'Diciadain', 'Diardaoin', 'Dihaoine', 'Disathairne']; var weekdaysShort = ['Did', 'Dil', 'Dim', 'Dic', 'Dia', 'Dih', 'Dis']; var weekdaysMin = ['Dò', 'Lu', 'Mà', 'Ci', 'Ar', 'Ha', 'Sa']; var gd = moment__default.defineLocale('gd', { months: gd__months, monthsShort: gd__monthsShort, monthsParseExact: true, weekdays: gd__weekdays, weekdaysShort: weekdaysShort, weekdaysMin: weekdaysMin, longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'dddd, D MMMM YYYY HH:mm' }, calendar: { sameDay: '[An-diugh aig] LT', nextDay: '[A-màireach aig] LT', nextWeek: 'dddd [aig] LT', lastDay: '[An-dè aig] LT', lastWeek: 'dddd [seo chaidh] [aig] LT', sameElse: 'L' }, relativeTime: { future: 'ann an %s', past: 'bho chionn %s', s: 'beagan diogan', m: 'mionaid', mm: '%d mionaidean', h: 'uair', hh: '%d uairean', d: 'latha', dd: '%d latha', M: 'mìos', MM: '%d mìosan', y: 'bliadhna', yy: '%d bliadhna' }, ordinalParse: /\d{1,2}(d|na|mh)/, ordinal: function (number) { var output = number === 1 ? 'd' : number % 10 === 2 ? 'na' : 'mh'; return number + output; }, week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); var gl = moment__default.defineLocale('gl', { months: 'Xaneiro_Febreiro_Marzo_Abril_Maio_Xuño_Xullo_Agosto_Setembro_Outubro_Novembro_Decembro'.split('_'), monthsShort: 'Xan._Feb._Mar._Abr._Mai._Xuñ._Xul._Ago._Set._Out._Nov._Dec.'.split('_'), monthsParseExact: true, weekdays: 'Domingo_Luns_Martes_Mércores_Xoves_Venres_Sábado'.split('_'), weekdaysShort: 'Dom._Lun._Mar._Mér._Xov._Ven._Sáb.'.split('_'), weekdaysMin: 'Do_Lu_Ma_Mé_Xo_Ve_Sá'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'H:mm', LTS: 'H:mm:ss', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY H:mm', LLLL: 'dddd D MMMM YYYY H:mm' }, calendar: { sameDay: function () { return '[hoxe ' + ((this.hours() !== 1) ? 'ás' : 'á') + '] LT'; }, nextDay: function () { return '[mañá ' + ((this.hours() !== 1) ? 'ás' : 'á') + '] LT'; }, nextWeek: function () { return 'dddd [' + ((this.hours() !== 1) ? 'ás' : 'a') + '] LT'; }, lastDay: function () { return '[onte ' + ((this.hours() !== 1) ? 'á' : 'a') + '] LT'; }, lastWeek: function () { return '[o] dddd [pasado ' + ((this.hours() !== 1) ? 'ás' : 'a') + '] LT'; }, sameElse: 'L' }, relativeTime: { future: function (str) { if (str === 'uns segundos') { return 'nuns segundos'; } return 'en ' + str; }, past: 'hai %s', s: 'uns segundos', m: 'un minuto', mm: '%d minutos', h: 'unha hora', hh: '%d horas', d: 'un día', dd: '%d días', M: 'un mes', MM: '%d meses', y: 'un ano', yy: '%d anos' }, ordinalParse: /\d{1,2}º/, ordinal: '%dº', week: { dow: 1, // Monday is the first day of the week. doy: 7 // The week that contains Jan 1st is the first week of the year. } }); var he = moment__default.defineLocale('he', { months: 'ינואר_פברואר_מרץ_אפריל_מאי_יוני_יולי_אוגוסט_ספטמבר_אוקטובר_נובמבר_דצמבר'.split('_'), monthsShort: 'ינו׳_פבר׳_מרץ_אפר׳_מאי_יוני_יולי_אוג׳_ספט׳_אוק׳_נוב׳_דצמ׳'.split('_'), weekdays: 'ראשון_שני_שלישי_רביעי_חמישי_שישי_שבת'.split('_'), weekdaysShort: 'א׳_ב׳_ג׳_ד׳_ה׳_ו׳_ש׳'.split('_'), weekdaysMin: 'א_ב_ג_ד_ה_ו_ש'.split('_'), longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD/MM/YYYY', LL: 'D [ב]MMMM YYYY', LLL: 'D [ב]MMMM YYYY HH:mm', LLLL: 'dddd, D [ב]MMMM YYYY HH:mm', l: 'D/M/YYYY', ll: 'D MMM YYYY', lll: 'D MMM YYYY HH:mm', llll: 'ddd, D MMM YYYY HH:mm' }, calendar: { sameDay: '[היום ב־]LT', nextDay: '[מחר ב־]LT', nextWeek: 'dddd [בשעה] LT', lastDay: '[אתמול ב־]LT', lastWeek: '[ביום] dddd [האחרון בשעה] LT', sameElse: 'L' }, relativeTime: { future: 'בעוד %s', past: 'לפני %s', s: 'מספר שניות', m: 'דקה', mm: '%d דקות', h: 'שעה', hh: function (number) { if (number === 2) { return 'שעתיים'; } return number + ' שעות'; }, d: 'יום', dd: function (number) { if (number === 2) { return 'יומיים'; } return number + ' ימים'; }, M: 'חודש', MM: function (number) { if (number === 2) { return 'חודשיים'; } return number + ' חודשים'; }, y: 'שנה', yy: function (number) { if (number === 2) { return 'שנתיים'; } else if (number % 10 === 0 && number !== 10) { return number + ' שנה'; } return number + ' שנים'; } }, meridiemParse: /אחה"צ|לפנה"צ|אחרי הצהריים|לפני הצהריים|לפנות בוקר|בבוקר|בערב/i, isPM: function (input) { return /^(אחה"צ|אחרי הצהריים|בערב)$/.test(input); }, meridiem: function (hour, minute, isLower) { if (hour < 5) { return 'לפנות בוקר'; } else if (hour < 10) { return 'בבוקר'; } else if (hour < 12) { return isLower ? 'לפנה"צ' : 'לפני הצהריים'; } else if (hour < 18) { return isLower ? 'אחה"צ' : 'אחרי הצהריים'; } else { return 'בערב'; } } }); var hi__symbolMap = { '1': '१', '2': '२', '3': '३', '4': '४', '5': '५', '6': '६', '7': '७', '8': '८', '9': '९', '0': '०' }, hi__numberMap = { '१': '1', '२': '2', '३': '3', '४': '4', '५': '5', '६': '6', '७': '7', '८': '8', '९': '9', '०': '0' }; var hi = moment__default.defineLocale('hi', { months: 'जनवरी_फ़रवरी_मार्च_अप्रैल_मई_जून_जुलाई_अगस्त_सितम्बर_अक्टूबर_नवम्बर_दिसम्बर'.split('_'), monthsShort: 'जन._फ़र._मार्च_अप्रै._मई_जून_जुल._अग._सित._अक्टू._नव._दिस.'.split('_'), monthsParseExact: true, weekdays: 'रविवार_सोमवार_मंगलवार_बुधवार_गुरूवार_शुक्रवार_शनिवार'.split('_'), weekdaysShort: 'रवि_सोम_मंगल_बुध_गुरू_शुक्र_शनि'.split('_'), weekdaysMin: 'र_सो_मं_बु_गु_शु_श'.split('_'), longDateFormat: { LT: 'A h:mm बजे', LTS: 'A h:mm:ss बजे', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY, A h:mm बजे', LLLL: 'dddd, D MMMM YYYY, A h:mm बजे' }, calendar: { sameDay: '[आज] LT', nextDay: '[कल] LT', nextWeek: 'dddd, LT', lastDay: '[कल] LT', lastWeek: '[पिछले] dddd, LT', sameElse: 'L' }, relativeTime: { future: '%s में', past: '%s पहले', s: 'कुछ ही क्षण', m: 'एक मिनट', mm: '%d मिनट', h: 'एक घंटा', hh: '%d घंटे', d: 'एक दिन', dd: '%d दिन', M: 'एक महीने', MM: '%d महीने', y: 'एक वर्ष', yy: '%d वर्ष' }, preparse: function (string) { return string.replace(/[१२३४५६७८९०]/g, function (match) { return hi__numberMap[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return hi__symbolMap[match]; }); }, // Hindi notation for meridiems are quite fuzzy in practice. While there exists // a rigid notion of a 'Pahar' it is not used as rigidly in modern Hindi. meridiemParse: /रात|सुबह|दोपहर|शाम/, meridiemHour: function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === 'रात') { return hour < 4 ? hour : hour + 12; } else if (meridiem === 'सुबह') { return hour; } else if (meridiem === 'दोपहर') { return hour >= 10 ? hour : hour + 12; } else if (meridiem === 'शाम') { return hour + 12; } }, meridiem: function (hour, minute, isLower) { if (hour < 4) { return 'रात'; } else if (hour < 10) { return 'सुबह'; } else if (hour < 17) { return 'दोपहर'; } else if (hour < 20) { return 'शाम'; } else { return 'रात'; } }, week: { dow: 0, // Sunday is the first day of the week. doy: 6 // The week that contains Jan 1st is the first week of the year. } }); function hr__translate(number, withoutSuffix, key) { var result = number + ' '; switch (key) { case 'm': return withoutSuffix ? 'jedna minuta' : 'jedne minute'; case 'mm': if (number === 1) { result += 'minuta'; } else if (number === 2 || number === 3 || number === 4) { result += 'minute'; } else { result += 'minuta'; } return result; case 'h': return withoutSuffix ? 'jedan sat' : 'jednog sata'; case 'hh': if (number === 1) { result += 'sat'; } else if (number === 2 || number === 3 || number === 4) { result += 'sata'; } else { result += 'sati'; } return result; case 'dd': if (number === 1) { result += 'dan'; } else { result += 'dana'; } return result; case 'MM': if (number === 1) { result += 'mjesec'; } else if (number === 2 || number === 3 || number === 4) { result += 'mjeseca'; } else { result += 'mjeseci'; } return result; case 'yy': if (number === 1) { result += 'godina'; } else if (number === 2 || number === 3 || number === 4) { result += 'godine'; } else { result += 'godina'; } return result; } } var hr = moment__default.defineLocale('hr', { months: { format: 'siječnja_veljače_ožujka_travnja_svibnja_lipnja_srpnja_kolovoza_rujna_listopada_studenoga_prosinca'.split('_'), standalone: 'siječanj_veljača_ožujak_travanj_svibanj_lipanj_srpanj_kolovoz_rujan_listopad_studeni_prosinac'.split('_') }, monthsShort: 'sij._velj._ožu._tra._svi._lip._srp._kol._ruj._lis._stu._pro.'.split('_'), monthsParseExact: true, weekdays: 'nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota'.split('_'), weekdaysShort: 'ned._pon._uto._sri._čet._pet._sub.'.split('_'), weekdaysMin: 'ne_po_ut_sr_če_pe_su'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'H:mm', LTS: 'H:mm:ss', L: 'DD. MM. YYYY', LL: 'D. MMMM YYYY', LLL: 'D. MMMM YYYY H:mm', LLLL: 'dddd, D. MMMM YYYY H:mm' }, calendar: { sameDay: '[danas u] LT', nextDay: '[sutra u] LT', nextWeek: function () { switch (this.day()) { case 0: return '[u] [nedjelju] [u] LT'; case 3: return '[u] [srijedu] [u] LT'; case 6: return '[u] [subotu] [u] LT'; case 1: case 2: case 4: case 5: return '[u] dddd [u] LT'; } }, lastDay: '[jučer u] LT', lastWeek: function () { switch (this.day()) { case 0: case 3: return '[prošlu] dddd [u] LT'; case 6: return '[prošle] [subote] [u] LT'; case 1: case 2: case 4: case 5: return '[prošli] dddd [u] LT'; } }, sameElse: 'L' }, relativeTime: { future: 'za %s', past: 'prije %s', s: 'par sekundi', m: hr__translate, mm: hr__translate, h: hr__translate, hh: hr__translate, d: 'dan', dd: hr__translate, M: 'mjesec', MM: hr__translate, y: 'godinu', yy: hr__translate }, ordinalParse: /\d{1,2}\./, ordinal: '%d.', week: { dow: 1, // Monday is the first day of the week. doy: 7 // The week that contains Jan 1st is the first week of the year. } }); var weekEndings = 'vasárnap hétfőn kedden szerdán csütörtökön pénteken szombaton'.split(' '); function hu__translate(number, withoutSuffix, key, isFuture) { var num = number, suffix; switch (key) { case 's': return (isFuture || withoutSuffix) ? 'néhány másodperc' : 'néhány másodperce'; case 'm': return 'egy' + (isFuture || withoutSuffix ? ' perc' : ' perce'); case 'mm': return num + (isFuture || withoutSuffix ? ' perc' : ' perce'); case 'h': return 'egy' + (isFuture || withoutSuffix ? ' óra' : ' órája'); case 'hh': return num + (isFuture || withoutSuffix ? ' óra' : ' órája'); case 'd': return 'egy' + (isFuture || withoutSuffix ? ' nap' : ' napja'); case 'dd': return num + (isFuture || withoutSuffix ? ' nap' : ' napja'); case 'M': return 'egy' + (isFuture || withoutSuffix ? ' hónap' : ' hónapja'); case 'MM': return num + (isFuture || withoutSuffix ? ' hónap' : ' hónapja'); case 'y': return 'egy' + (isFuture || withoutSuffix ? ' év' : ' éve'); case 'yy': return num + (isFuture || withoutSuffix ? ' év' : ' éve'); } return ''; } function week(isFuture) { return (isFuture ? '' : '[múlt] ') + '[' + weekEndings[this.day()] + '] LT[-kor]'; } var hu = moment__default.defineLocale('hu', { months: 'január_február_március_április_május_június_július_augusztus_szeptember_október_november_december'.split('_'), monthsShort: 'jan_feb_márc_ápr_máj_jún_júl_aug_szept_okt_nov_dec'.split('_'), weekdays: 'vasárnap_hétfő_kedd_szerda_csütörtök_péntek_szombat'.split('_'), weekdaysShort: 'vas_hét_kedd_sze_csüt_pén_szo'.split('_'), weekdaysMin: 'v_h_k_sze_cs_p_szo'.split('_'), longDateFormat: { LT: 'H:mm', LTS: 'H:mm:ss', L: 'YYYY.MM.DD.', LL: 'YYYY. MMMM D.', LLL: 'YYYY. MMMM D. H:mm', LLLL: 'YYYY. MMMM D., dddd H:mm' }, meridiemParse: /de|du/i, isPM: function (input) { return input.charAt(1).toLowerCase() === 'u'; }, meridiem: function (hours, minutes, isLower) { if (hours < 12) { return isLower === true ? 'de' : 'DE'; } else { return isLower === true ? 'du' : 'DU'; } }, calendar: { sameDay: '[ma] LT[-kor]', nextDay: '[holnap] LT[-kor]', nextWeek: function () { return week.call(this, true); }, lastDay: '[tegnap] LT[-kor]', lastWeek: function () { return week.call(this, false); }, sameElse: 'L' }, relativeTime: { future: '%s múlva', past: '%s', s: hu__translate, m: hu__translate, mm: hu__translate, h: hu__translate, hh: hu__translate, d: hu__translate, dd: hu__translate, M: hu__translate, MM: hu__translate, y: hu__translate, yy: hu__translate }, ordinalParse: /\d{1,2}\./, ordinal: '%d.', week: { dow: 1, // Monday is the first day of the week. doy: 7 // The week that contains Jan 1st is the first week of the year. } }); var hy_am = moment__default.defineLocale('hy-am', { months: { format: 'հունվարի_փետրվարի_մարտի_ապրիլի_մայիսի_հունիսի_հուլիսի_օգոստոսի_սեպտեմբերի_հոկտեմբերի_նոյեմբերի_դեկտեմբերի'.split('_'), standalone: 'հունվար_փետրվար_մարտ_ապրիլ_մայիս_հունիս_հուլիս_օգոստոս_սեպտեմբեր_հոկտեմբեր_նոյեմբեր_դեկտեմբեր'.split('_') }, monthsShort: 'հնվ_փտր_մրտ_ապր_մյս_հնս_հլս_օգս_սպտ_հկտ_նմբ_դկտ'.split('_'), weekdays: 'կիրակի_երկուշաբթի_երեքշաբթի_չորեքշաբթի_հինգշաբթի_ուրբաթ_շաբաթ'.split('_'), weekdaysShort: 'կրկ_երկ_երք_չրք_հնգ_ուրբ_շբթ'.split('_'), weekdaysMin: 'կրկ_երկ_երք_չրք_հնգ_ուրբ_շբթ'.split('_'), longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD.MM.YYYY', LL: 'D MMMM YYYY թ.', LLL: 'D MMMM YYYY թ., HH:mm', LLLL: 'dddd, D MMMM YYYY թ., HH:mm' }, calendar: { sameDay: '[այսօր] LT', nextDay: '[վաղը] LT', lastDay: '[երեկ] LT', nextWeek: function () { return 'dddd [օրը ժամը] LT'; }, lastWeek: function () { return '[անցած] dddd [օրը ժամը] LT'; }, sameElse: 'L' }, relativeTime: { future: '%s հետո', past: '%s առաջ', s: 'մի քանի վայրկյան', m: 'րոպե', mm: '%d րոպե', h: 'ժամ', hh: '%d ժամ', d: 'օր', dd: '%d օր', M: 'ամիս', MM: '%d ամիս', y: 'տարի', yy: '%d տարի' }, meridiemParse: /գիշերվա|առավոտվա|ցերեկվա|երեկոյան/, isPM: function (input) { return /^(ցերեկվա|երեկոյան)$/.test(input); }, meridiem: function (hour) { if (hour < 4) { return 'գիշերվա'; } else if (hour < 12) { return 'առավոտվա'; } else if (hour < 17) { return 'ցերեկվա'; } else { return 'երեկոյան'; } }, ordinalParse: /\d{1,2}|\d{1,2}-(ին|րդ)/, ordinal: function (number, period) { switch (period) { case 'DDD': case 'w': case 'W': case 'DDDo': if (number === 1) { return number + '-ին'; } return number + '-րդ'; default: return number; } }, week: { dow: 1, // Monday is the first day of the week. doy: 7 // The week that contains Jan 1st is the first week of the year. } }); var id = moment__default.defineLocale('id', { months: 'Januari_Februari_Maret_April_Mei_Juni_Juli_Agustus_September_Oktober_November_Desember'.split('_'), monthsShort: 'Jan_Feb_Mar_Apr_Mei_Jun_Jul_Ags_Sep_Okt_Nov_Des'.split('_'), weekdays: 'Minggu_Senin_Selasa_Rabu_Kamis_Jumat_Sabtu'.split('_'), weekdaysShort: 'Min_Sen_Sel_Rab_Kam_Jum_Sab'.split('_'), weekdaysMin: 'Mg_Sn_Sl_Rb_Km_Jm_Sb'.split('_'), longDateFormat: { LT: 'HH.mm', LTS: 'HH.mm.ss', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY [pukul] HH.mm', LLLL: 'dddd, D MMMM YYYY [pukul] HH.mm' }, meridiemParse: /pagi|siang|sore|malam/, meridiemHour: function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === 'pagi') { return hour; } else if (meridiem === 'siang') { return hour >= 11 ? hour : hour + 12; } else if (meridiem === 'sore' || meridiem === 'malam') { return hour + 12; } }, meridiem: function (hours, minutes, isLower) { if (hours < 11) { return 'pagi'; } else if (hours < 15) { return 'siang'; } else if (hours < 19) { return 'sore'; } else { return 'malam'; } }, calendar: { sameDay: '[Hari ini pukul] LT', nextDay: '[Besok pukul] LT', nextWeek: 'dddd [pukul] LT', lastDay: '[Kemarin pukul] LT', lastWeek: 'dddd [lalu pukul] LT', sameElse: 'L' }, relativeTime: { future: 'dalam %s', past: '%s yang lalu', s: 'beberapa detik', m: 'semenit', mm: '%d menit', h: 'sejam', hh: '%d jam', d: 'sehari', dd: '%d hari', M: 'sebulan', MM: '%d bulan', y: 'setahun', yy: '%d tahun' }, week: { dow: 1, // Monday is the first day of the week. doy: 7 // The week that contains Jan 1st is the first week of the year. } }); function is__plural(n) { if (n % 100 === 11) { return true; } else if (n % 10 === 1) { return false; } return true; } function is__translate(number, withoutSuffix, key, isFuture) { var result = number + ' '; switch (key) { case 's': return withoutSuffix || isFuture ? 'nokkrar sekúndur' : 'nokkrum sekúndum'; case 'm': return withoutSuffix ? 'mínúta' : 'mínútu'; case 'mm': if (is__plural(number)) { return result + (withoutSuffix || isFuture ? 'mínútur' : 'mínútum'); } else if (withoutSuffix) { return result + 'mínúta'; } return result + 'mínútu'; case 'hh': if (is__plural(number)) { return result + (withoutSuffix || isFuture ? 'klukkustundir' : 'klukkustundum'); } return result + 'klukkustund'; case 'd': if (withoutSuffix) { return 'dagur'; } return isFuture ? 'dag' : 'degi'; case 'dd': if (is__plural(number)) { if (withoutSuffix) { return result + 'dagar'; } return result + (isFuture ? 'daga' : 'dögum'); } else if (withoutSuffix) { return result + 'dagur'; } return result + (isFuture ? 'dag' : 'degi'); case 'M': if (withoutSuffix) { return 'mánuður'; } return isFuture ? 'mánuð' : 'mánuði'; case 'MM': if (is__plural(number)) { if (withoutSuffix) { return result + 'mánuðir'; } return result + (isFuture ? 'mánuði' : 'mánuðum'); } else if (withoutSuffix) { return result + 'mánuður'; } return result + (isFuture ? 'mánuð' : 'mánuði'); case 'y': return withoutSuffix || isFuture ? 'ár' : 'ári'; case 'yy': if (is__plural(number)) { return result + (withoutSuffix || isFuture ? 'ár' : 'árum'); } return result + (withoutSuffix || isFuture ? 'ár' : 'ári'); } } var is = moment__default.defineLocale('is', { months: 'janúar_febrúar_mars_apríl_maí_júní_júlí_ágúst_september_október_nóvember_desember'.split('_'), monthsShort: 'jan_feb_mar_apr_maí_jún_júl_ágú_sep_okt_nóv_des'.split('_'), weekdays: 'sunnudagur_mánudagur_þriðjudagur_miðvikudagur_fimmtudagur_föstudagur_laugardagur'.split('_'), weekdaysShort: 'sun_mán_þri_mið_fim_fös_lau'.split('_'), weekdaysMin: 'Su_Má_Þr_Mi_Fi_Fö_La'.split('_'), longDateFormat: { LT: 'H:mm', LTS: 'H:mm:ss', L: 'DD.MM.YYYY', LL: 'D. MMMM YYYY', LLL: 'D. MMMM YYYY [kl.] H:mm', LLLL: 'dddd, D. MMMM YYYY [kl.] H:mm' }, calendar: { sameDay: '[í dag kl.] LT', nextDay: '[á morgun kl.] LT', nextWeek: 'dddd [kl.] LT', lastDay: '[í gær kl.] LT', lastWeek: '[síðasta] dddd [kl.] LT', sameElse: 'L' }, relativeTime: { future: 'eftir %s', past: 'fyrir %s síðan', s: is__translate, m: is__translate, mm: is__translate, h: 'klukkustund', hh: is__translate, d: is__translate, dd: is__translate, M: is__translate, MM: is__translate, y: is__translate, yy: is__translate }, ordinalParse: /\d{1,2}\./, ordinal: '%d.', week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); var it = moment__default.defineLocale('it', { months: 'gennaio_febbraio_marzo_aprile_maggio_giugno_luglio_agosto_settembre_ottobre_novembre_dicembre'.split('_'), monthsShort: 'gen_feb_mar_apr_mag_giu_lug_ago_set_ott_nov_dic'.split('_'), weekdays: 'Domenica_Lunedì_Martedì_Mercoledì_Giovedì_Venerdì_Sabato'.split('_'), weekdaysShort: 'Dom_Lun_Mar_Mer_Gio_Ven_Sab'.split('_'), weekdaysMin: 'Do_Lu_Ma_Me_Gi_Ve_Sa'.split('_'), longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'dddd, D MMMM YYYY HH:mm' }, calendar: { sameDay: '[Oggi alle] LT', nextDay: '[Domani alle] LT', nextWeek: 'dddd [alle] LT', lastDay: '[Ieri alle] LT', lastWeek: function () { switch (this.day()) { case 0: return '[la scorsa] dddd [alle] LT'; default: return '[lo scorso] dddd [alle] LT'; } }, sameElse: 'L' }, relativeTime: { future: function (s) { return ((/^[0-9].+$/).test(s) ? 'tra' : 'in') + ' ' + s; }, past: '%s fa', s: 'alcuni secondi', m: 'un minuto', mm: '%d minuti', h: 'un\'ora', hh: '%d ore', d: 'un giorno', dd: '%d giorni', M: 'un mese', MM: '%d mesi', y: 'un anno', yy: '%d anni' }, ordinalParse: /\d{1,2}º/, ordinal: '%dº', week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); var ja = moment__default.defineLocale('ja', { months: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), weekdays: '日曜日_月曜日_火曜日_水曜日_木曜日_金曜日_土曜日'.split('_'), weekdaysShort: '日_月_火_水_木_金_土'.split('_'), weekdaysMin: '日_月_火_水_木_金_土'.split('_'), longDateFormat: { LT: 'Ah時m分', LTS: 'Ah時m分s秒', L: 'YYYY/MM/DD', LL: 'YYYY年M月D日', LLL: 'YYYY年M月D日Ah時m分', LLLL: 'YYYY年M月D日Ah時m分 dddd' }, meridiemParse: /午前|午後/i, isPM: function (input) { return input === '午後'; }, meridiem: function (hour, minute, isLower) { if (hour < 12) { return '午前'; } else { return '午後'; } }, calendar: { sameDay: '[今日] LT', nextDay: '[明日] LT', nextWeek: '[来週]dddd LT', lastDay: '[昨日] LT', lastWeek: '[前週]dddd LT', sameElse: 'L' }, ordinalParse: /\d{1,2}日/, ordinal: function (number, period) { switch (period) { case 'd': case 'D': case 'DDD': return number + '日'; default: return number; } }, relativeTime: { future: '%s後', past: '%s前', s: '数秒', m: '1分', mm: '%d分', h: '1時間', hh: '%d時間', d: '1日', dd: '%d日', M: '1ヶ月', MM: '%dヶ月', y: '1年', yy: '%d年' } }); var jv = moment__default.defineLocale('jv', { months: 'Januari_Februari_Maret_April_Mei_Juni_Juli_Agustus_September_Oktober_Nopember_Desember'.split('_'), monthsShort: 'Jan_Feb_Mar_Apr_Mei_Jun_Jul_Ags_Sep_Okt_Nop_Des'.split('_'), weekdays: 'Minggu_Senen_Seloso_Rebu_Kemis_Jemuwah_Septu'.split('_'), weekdaysShort: 'Min_Sen_Sel_Reb_Kem_Jem_Sep'.split('_'), weekdaysMin: 'Mg_Sn_Sl_Rb_Km_Jm_Sp'.split('_'), longDateFormat: { LT: 'HH.mm', LTS: 'HH.mm.ss', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY [pukul] HH.mm', LLLL: 'dddd, D MMMM YYYY [pukul] HH.mm' }, meridiemParse: /enjing|siyang|sonten|ndalu/, meridiemHour: function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === 'enjing') { return hour; } else if (meridiem === 'siyang') { return hour >= 11 ? hour : hour + 12; } else if (meridiem === 'sonten' || meridiem === 'ndalu') { return hour + 12; } }, meridiem: function (hours, minutes, isLower) { if (hours < 11) { return 'enjing'; } else if (hours < 15) { return 'siyang'; } else if (hours < 19) { return 'sonten'; } else { return 'ndalu'; } }, calendar: { sameDay: '[Dinten puniko pukul] LT', nextDay: '[Mbenjang pukul] LT', nextWeek: 'dddd [pukul] LT', lastDay: '[Kala wingi pukul] LT', lastWeek: 'dddd [kepengker pukul] LT', sameElse: 'L' }, relativeTime: { future: 'wonten ing %s', past: '%s ingkang kepengker', s: 'sawetawis detik', m: 'setunggal menit', mm: '%d menit', h: 'setunggal jam', hh: '%d jam', d: 'sedinten', dd: '%d dinten', M: 'sewulan', MM: '%d wulan', y: 'setaun', yy: '%d taun' }, week: { dow: 1, // Monday is the first day of the week. doy: 7 // The week that contains Jan 1st is the first week of the year. } }); var ka = moment__default.defineLocale('ka', { months: { standalone: 'იანვარი_თებერვალი_მარტი_აპრილი_მაისი_ივნისი_ივლისი_აგვისტო_სექტემბერი_ოქტომბერი_ნოემბერი_დეკემბერი'.split('_'), format: 'იანვარს_თებერვალს_მარტს_აპრილის_მაისს_ივნისს_ივლისს_აგვისტს_სექტემბერს_ოქტომბერს_ნოემბერს_დეკემბერს'.split('_') }, monthsShort: 'იან_თებ_მარ_აპრ_მაი_ივნ_ივლ_აგვ_სექ_ოქტ_ნოე_დეკ'.split('_'), weekdays: { standalone: 'კვირა_ორშაბათი_სამშაბათი_ოთხშაბათი_ხუთშაბათი_პარასკევი_შაბათი'.split('_'), format: 'კვირას_ორშაბათს_სამშაბათს_ოთხშაბათს_ხუთშაბათს_პარასკევს_შაბათს'.split('_'), isFormat: /(წინა|შემდეგ)/ }, weekdaysShort: 'კვი_ორშ_სამ_ოთხ_ხუთ_პარ_შაბ'.split('_'), weekdaysMin: 'კვ_ორ_სა_ოთ_ხუ_პა_შა'.split('_'), longDateFormat: { LT: 'h:mm A', LTS: 'h:mm:ss A', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY h:mm A', LLLL: 'dddd, D MMMM YYYY h:mm A' }, calendar: { sameDay: '[დღეს] LT[-ზე]', nextDay: '[ხვალ] LT[-ზე]', lastDay: '[გუშინ] LT[-ზე]', nextWeek: '[შემდეგ] dddd LT[-ზე]', lastWeek: '[წინა] dddd LT-ზე', sameElse: 'L' }, relativeTime: { future: function (s) { return (/(წამი|წუთი|საათი|წელი)/).test(s) ? s.replace(/ი$/, 'ში') : s + 'ში'; }, past: function (s) { if ((/(წამი|წუთი|საათი|დღე|თვე)/).test(s)) { return s.replace(/(ი|ე)$/, 'ის წინ'); } if ((/წელი/).test(s)) { return s.replace(/წელი$/, 'წლის წინ'); } }, s: 'რამდენიმე წამი', m: 'წუთი', mm: '%d წუთი', h: 'საათი', hh: '%d საათი', d: 'დღე', dd: '%d დღე', M: 'თვე', MM: '%d თვე', y: 'წელი', yy: '%d წელი' }, ordinalParse: /0|1-ლი|მე-\d{1,2}|\d{1,2}-ე/, ordinal: function (number) { if (number === 0) { return number; } if (number === 1) { return number + '-ლი'; } if ((number < 20) || (number <= 100 && (number % 20 === 0)) || (number % 100 === 0)) { return 'მე-' + number; } return number + '-ე'; }, week: { dow: 1, doy: 7 } }); var kk__suffixes = { 0: '-ші', 1: '-ші', 2: '-ші', 3: '-ші', 4: '-ші', 5: '-ші', 6: '-шы', 7: '-ші', 8: '-ші', 9: '-шы', 10: '-шы', 20: '-шы', 30: '-шы', 40: '-шы', 50: '-ші', 60: '-шы', 70: '-ші', 80: '-ші', 90: '-шы', 100: '-ші' }; var kk = moment__default.defineLocale('kk', { months: 'қаңтар_ақпан_наурыз_сәуір_мамыр_маусым_шілде_тамыз_қыркүйек_қазан_қараша_желтоқсан'.split('_'), monthsShort: 'қаң_ақп_нау_сәу_мам_мау_шіл_там_қыр_қаз_қар_жел'.split('_'), weekdays: 'жексенбі_дүйсенбі_сейсенбі_сәрсенбі_бейсенбі_жұма_сенбі'.split('_'), weekdaysShort: 'жек_дүй_сей_сәр_бей_жұм_сен'.split('_'), weekdaysMin: 'жк_дй_сй_ср_бй_жм_сн'.split('_'), longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD.MM.YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'dddd, D MMMM YYYY HH:mm' }, calendar: { sameDay: '[Бүгін сағат] LT', nextDay: '[Ертең сағат] LT', nextWeek: 'dddd [сағат] LT', lastDay: '[Кеше сағат] LT', lastWeek: '[Өткен аптаның] dddd [сағат] LT', sameElse: 'L' }, relativeTime: { future: '%s ішінде', past: '%s бұрын', s: 'бірнеше секунд', m: 'бір минут', mm: '%d минут', h: 'бір сағат', hh: '%d сағат', d: 'бір күн', dd: '%d күн', M: 'бір ай', MM: '%d ай', y: 'бір жыл', yy: '%d жыл' }, ordinalParse: /\d{1,2}-(ші|шы)/, ordinal: function (number) { var a = number % 10, b = number >= 100 ? 100 : null; return number + (kk__suffixes[number] || kk__suffixes[a] || kk__suffixes[b]); }, week: { dow: 1, // Monday is the first day of the week. doy: 7 // The week that contains Jan 1st is the first week of the year. } }); var km = moment__default.defineLocale('km', { months: 'មករា_កុម្ភៈ_មីនា_មេសា_ឧសភា_មិថុនា_កក្កដា_សីហា_កញ្ញា_តុលា_វិច្ឆិកា_ធ្នូ'.split('_'), monthsShort: 'មករា_កុម្ភៈ_មីនា_មេសា_ឧសភា_មិថុនា_កក្កដា_សីហា_កញ្ញា_តុលា_វិច្ឆិកា_ធ្នូ'.split('_'), weekdays: 'អាទិត្យ_ច័ន្ទ_អង្គារ_ពុធ_ព្រហស្បតិ៍_សុក្រ_សៅរ៍'.split('_'), weekdaysShort: 'អាទិត្យ_ច័ន្ទ_អង្គារ_ពុធ_ព្រហស្បតិ៍_សុក្រ_សៅរ៍'.split('_'), weekdaysMin: 'អាទិត្យ_ច័ន្ទ_អង្គារ_ពុធ_ព្រហស្បតិ៍_សុក្រ_សៅរ៍'.split('_'), longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'dddd, D MMMM YYYY HH:mm' }, calendar: { sameDay: '[ថ្ងៃនេះ ម៉ោង] LT', nextDay: '[ស្អែក ម៉ោង] LT', nextWeek: 'dddd [ម៉ោង] LT', lastDay: '[ម្សិលមិញ ម៉ោង] LT', lastWeek: 'dddd [សប្តាហ៍មុន] [ម៉ោង] LT', sameElse: 'L' }, relativeTime: { future: '%sទៀត', past: '%sមុន', s: 'ប៉ុន្មានវិនាទី', m: 'មួយនាទី', mm: '%d នាទី', h: 'មួយម៉ោង', hh: '%d ម៉ោង', d: 'មួយថ្ងៃ', dd: '%d ថ្ងៃ', M: 'មួយខែ', MM: '%d ខែ', y: 'មួយឆ្នាំ', yy: '%d ឆ្នាំ' }, week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); var ko = moment__default.defineLocale('ko', { months: '1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월'.split('_'), monthsShort: '1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월'.split('_'), weekdays: '일요일_월요일_화요일_수요일_목요일_금요일_토요일'.split('_'), weekdaysShort: '일_월_화_수_목_금_토'.split('_'), weekdaysMin: '일_월_화_수_목_금_토'.split('_'), longDateFormat: { LT: 'A h시 m분', LTS: 'A h시 m분 s초', L: 'YYYY.MM.DD', LL: 'YYYY년 MMMM D일', LLL: 'YYYY년 MMMM D일 A h시 m분', LLLL: 'YYYY년 MMMM D일 dddd A h시 m분' }, calendar: { sameDay: '오늘 LT', nextDay: '내일 LT', nextWeek: 'dddd LT', lastDay: '어제 LT', lastWeek: '지난주 dddd LT', sameElse: 'L' }, relativeTime: { future: '%s 후', past: '%s 전', s: '몇 초', ss: '%d초', m: '일분', mm: '%d분', h: '한 시간', hh: '%d시간', d: '하루', dd: '%d일', M: '한 달', MM: '%d달', y: '일 년', yy: '%d년' }, ordinalParse: /\d{1,2}일/, ordinal: '%d일', meridiemParse: /오전|오후/, isPM: function (token) { return token === '오후'; }, meridiem: function (hour, minute, isUpper) { return hour < 12 ? '오전' : '오후'; } }); var ky__suffixes = { 0: '-чү', 1: '-чи', 2: '-чи', 3: '-чү', 4: '-чү', 5: '-чи', 6: '-чы', 7: '-чи', 8: '-чи', 9: '-чу', 10: '-чу', 20: '-чы', 30: '-чу', 40: '-чы', 50: '-чү', 60: '-чы', 70: '-чи', 80: '-чи', 90: '-чу', 100: '-чү' }; var ky = moment__default.defineLocale('ky', { months: 'январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь'.split('_'), monthsShort: 'янв_фев_март_апр_май_июнь_июль_авг_сен_окт_ноя_дек'.split('_'), weekdays: 'Жекшемби_Дүйшөмбү_Шейшемби_Шаршемби_Бейшемби_Жума_Ишемби'.split('_'), weekdaysShort: 'Жек_Дүй_Шей_Шар_Бей_Жум_Ише'.split('_'), weekdaysMin: 'Жк_Дй_Шй_Шр_Бй_Жм_Иш'.split('_'), longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD.MM.YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'dddd, D MMMM YYYY HH:mm' }, calendar: { sameDay: '[Бүгүн саат] LT', nextDay: '[Эртең саат] LT', nextWeek: 'dddd [саат] LT', lastDay: '[Кече саат] LT', lastWeek: '[Өткен аптанын] dddd [күнү] [саат] LT', sameElse: 'L' }, relativeTime: { future: '%s ичинде', past: '%s мурун', s: 'бирнече секунд', m: 'бир мүнөт', mm: '%d мүнөт', h: 'бир саат', hh: '%d саат', d: 'бир күн', dd: '%d күн', M: 'бир ай', MM: '%d ай', y: 'бир жыл', yy: '%d жыл' }, ordinalParse: /\d{1,2}-(чи|чы|чү|чу)/, ordinal: function (number) { var a = number % 10, b = number >= 100 ? 100 : null; return number + (ky__suffixes[number] || ky__suffixes[a] || ky__suffixes[b]); }, week: { dow: 1, // Monday is the first day of the week. doy: 7 // The week that contains Jan 1st is the first week of the year. } }); function lb__processRelativeTime(number, withoutSuffix, key, isFuture) { var format = { 'm': ['eng Minutt', 'enger Minutt'], 'h': ['eng Stonn', 'enger Stonn'], 'd': ['een Dag', 'engem Dag'], 'M': ['ee Mount', 'engem Mount'], 'y': ['ee Joer', 'engem Joer'] }; return withoutSuffix ? format[key][0] : format[key][1]; } function processFutureTime(string) { var number = string.substr(0, string.indexOf(' ')); if (eifelerRegelAppliesToNumber(number)) { return 'a ' + string; } return 'an ' + string; } function processPastTime(string) { var number = string.substr(0, string.indexOf(' ')); if (eifelerRegelAppliesToNumber(number)) { return 'viru ' + string; } return 'virun ' + string; } /** * Returns true if the word before the given number loses the '-n' ending. * e.g. 'an 10 Deeg' but 'a 5 Deeg' * * @param number {integer} * @returns {boolean} */ function eifelerRegelAppliesToNumber(number) { number = parseInt(number, 10); if (isNaN(number)) { return false; } if (number < 0) { // Negative Number --> always true return true; } else if (number < 10) { // Only 1 digit if (4 <= number && number <= 7) { return true; } return false; } else if (number < 100) { // 2 digits var lastDigit = number % 10, firstDigit = number / 10; if (lastDigit === 0) { return eifelerRegelAppliesToNumber(firstDigit); } return eifelerRegelAppliesToNumber(lastDigit); } else if (number < 10000) { // 3 or 4 digits --> recursively check first digit while (number >= 10) { number = number / 10; } return eifelerRegelAppliesToNumber(number); } else { // Anything larger than 4 digits: recursively check first n-3 digits number = number / 1000; return eifelerRegelAppliesToNumber(number); } } var lb = moment__default.defineLocale('lb', { months: 'Januar_Februar_Mäerz_Abrëll_Mee_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'), monthsShort: 'Jan._Febr._Mrz._Abr._Mee_Jun._Jul._Aug._Sept._Okt._Nov._Dez.'.split('_'), monthsParseExact: true, weekdays: 'Sonndeg_Méindeg_Dënschdeg_Mëttwoch_Donneschdeg_Freideg_Samschdeg'.split('_'), weekdaysShort: 'So._Mé._Dë._Më._Do._Fr._Sa.'.split('_'), weekdaysMin: 'So_Mé_Dë_Më_Do_Fr_Sa'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'H:mm [Auer]', LTS: 'H:mm:ss [Auer]', L: 'DD.MM.YYYY', LL: 'D. MMMM YYYY', LLL: 'D. MMMM YYYY H:mm [Auer]', LLLL: 'dddd, D. MMMM YYYY H:mm [Auer]' }, calendar: { sameDay: '[Haut um] LT', sameElse: 'L', nextDay: '[Muer um] LT', nextWeek: 'dddd [um] LT', lastDay: '[Gëschter um] LT', lastWeek: function () { // Different date string for 'Dënschdeg' (Tuesday) and 'Donneschdeg' (Thursday) due to phonological rule switch (this.day()) { case 2: case 4: return '[Leschten] dddd [um] LT'; default: return '[Leschte] dddd [um] LT'; } } }, relativeTime: { future: processFutureTime, past: processPastTime, s: 'e puer Sekonnen', m: lb__processRelativeTime, mm: '%d Minutten', h: lb__processRelativeTime, hh: '%d Stonnen', d: lb__processRelativeTime, dd: '%d Deeg', M: lb__processRelativeTime, MM: '%d Méint', y: lb__processRelativeTime, yy: '%d Joer' }, ordinalParse: /\d{1,2}\./, ordinal: '%d.', week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); var lo = moment__default.defineLocale('lo', { months: 'ມັງກອນ_ກຸມພາ_ມີນາ_ເມສາ_ພຶດສະພາ_ມິຖຸນາ_ກໍລະກົດ_ສິງຫາ_ກັນຍາ_ຕຸລາ_ພະຈິກ_ທັນວາ'.split('_'), monthsShort: 'ມັງກອນ_ກຸມພາ_ມີນາ_ເມສາ_ພຶດສະພາ_ມິຖຸນາ_ກໍລະກົດ_ສິງຫາ_ກັນຍາ_ຕຸລາ_ພະຈິກ_ທັນວາ'.split('_'), weekdays: 'ອາທິດ_ຈັນ_ອັງຄານ_ພຸດ_ພະຫັດ_ສຸກ_ເສົາ'.split('_'), weekdaysShort: 'ທິດ_ຈັນ_ອັງຄານ_ພຸດ_ພະຫັດ_ສຸກ_ເສົາ'.split('_'), weekdaysMin: 'ທ_ຈ_ອຄ_ພ_ພຫ_ສກ_ສ'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'ວັນdddd D MMMM YYYY HH:mm' }, meridiemParse: /ຕອນເຊົ້າ|ຕອນແລງ/, isPM: function (input) { return input === 'ຕອນແລງ'; }, meridiem: function (hour, minute, isLower) { if (hour < 12) { return 'ຕອນເຊົ້າ'; } else { return 'ຕອນແລງ'; } }, calendar: { sameDay: '[ມື້ນີ້ເວລາ] LT', nextDay: '[ມື້ອື່ນເວລາ] LT', nextWeek: '[ວັນ]dddd[ໜ້າເວລາ] LT', lastDay: '[ມື້ວານນີ້ເວລາ] LT', lastWeek: '[ວັນ]dddd[ແລ້ວນີ້ເວລາ] LT', sameElse: 'L' }, relativeTime: { future: 'ອີກ %s', past: '%sຜ່ານມາ', s: 'ບໍ່ເທົ່າໃດວິນາທີ', m: '1 ນາທີ', mm: '%d ນາທີ', h: '1 ຊົ່ວໂມງ', hh: '%d ຊົ່ວໂມງ', d: '1 ມື້', dd: '%d ມື້', M: '1 ເດືອນ', MM: '%d ເດືອນ', y: '1 ປີ', yy: '%d ປີ' }, ordinalParse: /(ທີ່)\d{1,2}/, ordinal: function (number) { return 'ທີ່' + number; } }); var lt__units = { 'm': 'minutė_minutės_minutę', 'mm': 'minutės_minučių_minutes', 'h': 'valanda_valandos_valandą', 'hh': 'valandos_valandų_valandas', 'd': 'diena_dienos_dieną', 'dd': 'dienos_dienų_dienas', 'M': 'mėnuo_mėnesio_mėnesį', 'MM': 'mėnesiai_mėnesių_mėnesius', 'y': 'metai_metų_metus', 'yy': 'metai_metų_metus' }; function translateSeconds(number, withoutSuffix, key, isFuture) { if (withoutSuffix) { return 'kelios sekundės'; } else { return isFuture ? 'kelių sekundžių' : 'kelias sekundes'; } } function translateSingular(number, withoutSuffix, key, isFuture) { return withoutSuffix ? forms(key)[0] : (isFuture ? forms(key)[1] : forms(key)[2]); } function special(number) { return number % 10 === 0 || (number > 10 && number < 20); } function forms(key) { return lt__units[key].split('_'); } function lt__translate(number, withoutSuffix, key, isFuture) { var result = number + ' '; if (number === 1) { return result + translateSingular(number, withoutSuffix, key[0], isFuture); } else if (withoutSuffix) { return result + (special(number) ? forms(key)[1] : forms(key)[0]); } else { if (isFuture) { return result + forms(key)[1]; } else { return result + (special(number) ? forms(key)[1] : forms(key)[2]); } } } var lt = moment__default.defineLocale('lt', { months: { format: 'sausio_vasario_kovo_balandžio_gegužės_birželio_liepos_rugpjūčio_rugsėjo_spalio_lapkričio_gruodžio'.split('_'), standalone: 'sausis_vasaris_kovas_balandis_gegužė_birželis_liepa_rugpjūtis_rugsėjis_spalis_lapkritis_gruodis'.split('_'), isFormat: /D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?|MMMM?(\[[^\[\]]*\]|\s+)+D[oD]?/ }, monthsShort: 'sau_vas_kov_bal_geg_bir_lie_rgp_rgs_spa_lap_grd'.split('_'), weekdays: { format: 'sekmadienį_pirmadienį_antradienį_trečiadienį_ketvirtadienį_penktadienį_šeštadienį'.split('_'), standalone: 'sekmadienis_pirmadienis_antradienis_trečiadienis_ketvirtadienis_penktadienis_šeštadienis'.split('_'), isFormat: /dddd HH:mm/ }, weekdaysShort: 'Sek_Pir_Ant_Tre_Ket_Pen_Šeš'.split('_'), weekdaysMin: 'S_P_A_T_K_Pn_Š'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'YYYY-MM-DD', LL: 'YYYY [m.] MMMM D [d.]', LLL: 'YYYY [m.] MMMM D [d.], HH:mm [val.]', LLLL: 'YYYY [m.] MMMM D [d.], dddd, HH:mm [val.]', l: 'YYYY-MM-DD', ll: 'YYYY [m.] MMMM D [d.]', lll: 'YYYY [m.] MMMM D [d.], HH:mm [val.]', llll: 'YYYY [m.] MMMM D [d.], ddd, HH:mm [val.]' }, calendar: { sameDay: '[Šiandien] LT', nextDay: '[Rytoj] LT', nextWeek: 'dddd LT', lastDay: '[Vakar] LT', lastWeek: '[Praėjusį] dddd LT', sameElse: 'L' }, relativeTime: { future: 'po %s', past: 'prieš %s', s: translateSeconds, m: translateSingular, mm: lt__translate, h: translateSingular, hh: lt__translate, d: translateSingular, dd: lt__translate, M: translateSingular, MM: lt__translate, y: translateSingular, yy: lt__translate }, ordinalParse: /\d{1,2}-oji/, ordinal: function (number) { return number + '-oji'; }, week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); var lv__units = { 'm': 'minūtes_minūtēm_minūte_minūtes'.split('_'), 'mm': 'minūtes_minūtēm_minūte_minūtes'.split('_'), 'h': 'stundas_stundām_stunda_stundas'.split('_'), 'hh': 'stundas_stundām_stunda_stundas'.split('_'), 'd': 'dienas_dienām_diena_dienas'.split('_'), 'dd': 'dienas_dienām_diena_dienas'.split('_'), 'M': 'mēneša_mēnešiem_mēnesis_mēneši'.split('_'), 'MM': 'mēneša_mēnešiem_mēnesis_mēneši'.split('_'), 'y': 'gada_gadiem_gads_gadi'.split('_'), 'yy': 'gada_gadiem_gads_gadi'.split('_') }; /** * @param withoutSuffix boolean true = a length of time; false = before/after a period of time. */ function lv__format(forms, number, withoutSuffix) { if (withoutSuffix) { // E.g. "21 minūte", "3 minūtes". return number % 10 === 1 && number % 100 !== 11 ? forms[2] : forms[3]; } else { // E.g. "21 minūtes" as in "pēc 21 minūtes". // E.g. "3 minūtēm" as in "pēc 3 minūtēm". return number % 10 === 1 && number % 100 !== 11 ? forms[0] : forms[1]; } } function lv__relativeTimeWithPlural(number, withoutSuffix, key) { return number + ' ' + lv__format(lv__units[key], number, withoutSuffix); } function relativeTimeWithSingular(number, withoutSuffix, key) { return lv__format(lv__units[key], number, withoutSuffix); } function relativeSeconds(number, withoutSuffix) { return withoutSuffix ? 'dažas sekundes' : 'dažām sekundēm'; } var lv = moment__default.defineLocale('lv', { months: 'janvāris_februāris_marts_aprīlis_maijs_jūnijs_jūlijs_augusts_septembris_oktobris_novembris_decembris'.split('_'), monthsShort: 'jan_feb_mar_apr_mai_jūn_jūl_aug_sep_okt_nov_dec'.split('_'), weekdays: 'svētdiena_pirmdiena_otrdiena_trešdiena_ceturtdiena_piektdiena_sestdiena'.split('_'), weekdaysShort: 'Sv_P_O_T_C_Pk_S'.split('_'), weekdaysMin: 'Sv_P_O_T_C_Pk_S'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD.MM.YYYY.', LL: 'YYYY. [gada] D. MMMM', LLL: 'YYYY. [gada] D. MMMM, HH:mm', LLLL: 'YYYY. [gada] D. MMMM, dddd, HH:mm' }, calendar: { sameDay: '[Šodien pulksten] LT', nextDay: '[Rīt pulksten] LT', nextWeek: 'dddd [pulksten] LT', lastDay: '[Vakar pulksten] LT', lastWeek: '[Pagājušā] dddd [pulksten] LT', sameElse: 'L' }, relativeTime: { future: 'pēc %s', past: 'pirms %s', s: relativeSeconds, m: relativeTimeWithSingular, mm: lv__relativeTimeWithPlural, h: relativeTimeWithSingular, hh: lv__relativeTimeWithPlural, d: relativeTimeWithSingular, dd: lv__relativeTimeWithPlural, M: relativeTimeWithSingular, MM: lv__relativeTimeWithPlural, y: relativeTimeWithSingular, yy: lv__relativeTimeWithPlural }, ordinalParse: /\d{1,2}\./, ordinal: '%d.', week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); var me__translator = { words: { //Different grammatical cases m: ['jedan minut', 'jednog minuta'], mm: ['minut', 'minuta', 'minuta'], h: ['jedan sat', 'jednog sata'], hh: ['sat', 'sata', 'sati'], dd: ['dan', 'dana', 'dana'], MM: ['mjesec', 'mjeseca', 'mjeseci'], yy: ['godina', 'godine', 'godina'] }, correctGrammaticalCase: function (number, wordKey) { return number === 1 ? wordKey[0] : (number >= 2 && number <= 4 ? wordKey[1] : wordKey[2]); }, translate: function (number, withoutSuffix, key) { var wordKey = me__translator.words[key]; if (key.length === 1) { return withoutSuffix ? wordKey[0] : wordKey[1]; } else { return number + ' ' + me__translator.correctGrammaticalCase(number, wordKey); } } }; var me = moment__default.defineLocale('me', { months: 'januar_februar_mart_april_maj_jun_jul_avgust_septembar_oktobar_novembar_decembar'.split('_'), monthsShort: 'jan._feb._mar._apr._maj_jun_jul_avg._sep._okt._nov._dec.'.split('_'), monthsParseExact: true, weekdays: 'nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota'.split('_'), weekdaysShort: 'ned._pon._uto._sri._čet._pet._sub.'.split('_'), weekdaysMin: 'ne_po_ut_sr_če_pe_su'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'H:mm', LTS: 'H:mm:ss', L: 'DD. MM. YYYY', LL: 'D. MMMM YYYY', LLL: 'D. MMMM YYYY H:mm', LLLL: 'dddd, D. MMMM YYYY H:mm' }, calendar: { sameDay: '[danas u] LT', nextDay: '[sjutra u] LT', nextWeek: function () { switch (this.day()) { case 0: return '[u] [nedjelju] [u] LT'; case 3: return '[u] [srijedu] [u] LT'; case 6: return '[u] [subotu] [u] LT'; case 1: case 2: case 4: case 5: return '[u] dddd [u] LT'; } }, lastDay: '[juče u] LT', lastWeek: function () { var lastWeekDays = [ '[prošle] [nedjelje] [u] LT', '[prošlog] [ponedjeljka] [u] LT', '[prošlog] [utorka] [u] LT', '[prošle] [srijede] [u] LT', '[prošlog] [četvrtka] [u] LT', '[prošlog] [petka] [u] LT', '[prošle] [subote] [u] LT' ]; return lastWeekDays[this.day()]; }, sameElse: 'L' }, relativeTime: { future: 'za %s', past: 'prije %s', s: 'nekoliko sekundi', m: me__translator.translate, mm: me__translator.translate, h: me__translator.translate, hh: me__translator.translate, d: 'dan', dd: me__translator.translate, M: 'mjesec', MM: me__translator.translate, y: 'godinu', yy: me__translator.translate }, ordinalParse: /\d{1,2}\./, ordinal: '%d.', week: { dow: 1, // Monday is the first day of the week. doy: 7 // The week that contains Jan 1st is the first week of the year. } }); var mk = moment__default.defineLocale('mk', { months: 'јануари_февруари_март_април_мај_јуни_јули_август_септември_октомври_ноември_декември'.split('_'), monthsShort: 'јан_фев_мар_апр_мај_јун_јул_авг_сеп_окт_ное_дек'.split('_'), weekdays: 'недела_понеделник_вторник_среда_четврток_петок_сабота'.split('_'), weekdaysShort: 'нед_пон_вто_сре_чет_пет_саб'.split('_'), weekdaysMin: 'нe_пo_вт_ср_че_пе_сa'.split('_'), longDateFormat: { LT: 'H:mm', LTS: 'H:mm:ss', L: 'D.MM.YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY H:mm', LLLL: 'dddd, D MMMM YYYY H:mm' }, calendar: { sameDay: '[Денес во] LT', nextDay: '[Утре во] LT', nextWeek: '[Во] dddd [во] LT', lastDay: '[Вчера во] LT', lastWeek: function () { switch (this.day()) { case 0: case 3: case 6: return '[Изминатата] dddd [во] LT'; case 1: case 2: case 4: case 5: return '[Изминатиот] dddd [во] LT'; } }, sameElse: 'L' }, relativeTime: { future: 'после %s', past: 'пред %s', s: 'неколку секунди', m: 'минута', mm: '%d минути', h: 'час', hh: '%d часа', d: 'ден', dd: '%d дена', M: 'месец', MM: '%d месеци', y: 'година', yy: '%d години' }, ordinalParse: /\d{1,2}-(ев|ен|ти|ви|ри|ми)/, ordinal: function (number) { var lastDigit = number % 10, last2Digits = number % 100; if (number === 0) { return number + '-ев'; } else if (last2Digits === 0) { return number + '-ен'; } else if (last2Digits > 10 && last2Digits < 20) { return number + '-ти'; } else if (lastDigit === 1) { return number + '-ви'; } else if (lastDigit === 2) { return number + '-ри'; } else if (lastDigit === 7 || lastDigit === 8) { return number + '-ми'; } else { return number + '-ти'; } }, week: { dow: 1, // Monday is the first day of the week. doy: 7 // The week that contains Jan 1st is the first week of the year. } }); var ml = moment__default.defineLocale('ml', { months: 'ജനുവരി_ഫെബ്രുവരി_മാർച്ച്_ഏപ്രിൽ_മേയ്_ജൂൺ_ജൂലൈ_ഓഗസ്റ്റ്_സെപ്റ്റംബർ_ഒക്ടോബർ_നവംബർ_ഡിസംബർ'.split('_'), monthsShort: 'ജനു._ഫെബ്രു._മാർ._ഏപ്രി._മേയ്_ജൂൺ_ജൂലൈ._ഓഗ._സെപ്റ്റ._ഒക്ടോ._നവം._ഡിസം.'.split('_'), monthsParseExact: true, weekdays: 'ഞായറാഴ്ച_തിങ്കളാഴ്ച_ചൊവ്വാഴ്ച_ബുധനാഴ്ച_വ്യാഴാഴ്ച_വെള്ളിയാഴ്ച_ശനിയാഴ്ച'.split('_'), weekdaysShort: 'ഞായർ_തിങ്കൾ_ചൊവ്വ_ബുധൻ_വ്യാഴം_വെള്ളി_ശനി'.split('_'), weekdaysMin: 'ഞാ_തി_ചൊ_ബു_വ്യാ_വെ_ശ'.split('_'), longDateFormat: { LT: 'A h:mm -നു', LTS: 'A h:mm:ss -നു', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY, A h:mm -നു', LLLL: 'dddd, D MMMM YYYY, A h:mm -നു' }, calendar: { sameDay: '[ഇന്ന്] LT', nextDay: '[നാളെ] LT', nextWeek: 'dddd, LT', lastDay: '[ഇന്നലെ] LT', lastWeek: '[കഴിഞ്ഞ] dddd, LT', sameElse: 'L' }, relativeTime: { future: '%s കഴിഞ്ഞ്', past: '%s മുൻപ്', s: 'അൽപ നിമിഷങ്ങൾ', m: 'ഒരു മിനിറ്റ്', mm: '%d മിനിറ്റ്', h: 'ഒരു മണിക്കൂർ', hh: '%d മണിക്കൂർ', d: 'ഒരു ദിവസം', dd: '%d ദിവസം', M: 'ഒരു മാസം', MM: '%d മാസം', y: 'ഒരു വർഷം', yy: '%d വർഷം' }, meridiemParse: /രാത്രി|രാവിലെ|ഉച്ച കഴിഞ്ഞ്|വൈകുന്നേരം|രാത്രി/i, meridiemHour: function (hour, meridiem) { if (hour === 12) { hour = 0; } if ((meridiem === 'രാത്രി' && hour >= 4) || meridiem === 'ഉച്ച കഴിഞ്ഞ്' || meridiem === 'വൈകുന്നേരം') { return hour + 12; } else { return hour; } }, meridiem: function (hour, minute, isLower) { if (hour < 4) { return 'രാത്രി'; } else if (hour < 12) { return 'രാവിലെ'; } else if (hour < 17) { return 'ഉച്ച കഴിഞ്ഞ്'; } else if (hour < 20) { return 'വൈകുന്നേരം'; } else { return 'രാത്രി'; } } }); var mr__symbolMap = { '1': '१', '2': '२', '3': '३', '4': '४', '5': '५', '6': '६', '7': '७', '8': '८', '9': '९', '0': '०' }, mr__numberMap = { '१': '1', '२': '2', '३': '3', '४': '4', '५': '5', '६': '6', '७': '7', '८': '8', '९': '9', '०': '0' }; function relativeTimeMr(number, withoutSuffix, string, isFuture) { var output = ''; if (withoutSuffix) { switch (string) { case 's': output = 'काही सेकंद'; break; case 'm': output = 'एक मिनिट'; break; case 'mm': output = '%d मिनिटे'; break; case 'h': output = 'एक तास'; break; case 'hh': output = '%d तास'; break; case 'd': output = 'एक दिवस'; break; case 'dd': output = '%d दिवस'; break; case 'M': output = 'एक महिना'; break; case 'MM': output = '%d महिने'; break; case 'y': output = 'एक वर्ष'; break; case 'yy': output = '%d वर्षे'; break; } } else { switch (string) { case 's': output = 'काही सेकंदां'; break; case 'm': output = 'एका मिनिटा'; break; case 'mm': output = '%d मिनिटां'; break; case 'h': output = 'एका तासा'; break; case 'hh': output = '%d तासां'; break; case 'd': output = 'एका दिवसा'; break; case 'dd': output = '%d दिवसां'; break; case 'M': output = 'एका महिन्या'; break; case 'MM': output = '%d महिन्यां'; break; case 'y': output = 'एका वर्षा'; break; case 'yy': output = '%d वर्षां'; break; } } return output.replace(/%d/i, number); } var mr = moment__default.defineLocale('mr', { months: 'जानेवारी_फेब्रुवारी_मार्च_एप्रिल_मे_जून_जुलै_ऑगस्ट_सप्टेंबर_ऑक्टोबर_नोव्हेंबर_डिसेंबर'.split('_'), monthsShort: 'जाने._फेब्रु._मार्च._एप्रि._मे._जून._जुलै._ऑग._सप्टें._ऑक्टो._नोव्हें._डिसें.'.split('_'), monthsParseExact: true, weekdays: 'रविवार_सोमवार_मंगळवार_बुधवार_गुरूवार_शुक्रवार_शनिवार'.split('_'), weekdaysShort: 'रवि_सोम_मंगळ_बुध_गुरू_शुक्र_शनि'.split('_'), weekdaysMin: 'र_सो_मं_बु_गु_शु_श'.split('_'), longDateFormat: { LT: 'A h:mm वाजता', LTS: 'A h:mm:ss वाजता', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY, A h:mm वाजता', LLLL: 'dddd, D MMMM YYYY, A h:mm वाजता' }, calendar: { sameDay: '[आज] LT', nextDay: '[उद्या] LT', nextWeek: 'dddd, LT', lastDay: '[काल] LT', lastWeek: '[मागील] dddd, LT', sameElse: 'L' }, relativeTime: { future: '%sमध्ये', past: '%sपूर्वी', s: relativeTimeMr, m: relativeTimeMr, mm: relativeTimeMr, h: relativeTimeMr, hh: relativeTimeMr, d: relativeTimeMr, dd: relativeTimeMr, M: relativeTimeMr, MM: relativeTimeMr, y: relativeTimeMr, yy: relativeTimeMr }, preparse: function (string) { return string.replace(/[१२३४५६७८९०]/g, function (match) { return mr__numberMap[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return mr__symbolMap[match]; }); }, meridiemParse: /रात्री|सकाळी|दुपारी|सायंकाळी/, meridiemHour: function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === 'रात्री') { return hour < 4 ? hour : hour + 12; } else if (meridiem === 'सकाळी') { return hour; } else if (meridiem === 'दुपारी') { return hour >= 10 ? hour : hour + 12; } else if (meridiem === 'सायंकाळी') { return hour + 12; } }, meridiem: function (hour, minute, isLower) { if (hour < 4) { return 'रात्री'; } else if (hour < 10) { return 'सकाळी'; } else if (hour < 17) { return 'दुपारी'; } else if (hour < 20) { return 'सायंकाळी'; } else { return 'रात्री'; } }, week: { dow: 0, // Sunday is the first day of the week. doy: 6 // The week that contains Jan 1st is the first week of the year. } }); var ms_my = moment__default.defineLocale('ms-my', { months: 'Januari_Februari_Mac_April_Mei_Jun_Julai_Ogos_September_Oktober_November_Disember'.split('_'), monthsShort: 'Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ogs_Sep_Okt_Nov_Dis'.split('_'), weekdays: 'Ahad_Isnin_Selasa_Rabu_Khamis_Jumaat_Sabtu'.split('_'), weekdaysShort: 'Ahd_Isn_Sel_Rab_Kha_Jum_Sab'.split('_'), weekdaysMin: 'Ah_Is_Sl_Rb_Km_Jm_Sb'.split('_'), longDateFormat: { LT: 'HH.mm', LTS: 'HH.mm.ss', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY [pukul] HH.mm', LLLL: 'dddd, D MMMM YYYY [pukul] HH.mm' }, meridiemParse: /pagi|tengahari|petang|malam/, meridiemHour: function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === 'pagi') { return hour; } else if (meridiem === 'tengahari') { return hour >= 11 ? hour : hour + 12; } else if (meridiem === 'petang' || meridiem === 'malam') { return hour + 12; } }, meridiem: function (hours, minutes, isLower) { if (hours < 11) { return 'pagi'; } else if (hours < 15) { return 'tengahari'; } else if (hours < 19) { return 'petang'; } else { return 'malam'; } }, calendar: { sameDay: '[Hari ini pukul] LT', nextDay: '[Esok pukul] LT', nextWeek: 'dddd [pukul] LT', lastDay: '[Kelmarin pukul] LT', lastWeek: 'dddd [lepas pukul] LT', sameElse: 'L' }, relativeTime: { future: 'dalam %s', past: '%s yang lepas', s: 'beberapa saat', m: 'seminit', mm: '%d minit', h: 'sejam', hh: '%d jam', d: 'sehari', dd: '%d hari', M: 'sebulan', MM: '%d bulan', y: 'setahun', yy: '%d tahun' }, week: { dow: 1, // Monday is the first day of the week. doy: 7 // The week that contains Jan 1st is the first week of the year. } }); var locale_ms = moment__default.defineLocale('ms', { months: 'Januari_Februari_Mac_April_Mei_Jun_Julai_Ogos_September_Oktober_November_Disember'.split('_'), monthsShort: 'Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ogs_Sep_Okt_Nov_Dis'.split('_'), weekdays: 'Ahad_Isnin_Selasa_Rabu_Khamis_Jumaat_Sabtu'.split('_'), weekdaysShort: 'Ahd_Isn_Sel_Rab_Kha_Jum_Sab'.split('_'), weekdaysMin: 'Ah_Is_Sl_Rb_Km_Jm_Sb'.split('_'), longDateFormat: { LT: 'HH.mm', LTS: 'HH.mm.ss', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY [pukul] HH.mm', LLLL: 'dddd, D MMMM YYYY [pukul] HH.mm' }, meridiemParse: /pagi|tengahari|petang|malam/, meridiemHour: function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === 'pagi') { return hour; } else if (meridiem === 'tengahari') { return hour >= 11 ? hour : hour + 12; } else if (meridiem === 'petang' || meridiem === 'malam') { return hour + 12; } }, meridiem: function (hours, minutes, isLower) { if (hours < 11) { return 'pagi'; } else if (hours < 15) { return 'tengahari'; } else if (hours < 19) { return 'petang'; } else { return 'malam'; } }, calendar: { sameDay: '[Hari ini pukul] LT', nextDay: '[Esok pukul] LT', nextWeek: 'dddd [pukul] LT', lastDay: '[Kelmarin pukul] LT', lastWeek: 'dddd [lepas pukul] LT', sameElse: 'L' }, relativeTime: { future: 'dalam %s', past: '%s yang lepas', s: 'beberapa saat', m: 'seminit', mm: '%d minit', h: 'sejam', hh: '%d jam', d: 'sehari', dd: '%d hari', M: 'sebulan', MM: '%d bulan', y: 'setahun', yy: '%d tahun' }, week: { dow: 1, // Monday is the first day of the week. doy: 7 // The week that contains Jan 1st is the first week of the year. } }); var my__symbolMap = { '1': '၁', '2': '၂', '3': '၃', '4': '၄', '5': '၅', '6': '၆', '7': '၇', '8': '၈', '9': '၉', '0': '၀' }, my__numberMap = { '၁': '1', '၂': '2', '၃': '3', '၄': '4', '၅': '5', '၆': '6', '၇': '7', '၈': '8', '၉': '9', '၀': '0' }; var my = moment__default.defineLocale('my', { months: 'ဇန်နဝါရီ_ဖေဖော်ဝါရီ_မတ်_ဧပြီ_မေ_ဇွန်_ဇူလိုင်_သြဂုတ်_စက်တင်ဘာ_အောက်တိုဘာ_နိုဝင်ဘာ_ဒီဇင်ဘာ'.split('_'), monthsShort: 'ဇန်_ဖေ_မတ်_ပြီ_မေ_ဇွန်_လိုင်_သြ_စက်_အောက်_နို_ဒီ'.split('_'), weekdays: 'တနင်္ဂနွေ_တနင်္လာ_အင်္ဂါ_ဗုဒ္ဓဟူး_ကြာသပတေး_သောကြာ_စနေ'.split('_'), weekdaysShort: 'နွေ_လာ_ဂါ_ဟူး_ကြာ_သော_နေ'.split('_'), weekdaysMin: 'နွေ_လာ_ဂါ_ဟူး_ကြာ_သော_နေ'.split('_'), longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'dddd D MMMM YYYY HH:mm' }, calendar: { sameDay: '[ယနေ.] LT [မှာ]', nextDay: '[မနက်ဖြန်] LT [မှာ]', nextWeek: 'dddd LT [မှာ]', lastDay: '[မနေ.က] LT [မှာ]', lastWeek: '[ပြီးခဲ့သော] dddd LT [မှာ]', sameElse: 'L' }, relativeTime: { future: 'လာမည့် %s မှာ', past: 'လွန်ခဲ့သော %s က', s: 'စက္ကန်.အနည်းငယ်', m: 'တစ်မိနစ်', mm: '%d မိနစ်', h: 'တစ်နာရီ', hh: '%d နာရီ', d: 'တစ်ရက်', dd: '%d ရက်', M: 'တစ်လ', MM: '%d လ', y: 'တစ်နှစ်', yy: '%d နှစ်' }, preparse: function (string) { return string.replace(/[၁၂၃၄၅၆၇၈၉၀]/g, function (match) { return my__numberMap[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return my__symbolMap[match]; }); }, week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 1st is the first week of the year. } }); var nb = moment__default.defineLocale('nb', { months: 'januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember'.split('_'), monthsShort: 'jan._feb._mars_april_mai_juni_juli_aug._sep._okt._nov._des.'.split('_'), monthsParseExact: true, weekdays: 'søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag'.split('_'), weekdaysShort: 'sø._ma._ti._on._to._fr._lø.'.split('_'), weekdaysMin: 'sø_ma_ti_on_to_fr_lø'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD.MM.YYYY', LL: 'D. MMMM YYYY', LLL: 'D. MMMM YYYY [kl.] HH:mm', LLLL: 'dddd D. MMMM YYYY [kl.] HH:mm' }, calendar: { sameDay: '[i dag kl.] LT', nextDay: '[i morgen kl.] LT', nextWeek: 'dddd [kl.] LT', lastDay: '[i går kl.] LT', lastWeek: '[forrige] dddd [kl.] LT', sameElse: 'L' }, relativeTime: { future: 'om %s', past: '%s siden', s: 'noen sekunder', m: 'ett minutt', mm: '%d minutter', h: 'en time', hh: '%d timer', d: 'en dag', dd: '%d dager', M: 'en måned', MM: '%d måneder', y: 'ett år', yy: '%d år' }, ordinalParse: /\d{1,2}\./, ordinal: '%d.', week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); var ne__symbolMap = { '1': '१', '2': '२', '3': '३', '4': '४', '5': '५', '6': '६', '7': '७', '8': '८', '9': '९', '0': '०' }, ne__numberMap = { '१': '1', '२': '2', '३': '3', '४': '4', '५': '5', '६': '6', '७': '7', '८': '8', '९': '9', '०': '0' }; var ne = moment__default.defineLocale('ne', { months: 'जनवरी_फेब्रुवरी_मार्च_अप्रिल_मई_जुन_जुलाई_अगष्ट_सेप्टेम्बर_अक्टोबर_नोभेम्बर_डिसेम्बर'.split('_'), monthsShort: 'जन._फेब्रु._मार्च_अप्रि._मई_जुन_जुलाई._अग._सेप्ट._अक्टो._नोभे._डिसे.'.split('_'), monthsParseExact: true, weekdays: 'आइतबार_सोमबार_मङ्गलबार_बुधबार_बिहिबार_शुक्रबार_शनिबार'.split('_'), weekdaysShort: 'आइत._सोम._मङ्गल._बुध._बिहि._शुक्र._शनि.'.split('_'), weekdaysMin: 'आ._सो._मं._बु._बि._शु._श.'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'Aको h:mm बजे', LTS: 'Aको h:mm:ss बजे', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY, Aको h:mm बजे', LLLL: 'dddd, D MMMM YYYY, Aको h:mm बजे' }, preparse: function (string) { return string.replace(/[१२३४५६७८९०]/g, function (match) { return ne__numberMap[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return ne__symbolMap[match]; }); }, meridiemParse: /राति|बिहान|दिउँसो|साँझ/, meridiemHour: function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === 'राति') { return hour < 4 ? hour : hour + 12; } else if (meridiem === 'बिहान') { return hour; } else if (meridiem === 'दिउँसो') { return hour >= 10 ? hour : hour + 12; } else if (meridiem === 'साँझ') { return hour + 12; } }, meridiem: function (hour, minute, isLower) { if (hour < 3) { return 'राति'; } else if (hour < 12) { return 'बिहान'; } else if (hour < 16) { return 'दिउँसो'; } else if (hour < 20) { return 'साँझ'; } else { return 'राति'; } }, calendar: { sameDay: '[आज] LT', nextDay: '[भोलि] LT', nextWeek: '[आउँदो] dddd[,] LT', lastDay: '[हिजो] LT', lastWeek: '[गएको] dddd[,] LT', sameElse: 'L' }, relativeTime: { future: '%sमा', past: '%s अगाडि', s: 'केही क्षण', m: 'एक मिनेट', mm: '%d मिनेट', h: 'एक घण्टा', hh: '%d घण्टा', d: 'एक दिन', dd: '%d दिन', M: 'एक महिना', MM: '%d महिना', y: 'एक बर्ष', yy: '%d बर्ष' }, week: { dow: 0, // Sunday is the first day of the week. doy: 6 // The week that contains Jan 1st is the first week of the year. } }); var nl__monthsShortWithDots = 'jan._feb._mrt._apr._mei_jun._jul._aug._sep._okt._nov._dec.'.split('_'), nl__monthsShortWithoutDots = 'jan_feb_mrt_apr_mei_jun_jul_aug_sep_okt_nov_dec'.split('_'); var nl = moment__default.defineLocale('nl', { months: 'januari_februari_maart_april_mei_juni_juli_augustus_september_oktober_november_december'.split('_'), monthsShort: function (m, format) { if (/-MMM-/.test(format)) { return nl__monthsShortWithoutDots[m.month()]; } else { return nl__monthsShortWithDots[m.month()]; } }, monthsParseExact: true, weekdays: 'zondag_maandag_dinsdag_woensdag_donderdag_vrijdag_zaterdag'.split('_'), weekdaysShort: 'zo._ma._di._wo._do._vr._za.'.split('_'), weekdaysMin: 'Zo_Ma_Di_Wo_Do_Vr_Za'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD-MM-YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'dddd D MMMM YYYY HH:mm' }, calendar: { sameDay: '[vandaag om] LT', nextDay: '[morgen om] LT', nextWeek: 'dddd [om] LT', lastDay: '[gisteren om] LT', lastWeek: '[afgelopen] dddd [om] LT', sameElse: 'L' }, relativeTime: { future: 'over %s', past: '%s geleden', s: 'een paar seconden', m: 'één minuut', mm: '%d minuten', h: 'één uur', hh: '%d uur', d: 'één dag', dd: '%d dagen', M: 'één maand', MM: '%d maanden', y: 'één jaar', yy: '%d jaar' }, ordinalParse: /\d{1,2}(ste|de)/, ordinal: function (number) { return number + ((number === 1 || number === 8 || number >= 20) ? 'ste' : 'de'); }, week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); var nn = moment__default.defineLocale('nn', { months: 'januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember'.split('_'), monthsShort: 'jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des'.split('_'), weekdays: 'sundag_måndag_tysdag_onsdag_torsdag_fredag_laurdag'.split('_'), weekdaysShort: 'sun_mån_tys_ons_tor_fre_lau'.split('_'), weekdaysMin: 'su_må_ty_on_to_fr_lø'.split('_'), longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD.MM.YYYY', LL: 'D. MMMM YYYY', LLL: 'D. MMMM YYYY [kl.] H:mm', LLLL: 'dddd D. MMMM YYYY [kl.] HH:mm' }, calendar: { sameDay: '[I dag klokka] LT', nextDay: '[I morgon klokka] LT', nextWeek: 'dddd [klokka] LT', lastDay: '[I går klokka] LT', lastWeek: '[Føregåande] dddd [klokka] LT', sameElse: 'L' }, relativeTime: { future: 'om %s', past: '%s sidan', s: 'nokre sekund', m: 'eit minutt', mm: '%d minutt', h: 'ein time', hh: '%d timar', d: 'ein dag', dd: '%d dagar', M: 'ein månad', MM: '%d månader', y: 'eit år', yy: '%d år' }, ordinalParse: /\d{1,2}\./, ordinal: '%d.', week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); var pa_in__symbolMap = { '1': '੧', '2': '੨', '3': '੩', '4': '੪', '5': '੫', '6': '੬', '7': '੭', '8': '੮', '9': '੯', '0': '੦' }, pa_in__numberMap = { '੧': '1', '੨': '2', '੩': '3', '੪': '4', '੫': '5', '੬': '6', '੭': '7', '੮': '8', '੯': '9', '੦': '0' }; var pa_in = moment__default.defineLocale('pa-in', { // There are months name as per Nanakshahi Calender but they are not used as rigidly in modern Punjabi. months: 'ਜਨਵਰੀ_ਫ਼ਰਵਰੀ_ਮਾਰਚ_ਅਪ੍ਰੈਲ_ਮਈ_ਜੂਨ_ਜੁਲਾਈ_ਅਗਸਤ_ਸਤੰਬਰ_ਅਕਤੂਬਰ_ਨਵੰਬਰ_ਦਸੰਬਰ'.split('_'), monthsShort: 'ਜਨਵਰੀ_ਫ਼ਰਵਰੀ_ਮਾਰਚ_ਅਪ੍ਰੈਲ_ਮਈ_ਜੂਨ_ਜੁਲਾਈ_ਅਗਸਤ_ਸਤੰਬਰ_ਅਕਤੂਬਰ_ਨਵੰਬਰ_ਦਸੰਬਰ'.split('_'), weekdays: 'ਐਤਵਾਰ_ਸੋਮਵਾਰ_ਮੰਗਲਵਾਰ_ਬੁਧਵਾਰ_ਵੀਰਵਾਰ_ਸ਼ੁੱਕਰਵਾਰ_ਸ਼ਨੀਚਰਵਾਰ'.split('_'), weekdaysShort: 'ਐਤ_ਸੋਮ_ਮੰਗਲ_ਬੁਧ_ਵੀਰ_ਸ਼ੁਕਰ_ਸ਼ਨੀ'.split('_'), weekdaysMin: 'ਐਤ_ਸੋਮ_ਮੰਗਲ_ਬੁਧ_ਵੀਰ_ਸ਼ੁਕਰ_ਸ਼ਨੀ'.split('_'), longDateFormat: { LT: 'A h:mm ਵਜੇ', LTS: 'A h:mm:ss ਵਜੇ', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY, A h:mm ਵਜੇ', LLLL: 'dddd, D MMMM YYYY, A h:mm ਵਜੇ' }, calendar: { sameDay: '[ਅਜ] LT', nextDay: '[ਕਲ] LT', nextWeek: 'dddd, LT', lastDay: '[ਕਲ] LT', lastWeek: '[ਪਿਛਲੇ] dddd, LT', sameElse: 'L' }, relativeTime: { future: '%s ਵਿੱਚ', past: '%s ਪਿਛਲੇ', s: 'ਕੁਝ ਸਕਿੰਟ', m: 'ਇਕ ਮਿੰਟ', mm: '%d ਮਿੰਟ', h: 'ਇੱਕ ਘੰਟਾ', hh: '%d ਘੰਟੇ', d: 'ਇੱਕ ਦਿਨ', dd: '%d ਦਿਨ', M: 'ਇੱਕ ਮਹੀਨਾ', MM: '%d ਮਹੀਨੇ', y: 'ਇੱਕ ਸਾਲ', yy: '%d ਸਾਲ' }, preparse: function (string) { return string.replace(/[੧੨੩੪੫੬੭੮੯੦]/g, function (match) { return pa_in__numberMap[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return pa_in__symbolMap[match]; }); }, // Punjabi notation for meridiems are quite fuzzy in practice. While there exists // a rigid notion of a 'Pahar' it is not used as rigidly in modern Punjabi. meridiemParse: /ਰਾਤ|ਸਵੇਰ|ਦੁਪਹਿਰ|ਸ਼ਾਮ/, meridiemHour: function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === 'ਰਾਤ') { return hour < 4 ? hour : hour + 12; } else if (meridiem === 'ਸਵੇਰ') { return hour; } else if (meridiem === 'ਦੁਪਹਿਰ') { return hour >= 10 ? hour : hour + 12; } else if (meridiem === 'ਸ਼ਾਮ') { return hour + 12; } }, meridiem: function (hour, minute, isLower) { if (hour < 4) { return 'ਰਾਤ'; } else if (hour < 10) { return 'ਸਵੇਰ'; } else if (hour < 17) { return 'ਦੁਪਹਿਰ'; } else if (hour < 20) { return 'ਸ਼ਾਮ'; } else { return 'ਰਾਤ'; } }, week: { dow: 0, // Sunday is the first day of the week. doy: 6 // The week that contains Jan 1st is the first week of the year. } }); var monthsNominative = 'styczeń_luty_marzec_kwiecień_maj_czerwiec_lipiec_sierpień_wrzesień_październik_listopad_grudzień'.split('_'), monthsSubjective = 'stycznia_lutego_marca_kwietnia_maja_czerwca_lipca_sierpnia_września_października_listopada_grudnia'.split('_'); function pl__plural(n) { return (n % 10 < 5) && (n % 10 > 1) && ((~~(n / 10) % 10) !== 1); } function pl__translate(number, withoutSuffix, key) { var result = number + ' '; switch (key) { case 'm': return withoutSuffix ? 'minuta' : 'minutę'; case 'mm': return result + (pl__plural(number) ? 'minuty' : 'minut'); case 'h': return withoutSuffix ? 'godzina' : 'godzinę'; case 'hh': return result + (pl__plural(number) ? 'godziny' : 'godzin'); case 'MM': return result + (pl__plural(number) ? 'miesiące' : 'miesięcy'); case 'yy': return result + (pl__plural(number) ? 'lata' : 'lat'); } } var pl = moment__default.defineLocale('pl', { months: function (momentToFormat, format) { if (format === '') { // Hack: if format empty we know this is used to generate // RegExp by moment. Give then back both valid forms of months // in RegExp ready format. return '(' + monthsSubjective[momentToFormat.month()] + '|' + monthsNominative[momentToFormat.month()] + ')'; } else if (/D MMMM/.test(format)) { return monthsSubjective[momentToFormat.month()]; } else { return monthsNominative[momentToFormat.month()]; } }, monthsShort: 'sty_lut_mar_kwi_maj_cze_lip_sie_wrz_paź_lis_gru'.split('_'), weekdays: 'niedziela_poniedziałek_wtorek_środa_czwartek_piątek_sobota'.split('_'), weekdaysShort: 'nie_pon_wt_śr_czw_pt_sb'.split('_'), weekdaysMin: 'Nd_Pn_Wt_Śr_Cz_Pt_So'.split('_'), longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD.MM.YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'dddd, D MMMM YYYY HH:mm' }, calendar: { sameDay: '[Dziś o] LT', nextDay: '[Jutro o] LT', nextWeek: '[W] dddd [o] LT', lastDay: '[Wczoraj o] LT', lastWeek: function () { switch (this.day()) { case 0: return '[W zeszłą niedzielę o] LT'; case 3: return '[W zeszłą środę o] LT'; case 6: return '[W zeszłą sobotę o] LT'; default: return '[W zeszły] dddd [o] LT'; } }, sameElse: 'L' }, relativeTime: { future: 'za %s', past: '%s temu', s: 'kilka sekund', m: pl__translate, mm: pl__translate, h: pl__translate, hh: pl__translate, d: '1 dzień', dd: '%d dni', M: 'miesiąc', MM: pl__translate, y: 'rok', yy: pl__translate }, ordinalParse: /\d{1,2}\./, ordinal: '%d.', week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); var pt_br = moment__default.defineLocale('pt-br', { months: 'Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro'.split('_'), monthsShort: 'Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez'.split('_'), weekdays: 'Domingo_Segunda-feira_Terça-feira_Quarta-feira_Quinta-feira_Sexta-feira_Sábado'.split('_'), weekdaysShort: 'Dom_Seg_Ter_Qua_Qui_Sex_Sáb'.split('_'), weekdaysMin: 'Dom_2ª_3ª_4ª_5ª_6ª_Sáb'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD/MM/YYYY', LL: 'D [de] MMMM [de] YYYY', LLL: 'D [de] MMMM [de] YYYY [às] HH:mm', LLLL: 'dddd, D [de] MMMM [de] YYYY [às] HH:mm' }, calendar: { sameDay: '[Hoje às] LT', nextDay: '[Amanhã às] LT', nextWeek: 'dddd [às] LT', lastDay: '[Ontem às] LT', lastWeek: function () { return (this.day() === 0 || this.day() === 6) ? '[Último] dddd [às] LT' : // Saturday + Sunday '[Última] dddd [às] LT'; // Monday - Friday }, sameElse: 'L' }, relativeTime: { future: 'em %s', past: '%s atrás', s: 'poucos segundos', m: 'um minuto', mm: '%d minutos', h: 'uma hora', hh: '%d horas', d: 'um dia', dd: '%d dias', M: 'um mês', MM: '%d meses', y: 'um ano', yy: '%d anos' }, ordinalParse: /\d{1,2}º/, ordinal: '%dº' }); var pt = moment__default.defineLocale('pt', { months: 'Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro'.split('_'), monthsShort: 'Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez'.split('_'), weekdays: 'Domingo_Segunda-Feira_Terça-Feira_Quarta-Feira_Quinta-Feira_Sexta-Feira_Sábado'.split('_'), weekdaysShort: 'Dom_Seg_Ter_Qua_Qui_Sex_Sáb'.split('_'), weekdaysMin: 'Dom_2ª_3ª_4ª_5ª_6ª_Sáb'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD/MM/YYYY', LL: 'D [de] MMMM [de] YYYY', LLL: 'D [de] MMMM [de] YYYY HH:mm', LLLL: 'dddd, D [de] MMMM [de] YYYY HH:mm' }, calendar: { sameDay: '[Hoje às] LT', nextDay: '[Amanhã às] LT', nextWeek: 'dddd [às] LT', lastDay: '[Ontem às] LT', lastWeek: function () { return (this.day() === 0 || this.day() === 6) ? '[Último] dddd [às] LT' : // Saturday + Sunday '[Última] dddd [às] LT'; // Monday - Friday }, sameElse: 'L' }, relativeTime: { future: 'em %s', past: 'há %s', s: 'segundos', m: 'um minuto', mm: '%d minutos', h: 'uma hora', hh: '%d horas', d: 'um dia', dd: '%d dias', M: 'um mês', MM: '%d meses', y: 'um ano', yy: '%d anos' }, ordinalParse: /\d{1,2}º/, ordinal: '%dº', week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); function ro__relativeTimeWithPlural(number, withoutSuffix, key) { var format = { 'mm': 'minute', 'hh': 'ore', 'dd': 'zile', 'MM': 'luni', 'yy': 'ani' }, separator = ' '; if (number % 100 >= 20 || (number >= 100 && number % 100 === 0)) { separator = ' de '; } return number + separator + format[key]; } var ro = moment__default.defineLocale('ro', { months: 'ianuarie_februarie_martie_aprilie_mai_iunie_iulie_august_septembrie_octombrie_noiembrie_decembrie'.split('_'), monthsShort: 'ian._febr._mart._apr._mai_iun._iul._aug._sept._oct._nov._dec.'.split('_'), monthsParseExact: true, weekdays: 'duminică_luni_marți_miercuri_joi_vineri_sâmbătă'.split('_'), weekdaysShort: 'Dum_Lun_Mar_Mie_Joi_Vin_Sâm'.split('_'), weekdaysMin: 'Du_Lu_Ma_Mi_Jo_Vi_Sâ'.split('_'), longDateFormat: { LT: 'H:mm', LTS: 'H:mm:ss', L: 'DD.MM.YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY H:mm', LLLL: 'dddd, D MMMM YYYY H:mm' }, calendar: { sameDay: '[azi la] LT', nextDay: '[mâine la] LT', nextWeek: 'dddd [la] LT', lastDay: '[ieri la] LT', lastWeek: '[fosta] dddd [la] LT', sameElse: 'L' }, relativeTime: { future: 'peste %s', past: '%s în urmă', s: 'câteva secunde', m: 'un minut', mm: ro__relativeTimeWithPlural, h: 'o oră', hh: ro__relativeTimeWithPlural, d: 'o zi', dd: ro__relativeTimeWithPlural, M: 'o lună', MM: ro__relativeTimeWithPlural, y: 'un an', yy: ro__relativeTimeWithPlural }, week: { dow: 1, // Monday is the first day of the week. doy: 7 // The week that contains Jan 1st is the first week of the year. } }); function ru__plural(word, num) { var forms = word.split('_'); return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]); } function ru__relativeTimeWithPlural(number, withoutSuffix, key) { var format = { 'mm': withoutSuffix ? 'минута_минуты_минут' : 'минуту_минуты_минут', 'hh': 'час_часа_часов', 'dd': 'день_дня_дней', 'MM': 'месяц_месяца_месяцев', 'yy': 'год_года_лет' }; if (key === 'm') { return withoutSuffix ? 'минута' : 'минуту'; } else { return number + ' ' + ru__plural(format[key], +number); } } var monthsParse = [/^янв/i, /^фев/i, /^мар/i, /^апр/i, /^ма[йя]/i, /^июн/i, /^июл/i, /^авг/i, /^сен/i, /^окт/i, /^ноя/i, /^дек/i]; // http://new.gramota.ru/spravka/rules/139-prop : § 103 // Сокращения месяцев: http://new.gramota.ru/spravka/buro/search-answer?s=242637 // CLDR data: http://www.unicode.org/cldr/charts/28/summary/ru.html#1753 var ru = moment__default.defineLocale('ru', { months: { format: 'января_февраля_марта_апреля_мая_июня_июля_августа_сентября_октября_ноября_декабря'.split('_'), standalone: 'январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь'.split('_') }, monthsShort: { // по CLDR именно "июл." и "июн.", но какой смысл менять букву на точку ? format: 'янв._февр._мар._апр._мая_июня_июля_авг._сент._окт._нояб._дек.'.split('_'), standalone: 'янв._февр._март_апр._май_июнь_июль_авг._сент._окт._нояб._дек.'.split('_') }, weekdays: { standalone: 'воскресенье_понедельник_вторник_среда_четверг_пятница_суббота'.split('_'), format: 'воскресенье_понедельник_вторник_среду_четверг_пятницу_субботу'.split('_'), isFormat: /\[ ?[Вв] ?(?:прошлую|следующую|эту)? ?\] ?dddd/ }, weekdaysShort: 'вс_пн_вт_ср_чт_пт_сб'.split('_'), weekdaysMin: 'вс_пн_вт_ср_чт_пт_сб'.split('_'), monthsParse: monthsParse, longMonthsParse: monthsParse, shortMonthsParse: monthsParse, // полные названия с падежами, по три буквы, для некоторых, по 4 буквы, сокращения с точкой и без точки monthsRegex: /^(январ[ья]|янв\.?|феврал[ья]|февр?\.?|марта?|мар\.?|апрел[ья]|апр\.?|ма[йя]|июн[ья]|июн\.?|июл[ья]|июл\.?|августа?|авг\.?|сентябр[ья]|сент?\.?|октябр[ья]|окт\.?|ноябр[ья]|нояб?\.?|декабр[ья]|дек\.?)/i, // копия предыдущего monthsShortRegex: /^(январ[ья]|янв\.?|феврал[ья]|февр?\.?|марта?|мар\.?|апрел[ья]|апр\.?|ма[йя]|июн[ья]|июн\.?|июл[ья]|июл\.?|августа?|авг\.?|сентябр[ья]|сент?\.?|октябр[ья]|окт\.?|ноябр[ья]|нояб?\.?|декабр[ья]|дек\.?)/i, // полные названия с падежами monthsStrictRegex: /^(январ[яь]|феврал[яь]|марта?|апрел[яь]|ма[яй]|июн[яь]|июл[яь]|августа?|сентябр[яь]|октябр[яь]|ноябр[яь]|декабр[яь])/i, // Выражение, которое соотвествует только сокращённым формам monthsShortStrictRegex: /^(янв\.|февр?\.|мар[т.]|апр\.|ма[яй]|июн[ья.]|июл[ья.]|авг\.|сент?\.|окт\.|нояб?\.|дек\.)/i, longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD.MM.YYYY', LL: 'D MMMM YYYY г.', LLL: 'D MMMM YYYY г., HH:mm', LLLL: 'dddd, D MMMM YYYY г., HH:mm' }, calendar: { sameDay: '[Сегодня в] LT', nextDay: '[Завтра в] LT', lastDay: '[Вчера в] LT', nextWeek: function (now) { if (now.week() !== this.week()) { switch (this.day()) { case 0: return '[В следующее] dddd [в] LT'; case 1: case 2: case 4: return '[В следующий] dddd [в] LT'; case 3: case 5: case 6: return '[В следующую] dddd [в] LT'; } } else { if (this.day() === 2) { return '[Во] dddd [в] LT'; } else { return '[В] dddd [в] LT'; } } }, lastWeek: function (now) { if (now.week() !== this.week()) { switch (this.day()) { case 0: return '[В прошлое] dddd [в] LT'; case 1: case 2: case 4: return '[В прошлый] dddd [в] LT'; case 3: case 5: case 6: return '[В прошлую] dddd [в] LT'; } } else { if (this.day() === 2) { return '[Во] dddd [в] LT'; } else { return '[В] dddd [в] LT'; } } }, sameElse: 'L' }, relativeTime: { future: 'через %s', past: '%s назад', s: 'несколько секунд', m: ru__relativeTimeWithPlural, mm: ru__relativeTimeWithPlural, h: 'час', hh: ru__relativeTimeWithPlural, d: 'день', dd: ru__relativeTimeWithPlural, M: 'месяц', MM: ru__relativeTimeWithPlural, y: 'год', yy: ru__relativeTimeWithPlural }, meridiemParse: /ночи|утра|дня|вечера/i, isPM: function (input) { return /^(дня|вечера)$/.test(input); }, meridiem: function (hour, minute, isLower) { if (hour < 4) { return 'ночи'; } else if (hour < 12) { return 'утра'; } else if (hour < 17) { return 'дня'; } else { return 'вечера'; } }, ordinalParse: /\d{1,2}-(й|го|я)/, ordinal: function (number, period) { switch (period) { case 'M': case 'd': case 'DDD': return number + '-й'; case 'D': return number + '-го'; case 'w': case 'W': return number + '-я'; default: return number; } }, week: { dow: 1, // Monday is the first day of the week. doy: 7 // The week that contains Jan 1st is the first week of the year. } }); var se = moment__default.defineLocale('se', { months: 'ođđajagemánnu_guovvamánnu_njukčamánnu_cuoŋománnu_miessemánnu_geassemánnu_suoidnemánnu_borgemánnu_čakčamánnu_golggotmánnu_skábmamánnu_juovlamánnu'.split('_'), monthsShort: 'ođđj_guov_njuk_cuo_mies_geas_suoi_borg_čakč_golg_skáb_juov'.split('_'), weekdays: 'sotnabeaivi_vuossárga_maŋŋebárga_gaskavahkku_duorastat_bearjadat_lávvardat'.split('_'), weekdaysShort: 'sotn_vuos_maŋ_gask_duor_bear_láv'.split('_'), weekdaysMin: 's_v_m_g_d_b_L'.split('_'), longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD.MM.YYYY', LL: 'MMMM D. [b.] YYYY', LLL: 'MMMM D. [b.] YYYY [ti.] HH:mm', LLLL: 'dddd, MMMM D. [b.] YYYY [ti.] HH:mm' }, calendar: { sameDay: '[otne ti] LT', nextDay: '[ihttin ti] LT', nextWeek: 'dddd [ti] LT', lastDay: '[ikte ti] LT', lastWeek: '[ovddit] dddd [ti] LT', sameElse: 'L' }, relativeTime: { future: '%s geažes', past: 'maŋit %s', s: 'moadde sekunddat', m: 'okta minuhta', mm: '%d minuhtat', h: 'okta diimmu', hh: '%d diimmut', d: 'okta beaivi', dd: '%d beaivvit', M: 'okta mánnu', MM: '%d mánut', y: 'okta jahki', yy: '%d jagit' }, ordinalParse: /\d{1,2}\./, ordinal: '%d.', week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); /*jshint -W100*/ var si = moment__default.defineLocale('si', { months: 'ජනවාරි_පෙබරවාරි_මාර්තු_අප්‍රේල්_මැයි_ජූනි_ජූලි_අගෝස්තු_සැප්තැම්බර්_ඔක්තෝබර්_නොවැම්බර්_දෙසැම්බර්'.split('_'), monthsShort: 'ජන_පෙබ_මාර්_අප්_මැයි_ජූනි_ජූලි_අගෝ_සැප්_ඔක්_නොවැ_දෙසැ'.split('_'), weekdays: 'ඉරිදා_සඳුදා_අඟහරුවාදා_බදාදා_බ්‍රහස්පතින්දා_සිකුරාදා_සෙනසුරාදා'.split('_'), weekdaysShort: 'ඉරි_සඳු_අඟ_බදා_බ්‍රහ_සිකු_සෙන'.split('_'), weekdaysMin: 'ඉ_ස_අ_බ_බ්‍ර_සි_සෙ'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'a h:mm', LTS: 'a h:mm:ss', L: 'YYYY/MM/DD', LL: 'YYYY MMMM D', LLL: 'YYYY MMMM D, a h:mm', LLLL: 'YYYY MMMM D [වැනි] dddd, a h:mm:ss' }, calendar: { sameDay: '[අද] LT[ට]', nextDay: '[හෙට] LT[ට]', nextWeek: 'dddd LT[ට]', lastDay: '[ඊයේ] LT[ට]', lastWeek: '[පසුගිය] dddd LT[ට]', sameElse: 'L' }, relativeTime: { future: '%sකින්', past: '%sකට පෙර', s: 'තත්පර කිහිපය', m: 'මිනිත්තුව', mm: 'මිනිත්තු %d', h: 'පැය', hh: 'පැය %d', d: 'දිනය', dd: 'දින %d', M: 'මාසය', MM: 'මාස %d', y: 'වසර', yy: 'වසර %d' }, ordinalParse: /\d{1,2} වැනි/, ordinal: function (number) { return number + ' වැනි'; }, meridiemParse: /පෙර වරු|පස් වරු|පෙ.ව|ප.ව./, isPM: function (input) { return input === 'ප.ව.' || input === 'පස් වරු'; }, meridiem: function (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'ප.ව.' : 'පස් වරු'; } else { return isLower ? 'පෙ.ව.' : 'පෙර වරු'; } } }); var sk__months = 'január_február_marec_apríl_máj_jún_júl_august_september_október_november_december'.split('_'), sk__monthsShort = 'jan_feb_mar_apr_máj_jún_júl_aug_sep_okt_nov_dec'.split('_'); function sk__plural(n) { return (n > 1) && (n < 5); } function sk__translate(number, withoutSuffix, key, isFuture) { var result = number + ' '; switch (key) { case 's': // a few seconds / in a few seconds / a few seconds ago return (withoutSuffix || isFuture) ? 'pár sekúnd' : 'pár sekundami'; case 'm': // a minute / in a minute / a minute ago return withoutSuffix ? 'minúta' : (isFuture ? 'minútu' : 'minútou'); case 'mm': // 9 minutes / in 9 minutes / 9 minutes ago if (withoutSuffix || isFuture) { return result + (sk__plural(number) ? 'minúty' : 'minút'); } else { return result + 'minútami'; } break; case 'h': // an hour / in an hour / an hour ago return withoutSuffix ? 'hodina' : (isFuture ? 'hodinu' : 'hodinou'); case 'hh': // 9 hours / in 9 hours / 9 hours ago if (withoutSuffix || isFuture) { return result + (sk__plural(number) ? 'hodiny' : 'hodín'); } else { return result + 'hodinami'; } break; case 'd': // a day / in a day / a day ago return (withoutSuffix || isFuture) ? 'deň' : 'dňom'; case 'dd': // 9 days / in 9 days / 9 days ago if (withoutSuffix || isFuture) { return result + (sk__plural(number) ? 'dni' : 'dní'); } else { return result + 'dňami'; } break; case 'M': // a month / in a month / a month ago return (withoutSuffix || isFuture) ? 'mesiac' : 'mesiacom'; case 'MM': // 9 months / in 9 months / 9 months ago if (withoutSuffix || isFuture) { return result + (sk__plural(number) ? 'mesiace' : 'mesiacov'); } else { return result + 'mesiacmi'; } break; case 'y': // a year / in a year / a year ago return (withoutSuffix || isFuture) ? 'rok' : 'rokom'; case 'yy': // 9 years / in 9 years / 9 years ago if (withoutSuffix || isFuture) { return result + (sk__plural(number) ? 'roky' : 'rokov'); } else { return result + 'rokmi'; } break; } } var sk = moment__default.defineLocale('sk', { months: sk__months, monthsShort: sk__monthsShort, weekdays: 'nedeľa_pondelok_utorok_streda_štvrtok_piatok_sobota'.split('_'), weekdaysShort: 'ne_po_ut_st_št_pi_so'.split('_'), weekdaysMin: 'ne_po_ut_st_št_pi_so'.split('_'), longDateFormat: { LT: 'H:mm', LTS: 'H:mm:ss', L: 'DD.MM.YYYY', LL: 'D. MMMM YYYY', LLL: 'D. MMMM YYYY H:mm', LLLL: 'dddd D. MMMM YYYY H:mm' }, calendar: { sameDay: '[dnes o] LT', nextDay: '[zajtra o] LT', nextWeek: function () { switch (this.day()) { case 0: return '[v nedeľu o] LT'; case 1: case 2: return '[v] dddd [o] LT'; case 3: return '[v stredu o] LT'; case 4: return '[vo štvrtok o] LT'; case 5: return '[v piatok o] LT'; case 6: return '[v sobotu o] LT'; } }, lastDay: '[včera o] LT', lastWeek: function () { switch (this.day()) { case 0: return '[minulú nedeľu o] LT'; case 1: case 2: return '[minulý] dddd [o] LT'; case 3: return '[minulú stredu o] LT'; case 4: case 5: return '[minulý] dddd [o] LT'; case 6: return '[minulú sobotu o] LT'; } }, sameElse: 'L' }, relativeTime: { future: 'za %s', past: 'pred %s', s: sk__translate, m: sk__translate, mm: sk__translate, h: sk__translate, hh: sk__translate, d: sk__translate, dd: sk__translate, M: sk__translate, MM: sk__translate, y: sk__translate, yy: sk__translate }, ordinalParse: /\d{1,2}\./, ordinal: '%d.', week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); function sl__processRelativeTime(number, withoutSuffix, key, isFuture) { var result = number + ' '; switch (key) { case 's': return withoutSuffix || isFuture ? 'nekaj sekund' : 'nekaj sekundami'; case 'm': return withoutSuffix ? 'ena minuta' : 'eno minuto'; case 'mm': if (number === 1) { result += withoutSuffix ? 'minuta' : 'minuto'; } else if (number === 2) { result += withoutSuffix || isFuture ? 'minuti' : 'minutama'; } else if (number < 5) { result += withoutSuffix || isFuture ? 'minute' : 'minutami'; } else { result += withoutSuffix || isFuture ? 'minut' : 'minutami'; } return result; case 'h': return withoutSuffix ? 'ena ura' : 'eno uro'; case 'hh': if (number === 1) { result += withoutSuffix ? 'ura' : 'uro'; } else if (number === 2) { result += withoutSuffix || isFuture ? 'uri' : 'urama'; } else if (number < 5) { result += withoutSuffix || isFuture ? 'ure' : 'urami'; } else { result += withoutSuffix || isFuture ? 'ur' : 'urami'; } return result; case 'd': return withoutSuffix || isFuture ? 'en dan' : 'enim dnem'; case 'dd': if (number === 1) { result += withoutSuffix || isFuture ? 'dan' : 'dnem'; } else if (number === 2) { result += withoutSuffix || isFuture ? 'dni' : 'dnevoma'; } else { result += withoutSuffix || isFuture ? 'dni' : 'dnevi'; } return result; case 'M': return withoutSuffix || isFuture ? 'en mesec' : 'enim mesecem'; case 'MM': if (number === 1) { result += withoutSuffix || isFuture ? 'mesec' : 'mesecem'; } else if (number === 2) { result += withoutSuffix || isFuture ? 'meseca' : 'mesecema'; } else if (number < 5) { result += withoutSuffix || isFuture ? 'mesece' : 'meseci'; } else { result += withoutSuffix || isFuture ? 'mesecev' : 'meseci'; } return result; case 'y': return withoutSuffix || isFuture ? 'eno leto' : 'enim letom'; case 'yy': if (number === 1) { result += withoutSuffix || isFuture ? 'leto' : 'letom'; } else if (number === 2) { result += withoutSuffix || isFuture ? 'leti' : 'letoma'; } else if (number < 5) { result += withoutSuffix || isFuture ? 'leta' : 'leti'; } else { result += withoutSuffix || isFuture ? 'let' : 'leti'; } return result; } } var sl = moment__default.defineLocale('sl', { months: 'januar_februar_marec_april_maj_junij_julij_avgust_september_oktober_november_december'.split('_'), monthsShort: 'jan._feb._mar._apr._maj._jun._jul._avg._sep._okt._nov._dec.'.split('_'), monthsParseExact: true, weekdays: 'nedelja_ponedeljek_torek_sreda_četrtek_petek_sobota'.split('_'), weekdaysShort: 'ned._pon._tor._sre._čet._pet._sob.'.split('_'), weekdaysMin: 'ne_po_to_sr_če_pe_so'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'H:mm', LTS: 'H:mm:ss', L: 'DD. MM. YYYY', LL: 'D. MMMM YYYY', LLL: 'D. MMMM YYYY H:mm', LLLL: 'dddd, D. MMMM YYYY H:mm' }, calendar: { sameDay: '[danes ob] LT', nextDay: '[jutri ob] LT', nextWeek: function () { switch (this.day()) { case 0: return '[v] [nedeljo] [ob] LT'; case 3: return '[v] [sredo] [ob] LT'; case 6: return '[v] [soboto] [ob] LT'; case 1: case 2: case 4: case 5: return '[v] dddd [ob] LT'; } }, lastDay: '[včeraj ob] LT', lastWeek: function () { switch (this.day()) { case 0: return '[prejšnjo] [nedeljo] [ob] LT'; case 3: return '[prejšnjo] [sredo] [ob] LT'; case 6: return '[prejšnjo] [soboto] [ob] LT'; case 1: case 2: case 4: case 5: return '[prejšnji] dddd [ob] LT'; } }, sameElse: 'L' }, relativeTime: { future: 'čez %s', past: 'pred %s', s: sl__processRelativeTime, m: sl__processRelativeTime, mm: sl__processRelativeTime, h: sl__processRelativeTime, hh: sl__processRelativeTime, d: sl__processRelativeTime, dd: sl__processRelativeTime, M: sl__processRelativeTime, MM: sl__processRelativeTime, y: sl__processRelativeTime, yy: sl__processRelativeTime }, ordinalParse: /\d{1,2}\./, ordinal: '%d.', week: { dow: 1, // Monday is the first day of the week. doy: 7 // The week that contains Jan 1st is the first week of the year. } }); var sq = moment__default.defineLocale('sq', { months: 'Janar_Shkurt_Mars_Prill_Maj_Qershor_Korrik_Gusht_Shtator_Tetor_Nëntor_Dhjetor'.split('_'), monthsShort: 'Jan_Shk_Mar_Pri_Maj_Qer_Kor_Gus_Sht_Tet_Nën_Dhj'.split('_'), weekdays: 'E Diel_E Hënë_E Martë_E Mërkurë_E Enjte_E Premte_E Shtunë'.split('_'), weekdaysShort: 'Die_Hën_Mar_Mër_Enj_Pre_Sht'.split('_'), weekdaysMin: 'D_H_Ma_Më_E_P_Sh'.split('_'), weekdaysParseExact: true, meridiemParse: /PD|MD/, isPM: function (input) { return input.charAt(0) === 'M'; }, meridiem: function (hours, minutes, isLower) { return hours < 12 ? 'PD' : 'MD'; }, longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'dddd, D MMMM YYYY HH:mm' }, calendar: { sameDay: '[Sot në] LT', nextDay: '[Nesër në] LT', nextWeek: 'dddd [në] LT', lastDay: '[Dje në] LT', lastWeek: 'dddd [e kaluar në] LT', sameElse: 'L' }, relativeTime: { future: 'në %s', past: '%s më parë', s: 'disa sekonda', m: 'një minutë', mm: '%d minuta', h: 'një orë', hh: '%d orë', d: 'një ditë', dd: '%d ditë', M: 'një muaj', MM: '%d muaj', y: 'një vit', yy: '%d vite' }, ordinalParse: /\d{1,2}\./, ordinal: '%d.', week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); var sr_cyrl__translator = { words: { //Different grammatical cases m: ['један минут', 'једне минуте'], mm: ['минут', 'минуте', 'минута'], h: ['један сат', 'једног сата'], hh: ['сат', 'сата', 'сати'], dd: ['дан', 'дана', 'дана'], MM: ['месец', 'месеца', 'месеци'], yy: ['година', 'године', 'година'] }, correctGrammaticalCase: function (number, wordKey) { return number === 1 ? wordKey[0] : (number >= 2 && number <= 4 ? wordKey[1] : wordKey[2]); }, translate: function (number, withoutSuffix, key) { var wordKey = sr_cyrl__translator.words[key]; if (key.length === 1) { return withoutSuffix ? wordKey[0] : wordKey[1]; } else { return number + ' ' + sr_cyrl__translator.correctGrammaticalCase(number, wordKey); } } }; var sr_cyrl = moment__default.defineLocale('sr-cyrl', { months: 'јануар_фебруар_март_април_мај_јун_јул_август_септембар_октобар_новембар_децембар'.split('_'), monthsShort: 'јан._феб._мар._апр._мај_јун_јул_авг._сеп._окт._нов._дец.'.split('_'), monthsParseExact: true, weekdays: 'недеља_понедељак_уторак_среда_четвртак_петак_субота'.split('_'), weekdaysShort: 'нед._пон._уто._сре._чет._пет._суб.'.split('_'), weekdaysMin: 'не_по_ут_ср_че_пе_су'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'H:mm', LTS: 'H:mm:ss', L: 'DD. MM. YYYY', LL: 'D. MMMM YYYY', LLL: 'D. MMMM YYYY H:mm', LLLL: 'dddd, D. MMMM YYYY H:mm' }, calendar: { sameDay: '[данас у] LT', nextDay: '[сутра у] LT', nextWeek: function () { switch (this.day()) { case 0: return '[у] [недељу] [у] LT'; case 3: return '[у] [среду] [у] LT'; case 6: return '[у] [суботу] [у] LT'; case 1: case 2: case 4: case 5: return '[у] dddd [у] LT'; } }, lastDay: '[јуче у] LT', lastWeek: function () { var lastWeekDays = [ '[прошле] [недеље] [у] LT', '[прошлог] [понедељка] [у] LT', '[прошлог] [уторка] [у] LT', '[прошле] [среде] [у] LT', '[прошлог] [четвртка] [у] LT', '[прошлог] [петка] [у] LT', '[прошле] [суботе] [у] LT' ]; return lastWeekDays[this.day()]; }, sameElse: 'L' }, relativeTime: { future: 'за %s', past: 'пре %s', s: 'неколико секунди', m: sr_cyrl__translator.translate, mm: sr_cyrl__translator.translate, h: sr_cyrl__translator.translate, hh: sr_cyrl__translator.translate, d: 'дан', dd: sr_cyrl__translator.translate, M: 'месец', MM: sr_cyrl__translator.translate, y: 'годину', yy: sr_cyrl__translator.translate }, ordinalParse: /\d{1,2}\./, ordinal: '%d.', week: { dow: 1, // Monday is the first day of the week. doy: 7 // The week that contains Jan 1st is the first week of the year. } }); var sr__translator = { words: { //Different grammatical cases m: ['jedan minut', 'jedne minute'], mm: ['minut', 'minute', 'minuta'], h: ['jedan sat', 'jednog sata'], hh: ['sat', 'sata', 'sati'], dd: ['dan', 'dana', 'dana'], MM: ['mesec', 'meseca', 'meseci'], yy: ['godina', 'godine', 'godina'] }, correctGrammaticalCase: function (number, wordKey) { return number === 1 ? wordKey[0] : (number >= 2 && number <= 4 ? wordKey[1] : wordKey[2]); }, translate: function (number, withoutSuffix, key) { var wordKey = sr__translator.words[key]; if (key.length === 1) { return withoutSuffix ? wordKey[0] : wordKey[1]; } else { return number + ' ' + sr__translator.correctGrammaticalCase(number, wordKey); } } }; var sr = moment__default.defineLocale('sr', { months: 'januar_februar_mart_april_maj_jun_jul_avgust_septembar_oktobar_novembar_decembar'.split('_'), monthsShort: 'jan._feb._mar._apr._maj_jun_jul_avg._sep._okt._nov._dec.'.split('_'), monthsParseExact: true, weekdays: 'nedelja_ponedeljak_utorak_sreda_četvrtak_petak_subota'.split('_'), weekdaysShort: 'ned._pon._uto._sre._čet._pet._sub.'.split('_'), weekdaysMin: 'ne_po_ut_sr_če_pe_su'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'H:mm', LTS: 'H:mm:ss', L: 'DD. MM. YYYY', LL: 'D. MMMM YYYY', LLL: 'D. MMMM YYYY H:mm', LLLL: 'dddd, D. MMMM YYYY H:mm' }, calendar: { sameDay: '[danas u] LT', nextDay: '[sutra u] LT', nextWeek: function () { switch (this.day()) { case 0: return '[u] [nedelju] [u] LT'; case 3: return '[u] [sredu] [u] LT'; case 6: return '[u] [subotu] [u] LT'; case 1: case 2: case 4: case 5: return '[u] dddd [u] LT'; } }, lastDay: '[juče u] LT', lastWeek: function () { var lastWeekDays = [ '[prošle] [nedelje] [u] LT', '[prošlog] [ponedeljka] [u] LT', '[prošlog] [utorka] [u] LT', '[prošle] [srede] [u] LT', '[prošlog] [četvrtka] [u] LT', '[prošlog] [petka] [u] LT', '[prošle] [subote] [u] LT' ]; return lastWeekDays[this.day()]; }, sameElse: 'L' }, relativeTime: { future: 'za %s', past: 'pre %s', s: 'nekoliko sekundi', m: sr__translator.translate, mm: sr__translator.translate, h: sr__translator.translate, hh: sr__translator.translate, d: 'dan', dd: sr__translator.translate, M: 'mesec', MM: sr__translator.translate, y: 'godinu', yy: sr__translator.translate }, ordinalParse: /\d{1,2}\./, ordinal: '%d.', week: { dow: 1, // Monday is the first day of the week. doy: 7 // The week that contains Jan 1st is the first week of the year. } }); var ss = moment__default.defineLocale('ss', { months: "Bhimbidvwane_Indlovana_Indlov'lenkhulu_Mabasa_Inkhwekhweti_Inhlaba_Kholwane_Ingci_Inyoni_Imphala_Lweti_Ingongoni".split('_'), monthsShort: 'Bhi_Ina_Inu_Mab_Ink_Inh_Kho_Igc_Iny_Imp_Lwe_Igo'.split('_'), weekdays: 'Lisontfo_Umsombuluko_Lesibili_Lesitsatfu_Lesine_Lesihlanu_Umgcibelo'.split('_'), weekdaysShort: 'Lis_Umb_Lsb_Les_Lsi_Lsh_Umg'.split('_'), weekdaysMin: 'Li_Us_Lb_Lt_Ls_Lh_Ug'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'h:mm A', LTS: 'h:mm:ss A', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY h:mm A', LLLL: 'dddd, D MMMM YYYY h:mm A' }, calendar: { sameDay: '[Namuhla nga] LT', nextDay: '[Kusasa nga] LT', nextWeek: 'dddd [nga] LT', lastDay: '[Itolo nga] LT', lastWeek: 'dddd [leliphelile] [nga] LT', sameElse: 'L' }, relativeTime: { future: 'nga %s', past: 'wenteka nga %s', s: 'emizuzwana lomcane', m: 'umzuzu', mm: '%d emizuzu', h: 'lihora', hh: '%d emahora', d: 'lilanga', dd: '%d emalanga', M: 'inyanga', MM: '%d tinyanga', y: 'umnyaka', yy: '%d iminyaka' }, meridiemParse: /ekuseni|emini|entsambama|ebusuku/, meridiem: function (hours, minutes, isLower) { if (hours < 11) { return 'ekuseni'; } else if (hours < 15) { return 'emini'; } else if (hours < 19) { return 'entsambama'; } else { return 'ebusuku'; } }, meridiemHour: function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === 'ekuseni') { return hour; } else if (meridiem === 'emini') { return hour >= 11 ? hour : hour + 12; } else if (meridiem === 'entsambama' || meridiem === 'ebusuku') { if (hour === 0) { return 0; } return hour + 12; } }, ordinalParse: /\d{1,2}/, ordinal: '%d', week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); var sv = moment__default.defineLocale('sv', { months: 'januari_februari_mars_april_maj_juni_juli_augusti_september_oktober_november_december'.split('_'), monthsShort: 'jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec'.split('_'), weekdays: 'söndag_måndag_tisdag_onsdag_torsdag_fredag_lördag'.split('_'), weekdaysShort: 'sön_mån_tis_ons_tor_fre_lör'.split('_'), weekdaysMin: 'sö_må_ti_on_to_fr_lö'.split('_'), longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'YYYY-MM-DD', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY [kl.] HH:mm', LLLL: 'dddd D MMMM YYYY [kl.] HH:mm', lll: 'D MMM YYYY HH:mm', llll: 'ddd D MMM YYYY HH:mm' }, calendar: { sameDay: '[Idag] LT', nextDay: '[Imorgon] LT', lastDay: '[Igår] LT', nextWeek: '[På] dddd LT', lastWeek: '[I] dddd[s] LT', sameElse: 'L' }, relativeTime: { future: 'om %s', past: 'för %s sedan', s: 'några sekunder', m: 'en minut', mm: '%d minuter', h: 'en timme', hh: '%d timmar', d: 'en dag', dd: '%d dagar', M: 'en månad', MM: '%d månader', y: 'ett år', yy: '%d år' }, ordinalParse: /\d{1,2}(e|a)/, ordinal: function (number) { var b = number % 10, output = (~~(number % 100 / 10) === 1) ? 'e' : (b === 1) ? 'a' : (b === 2) ? 'a' : (b === 3) ? 'e' : 'e'; return number + output; }, week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); var sw = moment__default.defineLocale('sw', { months: 'Januari_Februari_Machi_Aprili_Mei_Juni_Julai_Agosti_Septemba_Oktoba_Novemba_Desemba'.split('_'), monthsShort: 'Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ago_Sep_Okt_Nov_Des'.split('_'), weekdays: 'Jumapili_Jumatatu_Jumanne_Jumatano_Alhamisi_Ijumaa_Jumamosi'.split('_'), weekdaysShort: 'Jpl_Jtat_Jnne_Jtan_Alh_Ijm_Jmos'.split('_'), weekdaysMin: 'J2_J3_J4_J5_Al_Ij_J1'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD.MM.YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'dddd, D MMMM YYYY HH:mm' }, calendar: { sameDay: '[leo saa] LT', nextDay: '[kesho saa] LT', nextWeek: '[wiki ijayo] dddd [saat] LT', lastDay: '[jana] LT', lastWeek: '[wiki iliyopita] dddd [saat] LT', sameElse: 'L' }, relativeTime: { future: '%s baadaye', past: 'tokea %s', s: 'hivi punde', m: 'dakika moja', mm: 'dakika %d', h: 'saa limoja', hh: 'masaa %d', d: 'siku moja', dd: 'masiku %d', M: 'mwezi mmoja', MM: 'miezi %d', y: 'mwaka mmoja', yy: 'miaka %d' }, week: { dow: 1, // Monday is the first day of the week. doy: 7 // The week that contains Jan 1st is the first week of the year. } }); var ta__symbolMap = { '1': '௧', '2': '௨', '3': '௩', '4': '௪', '5': '௫', '6': '௬', '7': '௭', '8': '௮', '9': '௯', '0': '௦' }, ta__numberMap = { '௧': '1', '௨': '2', '௩': '3', '௪': '4', '௫': '5', '௬': '6', '௭': '7', '௮': '8', '௯': '9', '௦': '0' }; var ta = moment__default.defineLocale('ta', { months: 'ஜனவரி_பிப்ரவரி_மார்ச்_ஏப்ரல்_மே_ஜூன்_ஜூலை_ஆகஸ்ட்_செப்டெம்பர்_அக்டோபர்_நவம்பர்_டிசம்பர்'.split('_'), monthsShort: 'ஜனவரி_பிப்ரவரி_மார்ச்_ஏப்ரல்_மே_ஜூன்_ஜூலை_ஆகஸ்ட்_செப்டெம்பர்_அக்டோபர்_நவம்பர்_டிசம்பர்'.split('_'), weekdays: 'ஞாயிற்றுக்கிழமை_திங்கட்கிழமை_செவ்வாய்கிழமை_புதன்கிழமை_வியாழக்கிழமை_வெள்ளிக்கிழமை_சனிக்கிழமை'.split('_'), weekdaysShort: 'ஞாயிறு_திங்கள்_செவ்வாய்_புதன்_வியாழன்_வெள்ளி_சனி'.split('_'), weekdaysMin: 'ஞா_தி_செ_பு_வி_வெ_ச'.split('_'), longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY, HH:mm', LLLL: 'dddd, D MMMM YYYY, HH:mm' }, calendar: { sameDay: '[இன்று] LT', nextDay: '[நாளை] LT', nextWeek: 'dddd, LT', lastDay: '[நேற்று] LT', lastWeek: '[கடந்த வாரம்] dddd, LT', sameElse: 'L' }, relativeTime: { future: '%s இல்', past: '%s முன்', s: 'ஒரு சில விநாடிகள்', m: 'ஒரு நிமிடம்', mm: '%d நிமிடங்கள்', h: 'ஒரு மணி நேரம்', hh: '%d மணி நேரம்', d: 'ஒரு நாள்', dd: '%d நாட்கள்', M: 'ஒரு மாதம்', MM: '%d மாதங்கள்', y: 'ஒரு வருடம்', yy: '%d ஆண்டுகள்' }, ordinalParse: /\d{1,2}வது/, ordinal: function (number) { return number + 'வது'; }, preparse: function (string) { return string.replace(/[௧௨௩௪௫௬௭௮௯௦]/g, function (match) { return ta__numberMap[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return ta__symbolMap[match]; }); }, // refer http://ta.wikipedia.org/s/1er1 meridiemParse: /யாமம்|வைகறை|காலை|நண்பகல்|எற்பாடு|மாலை/, meridiem: function (hour, minute, isLower) { if (hour < 2) { return ' யாமம்'; } else if (hour < 6) { return ' வைகறை'; // வைகறை } else if (hour < 10) { return ' காலை'; // காலை } else if (hour < 14) { return ' நண்பகல்'; // நண்பகல் } else if (hour < 18) { return ' எற்பாடு'; // எற்பாடு } else if (hour < 22) { return ' மாலை'; // மாலை } else { return ' யாமம்'; } }, meridiemHour: function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === 'யாமம்') { return hour < 2 ? hour : hour + 12; } else if (meridiem === 'வைகறை' || meridiem === 'காலை') { return hour; } else if (meridiem === 'நண்பகல்') { return hour >= 10 ? hour : hour + 12; } else { return hour + 12; } }, week: { dow: 0, // Sunday is the first day of the week. doy: 6 // The week that contains Jan 1st is the first week of the year. } }); var te = moment__default.defineLocale('te', { months: 'జనవరి_ఫిబ్రవరి_మార్చి_ఏప్రిల్_మే_జూన్_జూలై_ఆగస్టు_సెప్టెంబర్_అక్టోబర్_నవంబర్_డిసెంబర్'.split('_'), monthsShort: 'జన._ఫిబ్ర._మార్చి_ఏప్రి._మే_జూన్_జూలై_ఆగ._సెప్._అక్టో._నవ._డిసె.'.split('_'), monthsParseExact: true, weekdays: 'ఆదివారం_సోమవారం_మంగళవారం_బుధవారం_గురువారం_శుక్రవారం_శనివారం'.split('_'), weekdaysShort: 'ఆది_సోమ_మంగళ_బుధ_గురు_శుక్ర_శని'.split('_'), weekdaysMin: 'ఆ_సో_మం_బు_గు_శు_శ'.split('_'), longDateFormat: { LT: 'A h:mm', LTS: 'A h:mm:ss', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY, A h:mm', LLLL: 'dddd, D MMMM YYYY, A h:mm' }, calendar: { sameDay: '[నేడు] LT', nextDay: '[రేపు] LT', nextWeek: 'dddd, LT', lastDay: '[నిన్న] LT', lastWeek: '[గత] dddd, LT', sameElse: 'L' }, relativeTime: { future: '%s లో', past: '%s క్రితం', s: 'కొన్ని క్షణాలు', m: 'ఒక నిమిషం', mm: '%d నిమిషాలు', h: 'ఒక గంట', hh: '%d గంటలు', d: 'ఒక రోజు', dd: '%d రోజులు', M: 'ఒక నెల', MM: '%d నెలలు', y: 'ఒక సంవత్సరం', yy: '%d సంవత్సరాలు' }, ordinalParse: /\d{1,2}వ/, ordinal: '%dవ', meridiemParse: /రాత్రి|ఉదయం|మధ్యాహ్నం|సాయంత్రం/, meridiemHour: function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === 'రాత్రి') { return hour < 4 ? hour : hour + 12; } else if (meridiem === 'ఉదయం') { return hour; } else if (meridiem === 'మధ్యాహ్నం') { return hour >= 10 ? hour : hour + 12; } else if (meridiem === 'సాయంత్రం') { return hour + 12; } }, meridiem: function (hour, minute, isLower) { if (hour < 4) { return 'రాత్రి'; } else if (hour < 10) { return 'ఉదయం'; } else if (hour < 17) { return 'మధ్యాహ్నం'; } else if (hour < 20) { return 'సాయంత్రం'; } else { return 'రాత్రి'; } }, week: { dow: 0, // Sunday is the first day of the week. doy: 6 // The week that contains Jan 1st is the first week of the year. } }); var th = moment__default.defineLocale('th', { months: 'มกราคม_กุมภาพันธ์_มีนาคม_เมษายน_พฤษภาคม_มิถุนายน_กรกฎาคม_สิงหาคม_กันยายน_ตุลาคม_พฤศจิกายน_ธันวาคม'.split('_'), monthsShort: 'ม.ค._ก.พ._มี.ค._เม.ย._พ.ค._มิ.ย._ก.ค._ส.ค._ก.ย._ต.ค._พ.ย._ธ.ค.'.split('_'), monthsParseExact: true, weekdays: 'อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัสบดี_ศุกร์_เสาร์'.split('_'), weekdaysShort: 'อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัส_ศุกร์_เสาร์'.split('_'), // yes, three characters difference weekdaysMin: 'อา._จ._อ._พ._พฤ._ศ._ส.'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'H นาฬิกา m นาที', LTS: 'H นาฬิกา m นาที s วินาที', L: 'YYYY/MM/DD', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY เวลา H นาฬิกา m นาที', LLLL: 'วันddddที่ D MMMM YYYY เวลา H นาฬิกา m นาที' }, meridiemParse: /ก่อนเที่ยง|หลังเที่ยง/, isPM: function (input) { return input === 'หลังเที่ยง'; }, meridiem: function (hour, minute, isLower) { if (hour < 12) { return 'ก่อนเที่ยง'; } else { return 'หลังเที่ยง'; } }, calendar: { sameDay: '[วันนี้ เวลา] LT', nextDay: '[พรุ่งนี้ เวลา] LT', nextWeek: 'dddd[หน้า เวลา] LT', lastDay: '[เมื่อวานนี้ เวลา] LT', lastWeek: '[วัน]dddd[ที่แล้ว เวลา] LT', sameElse: 'L' }, relativeTime: { future: 'อีก %s', past: '%sที่แล้ว', s: 'ไม่กี่วินาที', m: '1 นาที', mm: '%d นาที', h: '1 ชั่วโมง', hh: '%d ชั่วโมง', d: '1 วัน', dd: '%d วัน', M: '1 เดือน', MM: '%d เดือน', y: '1 ปี', yy: '%d ปี' } }); var tl_ph = moment__default.defineLocale('tl-ph', { months: 'Enero_Pebrero_Marso_Abril_Mayo_Hunyo_Hulyo_Agosto_Setyembre_Oktubre_Nobyembre_Disyembre'.split('_'), monthsShort: 'Ene_Peb_Mar_Abr_May_Hun_Hul_Ago_Set_Okt_Nob_Dis'.split('_'), weekdays: 'Linggo_Lunes_Martes_Miyerkules_Huwebes_Biyernes_Sabado'.split('_'), weekdaysShort: 'Lin_Lun_Mar_Miy_Huw_Biy_Sab'.split('_'), weekdaysMin: 'Li_Lu_Ma_Mi_Hu_Bi_Sab'.split('_'), longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'MM/D/YYYY', LL: 'MMMM D, YYYY', LLL: 'MMMM D, YYYY HH:mm', LLLL: 'dddd, MMMM DD, YYYY HH:mm' }, calendar: { sameDay: '[Ngayon sa] LT', nextDay: '[Bukas sa] LT', nextWeek: 'dddd [sa] LT', lastDay: '[Kahapon sa] LT', lastWeek: 'dddd [huling linggo] LT', sameElse: 'L' }, relativeTime: { future: 'sa loob ng %s', past: '%s ang nakalipas', s: 'ilang segundo', m: 'isang minuto', mm: '%d minuto', h: 'isang oras', hh: '%d oras', d: 'isang araw', dd: '%d araw', M: 'isang buwan', MM: '%d buwan', y: 'isang taon', yy: '%d taon' }, ordinalParse: /\d{1,2}/, ordinal: function (number) { return number; }, week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); var numbersNouns = 'pagh_wa’_cha’_wej_loS_vagh_jav_Soch_chorgh_Hut'.split('_'); function translateFuture(output) { var time = output; time = (output.indexOf('jaj') !== -1) ? time.slice(0, -3) + 'leS' : (output.indexOf('jar') !== -1) ? time.slice(0, -3) + 'waQ' : (output.indexOf('DIS') !== -1) ? time.slice(0, -3) + 'nem' : time + ' pIq'; return time; } function translatePast(output) { var time = output; time = (output.indexOf('jaj') !== -1) ? time.slice(0, -3) + 'Hu’' : (output.indexOf('jar') !== -1) ? time.slice(0, -3) + 'wen' : (output.indexOf('DIS') !== -1) ? time.slice(0, -3) + 'ben' : time + ' ret'; return time; } function tlh__translate(number, withoutSuffix, string, isFuture) { var numberNoun = numberAsNoun(number); switch (string) { case 'mm': return numberNoun + ' tup'; case 'hh': return numberNoun + ' rep'; case 'dd': return numberNoun + ' jaj'; case 'MM': return numberNoun + ' jar'; case 'yy': return numberNoun + ' DIS'; } } function numberAsNoun(number) { var hundred = Math.floor((number % 1000) / 100), ten = Math.floor((number % 100) / 10), one = number % 10, word = ''; if (hundred > 0) { word += numbersNouns[hundred] + 'vatlh'; } if (ten > 0) { word += ((word !== '') ? ' ' : '') + numbersNouns[ten] + 'maH'; } if (one > 0) { word += ((word !== '') ? ' ' : '') + numbersNouns[one]; } return (word === '') ? 'pagh' : word; } var tlh = moment__default.defineLocale('tlh', { months: 'tera’ jar wa’_tera’ jar cha’_tera’ jar wej_tera’ jar loS_tera’ jar vagh_tera’ jar jav_tera’ jar Soch_tera’ jar chorgh_tera’ jar Hut_tera’ jar wa’maH_tera’ jar wa’maH wa’_tera’ jar wa’maH cha’'.split('_'), monthsShort: 'jar wa’_jar cha’_jar wej_jar loS_jar vagh_jar jav_jar Soch_jar chorgh_jar Hut_jar wa’maH_jar wa’maH wa’_jar wa’maH cha’'.split('_'), monthsParseExact: true, weekdays: 'lojmItjaj_DaSjaj_povjaj_ghItlhjaj_loghjaj_buqjaj_ghInjaj'.split('_'), weekdaysShort: 'lojmItjaj_DaSjaj_povjaj_ghItlhjaj_loghjaj_buqjaj_ghInjaj'.split('_'), weekdaysMin: 'lojmItjaj_DaSjaj_povjaj_ghItlhjaj_loghjaj_buqjaj_ghInjaj'.split('_'), longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD.MM.YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'dddd, D MMMM YYYY HH:mm' }, calendar: { sameDay: '[DaHjaj] LT', nextDay: '[wa’leS] LT', nextWeek: 'LLL', lastDay: '[wa’Hu’] LT', lastWeek: 'LLL', sameElse: 'L' }, relativeTime: { future: translateFuture, past: translatePast, s: 'puS lup', m: 'wa’ tup', mm: tlh__translate, h: 'wa’ rep', hh: tlh__translate, d: 'wa’ jaj', dd: tlh__translate, M: 'wa’ jar', MM: tlh__translate, y: 'wa’ DIS', yy: tlh__translate }, ordinalParse: /\d{1,2}\./, ordinal: '%d.', week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); var tr__suffixes = { 1: '\'inci', 5: '\'inci', 8: '\'inci', 70: '\'inci', 80: '\'inci', 2: '\'nci', 7: '\'nci', 20: '\'nci', 50: '\'nci', 3: '\'üncü', 4: '\'üncü', 100: '\'üncü', 6: '\'ncı', 9: '\'uncu', 10: '\'uncu', 30: '\'uncu', 60: '\'ıncı', 90: '\'ıncı' }; var tr = moment__default.defineLocale('tr', { months: 'Ocak_Şubat_Mart_Nisan_Mayıs_Haziran_Temmuz_Ağustos_Eylül_Ekim_Kasım_Aralık'.split('_'), monthsShort: 'Oca_Şub_Mar_Nis_May_Haz_Tem_Ağu_Eyl_Eki_Kas_Ara'.split('_'), weekdays: 'Pazar_Pazartesi_Salı_Çarşamba_Perşembe_Cuma_Cumartesi'.split('_'), weekdaysShort: 'Paz_Pts_Sal_Çar_Per_Cum_Cts'.split('_'), weekdaysMin: 'Pz_Pt_Sa_Ça_Pe_Cu_Ct'.split('_'), longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD.MM.YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'dddd, D MMMM YYYY HH:mm' }, calendar: { sameDay: '[bugün saat] LT', nextDay: '[yarın saat] LT', nextWeek: '[haftaya] dddd [saat] LT', lastDay: '[dün] LT', lastWeek: '[geçen hafta] dddd [saat] LT', sameElse: 'L' }, relativeTime: { future: '%s sonra', past: '%s önce', s: 'birkaç saniye', m: 'bir dakika', mm: '%d dakika', h: 'bir saat', hh: '%d saat', d: 'bir gün', dd: '%d gün', M: 'bir ay', MM: '%d ay', y: 'bir yıl', yy: '%d yıl' }, ordinalParse: /\d{1,2}'(inci|nci|üncü|ncı|uncu|ıncı)/, ordinal: function (number) { if (number === 0) { // special case for zero return number + '\'ıncı'; } var a = number % 10, b = number % 100 - a, c = number >= 100 ? 100 : null; return number + (tr__suffixes[a] || tr__suffixes[b] || tr__suffixes[c]); }, week: { dow: 1, // Monday is the first day of the week. doy: 7 // The week that contains Jan 1st is the first week of the year. } }); // After the year there should be a slash and the amount of years since December 26, 1979 in Roman numerals. // This is currently too difficult (maybe even impossible) to add. var tzl = moment__default.defineLocale('tzl', { months: 'Januar_Fevraglh_Març_Avrïu_Mai_Gün_Julia_Guscht_Setemvar_Listopäts_Noemvar_Zecemvar'.split('_'), monthsShort: 'Jan_Fev_Mar_Avr_Mai_Gün_Jul_Gus_Set_Lis_Noe_Zec'.split('_'), weekdays: 'Súladi_Lúneçi_Maitzi_Márcuri_Xhúadi_Viénerçi_Sáturi'.split('_'), weekdaysShort: 'Súl_Lún_Mai_Már_Xhú_Vié_Sát'.split('_'), weekdaysMin: 'Sú_Lú_Ma_Má_Xh_Vi_Sá'.split('_'), longDateFormat: { LT: 'HH.mm', LTS: 'HH.mm.ss', L: 'DD.MM.YYYY', LL: 'D. MMMM [dallas] YYYY', LLL: 'D. MMMM [dallas] YYYY HH.mm', LLLL: 'dddd, [li] D. MMMM [dallas] YYYY HH.mm' }, meridiemParse: /d\'o|d\'a/i, isPM: function (input) { return 'd\'o' === input.toLowerCase(); }, meridiem: function (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'd\'o' : 'D\'O'; } else { return isLower ? 'd\'a' : 'D\'A'; } }, calendar: { sameDay: '[oxhi à] LT', nextDay: '[demà à] LT', nextWeek: 'dddd [à] LT', lastDay: '[ieiri à] LT', lastWeek: '[sür el] dddd [lasteu à] LT', sameElse: 'L' }, relativeTime: { future: 'osprei %s', past: 'ja%s', s: tzl__processRelativeTime, m: tzl__processRelativeTime, mm: tzl__processRelativeTime, h: tzl__processRelativeTime, hh: tzl__processRelativeTime, d: tzl__processRelativeTime, dd: tzl__processRelativeTime, M: tzl__processRelativeTime, MM: tzl__processRelativeTime, y: tzl__processRelativeTime, yy: tzl__processRelativeTime }, ordinalParse: /\d{1,2}\./, ordinal: '%d.', week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); function tzl__processRelativeTime(number, withoutSuffix, key, isFuture) { var format = { 's': ['viensas secunds', '\'iensas secunds'], 'm': ['\'n míut', '\'iens míut'], 'mm': [number + ' míuts', '' + number + ' míuts'], 'h': ['\'n þora', '\'iensa þora'], 'hh': [number + ' þoras', '' + number + ' þoras'], 'd': ['\'n ziua', '\'iensa ziua'], 'dd': [number + ' ziuas', '' + number + ' ziuas'], 'M': ['\'n mes', '\'iens mes'], 'MM': [number + ' mesen', '' + number + ' mesen'], 'y': ['\'n ar', '\'iens ar'], 'yy': [number + ' ars', '' + number + ' ars'] }; return isFuture ? format[key][0] : (withoutSuffix ? format[key][0] : format[key][1]); } var tzm_latn = moment__default.defineLocale('tzm-latn', { months: 'innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_ɣwšt_šwtanbir_ktˤwbrˤ_nwwanbir_dwjnbir'.split('_'), monthsShort: 'innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_ɣwšt_šwtanbir_ktˤwbrˤ_nwwanbir_dwjnbir'.split('_'), weekdays: 'asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas'.split('_'), weekdaysShort: 'asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas'.split('_'), weekdaysMin: 'asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas'.split('_'), longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'dddd D MMMM YYYY HH:mm' }, calendar: { sameDay: '[asdkh g] LT', nextDay: '[aska g] LT', nextWeek: 'dddd [g] LT', lastDay: '[assant g] LT', lastWeek: 'dddd [g] LT', sameElse: 'L' }, relativeTime: { future: 'dadkh s yan %s', past: 'yan %s', s: 'imik', m: 'minuḍ', mm: '%d minuḍ', h: 'saɛa', hh: '%d tassaɛin', d: 'ass', dd: '%d ossan', M: 'ayowr', MM: '%d iyyirn', y: 'asgas', yy: '%d isgasn' }, week: { dow: 6, // Saturday is the first day of the week. doy: 12 // The week that contains Jan 1st is the first week of the year. } }); var tzm = moment__default.defineLocale('tzm', { months: 'ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ'.split('_'), monthsShort: 'ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ'.split('_'), weekdays: 'ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ'.split('_'), weekdaysShort: 'ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ'.split('_'), weekdaysMin: 'ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ'.split('_'), longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'dddd D MMMM YYYY HH:mm' }, calendar: { sameDay: '[ⴰⵙⴷⵅ ⴴ] LT', nextDay: '[ⴰⵙⴽⴰ ⴴ] LT', nextWeek: 'dddd [ⴴ] LT', lastDay: '[ⴰⵚⴰⵏⵜ ⴴ] LT', lastWeek: 'dddd [ⴴ] LT', sameElse: 'L' }, relativeTime: { future: 'ⴷⴰⴷⵅ ⵙ ⵢⴰⵏ %s', past: 'ⵢⴰⵏ %s', s: 'ⵉⵎⵉⴽ', m: 'ⵎⵉⵏⵓⴺ', mm: '%d ⵎⵉⵏⵓⴺ', h: 'ⵙⴰⵄⴰ', hh: '%d ⵜⴰⵙⵙⴰⵄⵉⵏ', d: 'ⴰⵙⵙ', dd: '%d oⵙⵙⴰⵏ', M: 'ⴰⵢoⵓⵔ', MM: '%d ⵉⵢⵢⵉⵔⵏ', y: 'ⴰⵙⴳⴰⵙ', yy: '%d ⵉⵙⴳⴰⵙⵏ' }, week: { dow: 6, // Saturday is the first day of the week. doy: 12 // The week that contains Jan 1st is the first week of the year. } }); function uk__plural(word, num) { var forms = word.split('_'); return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]); } function uk__relativeTimeWithPlural(number, withoutSuffix, key) { var format = { 'mm': withoutSuffix ? 'хвилина_хвилини_хвилин' : 'хвилину_хвилини_хвилин', 'hh': withoutSuffix ? 'година_години_годин' : 'годину_години_годин', 'dd': 'день_дні_днів', 'MM': 'місяць_місяці_місяців', 'yy': 'рік_роки_років' }; if (key === 'm') { return withoutSuffix ? 'хвилина' : 'хвилину'; } else if (key === 'h') { return withoutSuffix ? 'година' : 'годину'; } else { return number + ' ' + uk__plural(format[key], +number); } } function weekdaysCaseReplace(m, format) { var weekdays = { 'nominative': 'неділя_понеділок_вівторок_середа_четвер_п’ятниця_субота'.split('_'), 'accusative': 'неділю_понеділок_вівторок_середу_четвер_п’ятницю_суботу'.split('_'), 'genitive': 'неділі_понеділка_вівторка_середи_четверга_п’ятниці_суботи'.split('_') }, nounCase = (/(\[[ВвУу]\]) ?dddd/).test(format) ? 'accusative' : ((/\[?(?:минулої|наступної)? ?\] ?dddd/).test(format) ? 'genitive' : 'nominative'); return weekdays[nounCase][m.day()]; } function processHoursFunction(str) { return function () { return str + 'о' + (this.hours() === 11 ? 'б' : '') + '] LT'; }; } var uk = moment__default.defineLocale('uk', { months: { 'format': 'січня_лютого_березня_квітня_травня_червня_липня_серпня_вересня_жовтня_листопада_грудня'.split('_'), 'standalone': 'січень_лютий_березень_квітень_травень_червень_липень_серпень_вересень_жовтень_листопад_грудень'.split('_') }, monthsShort: 'січ_лют_бер_квіт_трав_черв_лип_серп_вер_жовт_лист_груд'.split('_'), weekdays: weekdaysCaseReplace, weekdaysShort: 'нд_пн_вт_ср_чт_пт_сб'.split('_'), weekdaysMin: 'нд_пн_вт_ср_чт_пт_сб'.split('_'), longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD.MM.YYYY', LL: 'D MMMM YYYY р.', LLL: 'D MMMM YYYY р., HH:mm', LLLL: 'dddd, D MMMM YYYY р., HH:mm' }, calendar: { sameDay: processHoursFunction('[Сьогодні '), nextDay: processHoursFunction('[Завтра '), lastDay: processHoursFunction('[Вчора '), nextWeek: processHoursFunction('[У] dddd ['), lastWeek: function () { switch (this.day()) { case 0: case 3: case 5: case 6: return processHoursFunction('[Минулої] dddd [').call(this); case 1: case 2: case 4: return processHoursFunction('[Минулого] dddd [').call(this); } }, sameElse: 'L' }, relativeTime: { future: 'за %s', past: '%s тому', s: 'декілька секунд', m: uk__relativeTimeWithPlural, mm: uk__relativeTimeWithPlural, h: 'годину', hh: uk__relativeTimeWithPlural, d: 'день', dd: uk__relativeTimeWithPlural, M: 'місяць', MM: uk__relativeTimeWithPlural, y: 'рік', yy: uk__relativeTimeWithPlural }, // M. E.: those two are virtually unused but a user might want to implement them for his/her website for some reason meridiemParse: /ночі|ранку|дня|вечора/, isPM: function (input) { return /^(дня|вечора)$/.test(input); }, meridiem: function (hour, minute, isLower) { if (hour < 4) { return 'ночі'; } else if (hour < 12) { return 'ранку'; } else if (hour < 17) { return 'дня'; } else { return 'вечора'; } }, ordinalParse: /\d{1,2}-(й|го)/, ordinal: function (number, period) { switch (period) { case 'M': case 'd': case 'DDD': case 'w': case 'W': return number + '-й'; case 'D': return number + '-го'; default: return number; } }, week: { dow: 1, // Monday is the first day of the week. doy: 7 // The week that contains Jan 1st is the first week of the year. } }); var uz = moment__default.defineLocale('uz', { months: 'январ_феврал_март_апрел_май_июн_июл_август_сентябр_октябр_ноябр_декабр'.split('_'), monthsShort: 'янв_фев_мар_апр_май_июн_июл_авг_сен_окт_ноя_дек'.split('_'), weekdays: 'Якшанба_Душанба_Сешанба_Чоршанба_Пайшанба_Жума_Шанба'.split('_'), weekdaysShort: 'Якш_Душ_Сеш_Чор_Пай_Жум_Шан'.split('_'), weekdaysMin: 'Як_Ду_Се_Чо_Па_Жу_Ша'.split('_'), longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'D MMMM YYYY, dddd HH:mm' }, calendar: { sameDay: '[Бугун соат] LT [да]', nextDay: '[Эртага] LT [да]', nextWeek: 'dddd [куни соат] LT [да]', lastDay: '[Кеча соат] LT [да]', lastWeek: '[Утган] dddd [куни соат] LT [да]', sameElse: 'L' }, relativeTime: { future: 'Якин %s ичида', past: 'Бир неча %s олдин', s: 'фурсат', m: 'бир дакика', mm: '%d дакика', h: 'бир соат', hh: '%d соат', d: 'бир кун', dd: '%d кун', M: 'бир ой', MM: '%d ой', y: 'бир йил', yy: '%d йил' }, week: { dow: 1, // Monday is the first day of the week. doy: 7 // The week that contains Jan 4th is the first week of the year. } }); var vi = moment__default.defineLocale('vi', { months: 'tháng 1_tháng 2_tháng 3_tháng 4_tháng 5_tháng 6_tháng 7_tháng 8_tháng 9_tháng 10_tháng 11_tháng 12'.split('_'), monthsShort: 'Th01_Th02_Th03_Th04_Th05_Th06_Th07_Th08_Th09_Th10_Th11_Th12'.split('_'), monthsParseExact: true, weekdays: 'chủ nhật_thứ hai_thứ ba_thứ tư_thứ năm_thứ sáu_thứ bảy'.split('_'), weekdaysShort: 'CN_T2_T3_T4_T5_T6_T7'.split('_'), weekdaysMin: 'CN_T2_T3_T4_T5_T6_T7'.split('_'), weekdaysParseExact: true, meridiemParse: /sa|ch/i, isPM: function (input) { return /^ch$/i.test(input); }, meridiem: function (hours, minutes, isLower) { if (hours < 12) { return isLower ? 'sa' : 'SA'; } else { return isLower ? 'ch' : 'CH'; } }, longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD/MM/YYYY', LL: 'D MMMM [năm] YYYY', LLL: 'D MMMM [năm] YYYY HH:mm', LLLL: 'dddd, D MMMM [năm] YYYY HH:mm', l: 'DD/M/YYYY', ll: 'D MMM YYYY', lll: 'D MMM YYYY HH:mm', llll: 'ddd, D MMM YYYY HH:mm' }, calendar: { sameDay: '[Hôm nay lúc] LT', nextDay: '[Ngày mai lúc] LT', nextWeek: 'dddd [tuần tới lúc] LT', lastDay: '[Hôm qua lúc] LT', lastWeek: 'dddd [tuần rồi lúc] LT', sameElse: 'L' }, relativeTime: { future: '%s tới', past: '%s trước', s: 'vài giây', m: 'một phút', mm: '%d phút', h: 'một giờ', hh: '%d giờ', d: 'một ngày', dd: '%d ngày', M: 'một tháng', MM: '%d tháng', y: 'một năm', yy: '%d năm' }, ordinalParse: /\d{1,2}/, ordinal: function (number) { return number; }, week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); var x_pseudo = moment__default.defineLocale('x-pseudo', { months: 'J~áñúá~rý_F~ébrú~árý_~Márc~h_Áp~ríl_~Máý_~Júñé~_Júl~ý_Áú~gúst~_Sép~témb~ér_Ó~ctób~ér_Ñ~óvém~bér_~Décé~mbér'.split('_'), monthsShort: 'J~áñ_~Féb_~Már_~Ápr_~Máý_~Júñ_~Júl_~Áúg_~Sép_~Óct_~Ñóv_~Déc'.split('_'), monthsParseExact: true, weekdays: 'S~úñdá~ý_Mó~ñdáý~_Túé~sdáý~_Wéd~ñésd~áý_T~húrs~dáý_~Fríd~áý_S~átúr~dáý'.split('_'), weekdaysShort: 'S~úñ_~Móñ_~Túé_~Wéd_~Thú_~Frí_~Sát'.split('_'), weekdaysMin: 'S~ú_Mó~_Tú_~Wé_T~h_Fr~_Sá'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'HH:mm', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'dddd, D MMMM YYYY HH:mm' }, calendar: { sameDay: '[T~ódá~ý át] LT', nextDay: '[T~ómó~rró~w át] LT', nextWeek: 'dddd [át] LT', lastDay: '[Ý~ést~érdá~ý át] LT', lastWeek: '[L~ást] dddd [át] LT', sameElse: 'L' }, relativeTime: { future: 'í~ñ %s', past: '%s á~gó', s: 'á ~féw ~sécó~ñds', m: 'á ~míñ~úté', mm: '%d m~íñú~tés', h: 'á~ñ hó~úr', hh: '%d h~óúrs', d: 'á ~dáý', dd: '%d d~áýs', M: 'á ~móñ~th', MM: '%d m~óñt~hs', y: 'á ~ýéár', yy: '%d ý~éárs' }, ordinalParse: /\d{1,2}(th|st|nd|rd)/, ordinal: function (number) { var b = number % 10, output = (~~(number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; }, week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); var zh_cn = moment__default.defineLocale('zh-cn', { months: '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'), monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), weekdays: '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'), weekdaysShort: '周日_周一_周二_周三_周四_周五_周六'.split('_'), weekdaysMin: '日_一_二_三_四_五_六'.split('_'), longDateFormat: { LT: 'Ah点mm分', LTS: 'Ah点m分s秒', L: 'YYYY-MM-DD', LL: 'YYYY年MMMD日', LLL: 'YYYY年MMMD日Ah点mm分', LLLL: 'YYYY年MMMD日ddddAh点mm分', l: 'YYYY-MM-DD', ll: 'YYYY年MMMD日', lll: 'YYYY年MMMD日Ah点mm分', llll: 'YYYY年MMMD日ddddAh点mm分' }, meridiemParse: /凌晨|早上|上午|中午|下午|晚上/, meridiemHour: function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === '凌晨' || meridiem === '早上' || meridiem === '上午') { return hour; } else if (meridiem === '下午' || meridiem === '晚上') { return hour + 12; } else { // '中午' return hour >= 11 ? hour : hour + 12; } }, meridiem: function (hour, minute, isLower) { var hm = hour * 100 + minute; if (hm < 600) { return '凌晨'; } else if (hm < 900) { return '早上'; } else if (hm < 1130) { return '上午'; } else if (hm < 1230) { return '中午'; } else if (hm < 1800) { return '下午'; } else { return '晚上'; } }, calendar: { sameDay: function () { return this.minutes() === 0 ? '[今天]Ah[点整]' : '[今天]LT'; }, nextDay: function () { return this.minutes() === 0 ? '[明天]Ah[点整]' : '[明天]LT'; }, lastDay: function () { return this.minutes() === 0 ? '[昨天]Ah[点整]' : '[昨天]LT'; }, nextWeek: function () { var startOfWeek, prefix; startOfWeek = moment__default().startOf('week'); prefix = this.diff(startOfWeek, 'days') >= 7 ? '[下]' : '[本]'; return this.minutes() === 0 ? prefix + 'dddAh点整' : prefix + 'dddAh点mm'; }, lastWeek: function () { var startOfWeek, prefix; startOfWeek = moment__default().startOf('week'); prefix = this.unix() < startOfWeek.unix() ? '[上]' : '[本]'; return this.minutes() === 0 ? prefix + 'dddAh点整' : prefix + 'dddAh点mm'; }, sameElse: 'LL' }, ordinalParse: /\d{1,2}(日|月|周)/, ordinal: function (number, period) { switch (period) { case 'd': case 'D': case 'DDD': return number + '日'; case 'M': return number + '月'; case 'w': case 'W': return number + '周'; default: return number; } }, relativeTime: { future: '%s内', past: '%s前', s: '几秒', m: '1 分钟', mm: '%d 分钟', h: '1 小时', hh: '%d 小时', d: '1 天', dd: '%d 天', M: '1 个月', MM: '%d 个月', y: '1 年', yy: '%d 年' }, week: { // GB/T 7408-1994《数据元和交换格式·信息交换·日期和时间表示法》与ISO 8601:1988等效 dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); var zh_tw = moment__default.defineLocale('zh-tw', { months: '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'), monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), weekdays: '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'), weekdaysShort: '週日_週一_週二_週三_週四_週五_週六'.split('_'), weekdaysMin: '日_一_二_三_四_五_六'.split('_'), longDateFormat: { LT: 'Ah點mm分', LTS: 'Ah點m分s秒', L: 'YYYY年MMMD日', LL: 'YYYY年MMMD日', LLL: 'YYYY年MMMD日Ah點mm分', LLLL: 'YYYY年MMMD日ddddAh點mm分', l: 'YYYY年MMMD日', ll: 'YYYY年MMMD日', lll: 'YYYY年MMMD日Ah點mm分', llll: 'YYYY年MMMD日ddddAh點mm分' }, meridiemParse: /凌晨|早上|上午|中午|下午|晚上/, meridiemHour: function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === '凌晨' || meridiem === '早上' || meridiem === '上午') { return hour; } else if (meridiem === '中午') { return hour >= 11 ? hour : hour + 12; } else if (meridiem === '下午' || meridiem === '晚上') { return hour + 12; } }, meridiem: function (hour, minute, isLower) { var hm = hour * 100 + minute; if (hm < 600) { return '凌晨'; } else if (hm < 900) { return '早上'; } else if (hm < 1130) { return '上午'; } else if (hm < 1230) { return '中午'; } else if (hm < 1800) { return '下午'; } else { return '晚上'; } }, calendar: { sameDay: '[今天]LT', nextDay: '[明天]LT', nextWeek: '[下]ddddLT', lastDay: '[昨天]LT', lastWeek: '[上]ddddLT', sameElse: 'L' }, ordinalParse: /\d{1,2}(日|月|週)/, ordinal: function (number, period) { switch (period) { case 'd': case 'D': case 'DDD': return number + '日'; case 'M': return number + '月'; case 'w': case 'W': return number + '週'; default: return number; } }, relativeTime: { future: '%s內', past: '%s前', s: '幾秒', m: '1 分鐘', mm: '%d 分鐘', h: '1 小時', hh: '%d 小時', d: '1 天', dd: '%d 天', M: '1 個月', MM: '%d 個月', y: '1 年', yy: '%d 年' } }); var moment_with_locales = moment__default; moment_with_locales.locale('en'); return moment_with_locales; }));
'use strict'; const OBJFile = require('../src/OBJFile'); describe('OBJ File Parser', () => { describe('Object Name', () => { it('assigns objects the default name "untitled" if no object name was declared', () => { const fileContents = "v 1.0 2.0 3.0"; const modelName = new OBJFile(fileContents).parse().models[0].name; expect(modelName).toBe('untitled'); }); it('assigns objects the name specified by the o statement', () => { const fileContents = "o cube"; const modelName = new OBJFile(fileContents).parse().models[0].name; expect(modelName).toBe('cube'); }); }); describe('Comments', () => { it('ignores the remainders of a line after #', () => { const fileContents = "o cube#This is an inline comment"; const modelName = new OBJFile(fileContents).parse().models[0].name; expect(modelName).toBe('cube'); }); it('ignores lines containing just a comment', () => { const fileContents = "v 1.0 2.0 3.0\n# LINE COMMENT\nv 4.0 5.5 6.0"; const model = new OBJFile(fileContents).parse().models[0]; expect(model.vertices.length).toBe(2); }); }); describe('Blank lines', () => { it('ignores blank lines', () => { const fileContents = "v 1.0 2.0 3.0\n \nv 4.0 5.5 6.0"; const model = new OBJFile(fileContents).parse().models[0]; expect(model.vertices.length).toBe(2); }); }); describe('Vertex Definition', () => { it('v statements define a vertex', () => { const fileContents = "v 1.0 2.0 3.0\nv 4.0 5.5 6.0" const model = new OBJFile(fileContents).parse().models[0]; expect(model.vertices.length).toBe(2); expect(model.vertices[0]).toEqual({x: 1.0, y: 2.0, z: 3.0 }); expect(model.vertices[1]).toEqual({x: 4.0, y: 5.5, z: 6.0 }); }); }); describe('Texture Coord Definition', () => { it('vt statements define a texture coords', () => { const fileContents = "vt 1.0 2.0 3.0\nvt 4.0 5.5 6.0"; const model = new OBJFile(fileContents).parse().models[0]; expect(model.textureCoords.length).toBe(2); expect(model.textureCoords[0]).toEqual({u: 1.0, v: 2.0, w: 3.0 }); expect(model.textureCoords[1]).toEqual({u: 4.0, v: 5.5, w: 6.0 }); }); }); describe('Vertex Normal Definition', () => { it('vn statements define vertex normals', () => { const fileContents = "vn 1.0 2.0 3.0\nvn 4.0 5.5 6.0"; const model = new OBJFile(fileContents).parse().models[0]; expect(model.vertexNormals.length).toBe(2); expect(model.vertexNormals[0]).toEqual({x: 1.0, y: 2.0, z: 3.0 }); expect(model.vertexNormals[1]).toEqual({x: 4.0, y: 5.5, z: 6.0 }); }); }); describe('Polygon Definition', () => { it('f statements throw an error if given less than 3 vertices', () => { const fileContents = "f 1 2"; expect(new OBJFile(fileContents).parse).toThrow(); }); it('f statements with single values define a face with the given vertex indices', () => { const fileContents = "f 1 2 3"; const model = new OBJFile(fileContents).parse().models[0]; expect(model.faces.length).toBe(1); expect(model.faces[0].vertices).toEqual([ { vertexIndex: 1, textureCoordsIndex: 0, vertexNormalIndex: 0 }, { vertexIndex: 2, textureCoordsIndex: 0, vertexNormalIndex: 0 }, { vertexIndex: 3, textureCoordsIndex: 0, vertexNormalIndex: 0 } ]); }); it('f statements with double values define a face with the given vertex indices / texture Coords', () => { const fileContents = "f 1/4 2/5 3/6"; const model = new OBJFile(fileContents).parse().models[0]; expect(model.faces.length).toBe(1); expect(model.faces[0].vertices).toEqual([ { vertexIndex: 1, textureCoordsIndex: 4, vertexNormalIndex: 0 }, { vertexIndex: 2, textureCoordsIndex: 5, vertexNormalIndex: 0 }, { vertexIndex: 3, textureCoordsIndex: 6, vertexNormalIndex: 0 } ]); }); it('f statements with triple values define a face with the given vertex indices / texture Coords / vertex normals', () => { const fileContents = "f 1/4/7 2/5/8 3/6/9"; const model = new OBJFile(fileContents).parse().models[0]; expect(model.faces.length).toBe(1); expect(model.faces[0].vertices).toEqual([ { vertexIndex: 1, textureCoordsIndex: 4, vertexNormalIndex: 7 }, { vertexIndex: 2, textureCoordsIndex: 5, vertexNormalIndex: 8 }, { vertexIndex: 3, textureCoordsIndex: 6, vertexNormalIndex: 9 } ]); }); it('f statements may omit texture coord indices', () => { const fileContents = "f 1//7 2//8 3//9"; const model = new OBJFile(fileContents).parse().models[0]; expect(model.faces.length).toBe(1); expect(model.faces[0].vertices).toEqual([ { vertexIndex: 1, textureCoordsIndex: 0, vertexNormalIndex: 7 }, { vertexIndex: 2, textureCoordsIndex: 0, vertexNormalIndex: 8 }, { vertexIndex: 3, textureCoordsIndex: 0, vertexNormalIndex: 9 } ]); }); }); describe('Materials', () => { it('returns a list of referenced material libraries', () => { var fileContents = "mtllib lib1\nmtllib lib2"; var materialLibs = new OBJFile(fileContents).parse().materialLibraries; expect(materialLibs).toEqual(['lib1', 'lib2']); }); }); describe('Groups', () => { it('assigns each face to a group called "" by default', () => { const fileContents = "f 1 2 3"; const model = new OBJFile(fileContents).parse().models[0]; expect(model.faces[0].group).toBe(''); }); it('assigns each face to the group indicated by the preceding g statement', () => { const fileContents = "g group1\nf 1 2 3"; const model = new OBJFile(fileContents).parse().models[0]; expect(model.faces[0].group).toBe('group1'); }); it('resets the current group to "" when starting a new object', () => { const fileContents = "g group1\nf 1 2 3\no newObj\nf 1 2 3"; const model = new OBJFile(fileContents).parse().models[1]; expect(model.faces[0].group).toBe(''); }); }); describe('Smoothing Groups', () => { it('assigns each face to a smoothing group 0 (no smoothing) by default', () => { const fileContents = "f 1 2 3"; const model = new OBJFile(fileContents).parse().models[0]; expect(model.faces[0].smoothingGroup).toBe(0); }); it('assigns each face to the smoothing group indicated by the preceding s statement', () => { const fileContents = "s 123\nf 1 2 3"; const model = new OBJFile(fileContents).parse().models[0]; expect(model.faces[0].smoothingGroup).toBe(123); }); it('resets the current smoothing group to 0 when starting a new object', () => { const fileContents = "s 2\nf 1 2 3\no newObj\nf 1 2 3"; const model = new OBJFile(fileContents).parse().models[1]; expect(model.faces[0].smoothingGroup).toBe(0); }); it('resets the current smoothing group to 0 after an "s off" statement', () => { const fileContents = "s 2\nf 1 2 3\ns off\nf 1 2 3"; const model = new OBJFile(fileContents).parse().models[0]; expect(model.faces[1].smoothingGroup).toBe(0); }); }); });
'use strict'; var Dispatcher = require('flux').Dispatcher, assign = require('object-assign'), AppDispatcher; AppDispatcher = assign(new Dispatcher(), { /** * A bridge function between the views and the dispatcher, marking the action * as a view action. * @param {object} action The data coming from the view. */ handleViewAction: function(action) { this.dispatch({ source: 'VIEW_ACTION', action: action }); }, /** * A bridge function between the server and the dispatcher, marking the action * as a server action. * @param {object} action The data coming from the server. */ handleServerAction: function(action) { this.dispatch({ source: 'SERVER_ACTION', action: action }); } }); module.exports = AppDispatcher;
import Page from '../classes/Page'; export default (req, res) => { const { session = {} } = req; const templatePath = '/templates/404.twig'; const pageDetails = { templatePath, templateVariables: { errors: session.errors, }, }; if (session.errors) { delete session.errors; } const page = new Page(pageDetails); res.send(page.render()); };
define(['backbone', './SkiAreaModel.js'], function(Backbone, SkiArea) { return Backbone.Collection.extend({ model: SkiArea, url: '/ski-areas/myList', getById: function (id) { return this.filter(function (area) { return area.get("id") == id; })[0]; } }); });
/* Copyright (c) 2015, Yahoo! Inc. All rights reserved. Code licensed under the MIT License. See LICENSE.txt file. */ var express = require('express'); var st = require('st'); var lru = require('lru-cache'); var fs = require('fs'); var url = require('url'); var mdns = require('mdns'); var path = require('path'); var spawn = require('child_process').spawn; var logger = require('davlog'); logger.init({name: 'reginabox'}); var app = express(); var cache = lru(); var port; var outputDir = process.argv[3] || path.join(process.cwd(), 'registry'); logger.info('using output directory', outputDir); // log each request, set server header app.use(function(req, res, cb){ logger.info(req.ip, req.method, req.path); res.append('Server', 'reginabox'); cb(); }); // serve up main index (no caching) app.get('/', function(req, res){ res.type('json'); fs.createReadStream(path.join(outputDir, 'index.json')).pipe(res); }); // serve up tarballs app.use(st({path: outputDir, passthrough: true, index: false})); // serve up metadata. doing it manually so we can modify JSON app.use(function(req, res){ var cached = cache.get(req.url); if (cached) { res.type('json') res.send(cached); return; } fs.readFile(path.join(outputDir, req.url, 'index.json'), {encoding: 'utf8'}, function(err, data){ if (err) { res.sendStatus(err.code === 'ENOENT' ? 404 : 500); return; } data = JSON.parse(data); if (data && data.versions && typeof data.versions === 'object') { Object.keys(data.versions).forEach(function(versionNum){ var version = data.versions[versionNum]; if (version.dist && version.dist.tarball && typeof version.dist.tarball === 'string') { var parts = url.parse(version.dist.tarball); version.dist.tarball = 'http://'+req.hostname+':'+port+parts.path; } }); } var buf = new Buffer(JSON.stringify(data)); cache.set(req.url, buf); res.type('json'); res.send(buf); }); }); var server = app.listen(function(){ port = exports.port = server.address().port; logger.info('listening on port', port); mdns.createAdvertisement(mdns.tcp('reginabox'), port).start(); logger.info('broadcasting on mDNS'); var child = spawn( path.resolve(require.resolve('registry-static'), '../../bin/registry-static'), ['-o', outputDir, '-d', 'localhost'], {stdio: 'inherit'} ); process.on('SIGINT', function(){ child.kill('SIGINT'); process.kill(); }); logger.info('starting registry-static'); }); exports.close = function(){ server.close(); };
Namespace.register("comp"); comp.Base=function(){ } comp.Listview=function(searchstr){ this.$elem=$(searchstr); this.searchstr=searchstr; } comp.Listview.prototype.render=function(entities,listItemHandler){ listItemHandler=listItemHandler || function(entity,$li){ $li.html(entity); } this.$elem.html(""); for(var i in entities) { var entity=entities[i]; $li=$("<li>"); listItemHandler(entity,$li); $li.appendTo(this.$elem); } this.$elem.listview("refresh"); } comp.Listview.prototype.addListItem=function(listItemHandler){ if(!listItemHandler) return; $li=$("<li>") listItemHandler($li); $li.appendTo(this.$elem); this.$elem.listview("refresh"); } comp.SelectMenu=function(searchstr) { this.$elem=$(searchstr); this.searchstr=searchstr; } comp.SelectMenu.prototype.load=function(entities,optionItemHandler) { this.reset(false); if(this.$elem.attr("multiple")!="multiple"){ var $option=$("<option>Select</option>"); $option.appendTo(this.$elem); } for(var i in entities) { var entity=entities[i]; var $option=$("<option>"); optionItemHandler(entity,$option); $option.appendTo(this.$elem); } this.$elem.selectmenu("refresh"); } comp.SelectMenu.prototype.simpleLoad=function(entities,valueTextHandler) { this.load(entities,function(entity,$option){ var pair=valueTextHandler(entity); $option.val(pair[0]); $option.text(pair[1]); }); } comp.SelectMenu.prototype.reset=function(refreshFlag) { refreshFlag=refreshFlag || true; this.$elem.empty(); if(refreshFlag){ this.$elem.selectmenu("refresh"); } } comp.SelectMenu.prototype.replaceSelectionWithText=function(trigger) { if(isNull(trigger)) { trigger=true; } var $select=this.$elem; var $ui_select=$select.parents("div.ui-select:first"); //reset the display $ui_select.show(); $ui_select.parent().find("div.selectionResult").remove(); //hide the selecor if($select.children().length==2) //only one option { $select.get(0).selectedIndex=1; $select.selectmenu("refresh"); if(trigger){ $select.trigger('change'); } $ui_select.hide(); $ui_select.parent().append('<div class="selectionResult">' +$select.children("option:selected").text()+ '</div>'); } } comp.SelectMenu.prototype.hasOneOption=function() { var $select=this.$elem; return $select.children().length<=2; } comp.SelectMenu.prototype.hasValue=function(){ var $select=this.$elem; return ($select.val()!="" && $select.val()!="Select") } comp.SelectMenu.prototype.autoSelect=function(value) { var $select=this.$elem; var val; if("function"==typeof value) { val=value($select); }else { val=value; } $select.val(val); $select.selectmenu("refresh"); $select.trigger('change'); } comp.InputField=function(searchstr) { this.$elem=$(searchstr); this.searchstr=searchstr; } comp.InputField.prototype.create=function(id,fieldName,format,value,extData) { var $input=UIExtends.createInputField(id,fieldName+":",format,value,extData); this.$elem=$input; } comp.InputField.prototype.appendTo=function(parent) { this.$elem.appendTo(parent); }
import React, { PureComponent } from 'react'; export default class NotFound extends PureComponent { render() { return <div>NotFound</div>; } }
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.2.3.6-2-16 description: > Object.defineProperty - argument 'P' is a number that converts to a string (value is 1(following 22 zeros)) includes: [runTestCase.js] ---*/ function testcase() { var obj = {}; Object.defineProperty(obj, 10000000000000000000000, {}); return obj.hasOwnProperty("1e+22"); } runTestCase(testcase);
const _ = require('lodash') const inquirer = require('inquirer') const packageQuestions = require('./packageQuestions') module.exports = function (questions, done) { inquirer.prompt(_.map(packageQuestions, transform), (pkg) => inquirer.prompt(_.map(questions, transform), (answers) => done({'package': pkg, answers}) ) ) } function transform (details, question) { return { name: question, message: details.prompt, type: getType(details.input.type, _.has(details, 'input.enum')), choices: details.input.enum } } function getType (type, hasEnum) { if (type === Boolean) return 'confirm' if (type === Array || Array.isArray(type)) return 'checkbox' return hasEnum ? 'list' : 'input' }
import Microcosm from 'microcosm' const identity = n => n describe('Action complete state', function() { it('will not change states if already complete', function() { const repo = new Microcosm() const action = repo.append(identity) action.cancel() action.resolve() expect(action.is('cancelled')).toBe(true) expect(action.is('done')).toBe(false) }) })
// All code points in the Hangul Compatibility Jamo block as per Unicode v4.0.1: [ 0x3130, 0x3131, 0x3132, 0x3133, 0x3134, 0x3135, 0x3136, 0x3137, 0x3138, 0x3139, 0x313A, 0x313B, 0x313C, 0x313D, 0x313E, 0x313F, 0x3140, 0x3141, 0x3142, 0x3143, 0x3144, 0x3145, 0x3146, 0x3147, 0x3148, 0x3149, 0x314A, 0x314B, 0x314C, 0x314D, 0x314E, 0x314F, 0x3150, 0x3151, 0x3152, 0x3153, 0x3154, 0x3155, 0x3156, 0x3157, 0x3158, 0x3159, 0x315A, 0x315B, 0x315C, 0x315D, 0x315E, 0x315F, 0x3160, 0x3161, 0x3162, 0x3163, 0x3164, 0x3165, 0x3166, 0x3167, 0x3168, 0x3169, 0x316A, 0x316B, 0x316C, 0x316D, 0x316E, 0x316F, 0x3170, 0x3171, 0x3172, 0x3173, 0x3174, 0x3175, 0x3176, 0x3177, 0x3178, 0x3179, 0x317A, 0x317B, 0x317C, 0x317D, 0x317E, 0x317F, 0x3180, 0x3181, 0x3182, 0x3183, 0x3184, 0x3185, 0x3186, 0x3187, 0x3188, 0x3189, 0x318A, 0x318B, 0x318C, 0x318D, 0x318E, 0x318F ];
$( document ).ready(function() { /* Sidebar height set */ $('.sidebar').css('min-height',$(document).height()); /* Secondary contact links */ var scontacts = $('#contact-list-secondary'); var contact_list = $('#contact-list'); scontacts.hide(); contact_list.mouseenter(function(){ scontacts.fadeIn(); }); contact_list.mouseleave(function(){ scontacts.fadeOut(); }); }); /* particlesJS.load(@dom-id, @path-json, @callback (optional)); */ particlesJS.load('particles-js', '../../../../../../assets/js/particles.json', function() { console.log('callback - particles.js config loaded'); });
function mayThrow() { throw new Error('Whoops...') } function unsafe() { try { mayThrow(); } catch (e) { handleError(e); } }
var searchData= [ ['set',['set',['../classSparseMatrix.html#a5344d8d6543344f3aec055c373ac61de',1,'SparseMatrix']]], ['sparsematrix',['SparseMatrix',['../classSparseMatrix.html#a14f8df02d304c3e60a308b426e908613',1,'SparseMatrix::SparseMatrix(int n)'],['../classSparseMatrix.html#a9e50d719e7d7fc212cfdac41eea1a63b',1,'SparseMatrix::SparseMatrix(int rows, int columns)']]] ];
var expect = require('./lib/expect'); var rewire = require('rewire'); var sinon = require('sinon'); describe('rewrite-files module', function() { var globResults, readContents, fs, glob, rewriteFiles; function setup() { globResults = []; readContents = ""; rewriteFiles = rewire('../lib/rewrite-files'); fs = { readFile: sinon.spy(function(fileName, callback) { callback(null, readContents); }), writeFile: sinon.spy(function(fileName, contents, callback) { callback(null); }) }; rewriteFiles.__set__('fs', fs); glob = { sync: sinon.spy(function(filenamePattern) { return globResults; }) }; rewriteFiles.__set__('glob', glob); } beforeEach(setup); describe('- withFiles function', function() { describe('when files is not an array', function() { it('throws error', function() { var transform = sinon.spy(); var afterTransform = sinon.spy(); expect(function() { rewriteFiles('', transform, afterTransform); }).to.throw('expected array as first argument'); expect(transform).not.to.be.called; expect(afterTransform).not.to.be.called; }); }); describe('with empty array', function() { it('does no file processing', function(done) { var transform = sinon.spy(); rewriteFiles([], transform, function() { expect(transform).not.to.be.called; done(); }); }); }); describe('with array of one or more files', function() { it('does file processing', function(done) { globResults = ['filename']; readContents = 'read file contents'; var writeContents = 'write file contents'; var pattern = 'nope'; var transform = sinon.spy(function(fileName, contents, callback) { callback(null, writeContents); }); rewriteFiles(globResults, transform, function() { expect(glob.sync).not.to.be.called; expect(transform).to.be.calledOnce; expect(transform.args[0][0]).to.eq(globResults[0]); expect(transform.args[0][1]).to.eq(readContents); expect(fs.writeFile).to.be.calledOnce; expect(fs.writeFile.args[0][0]).to.eq(globResults[0]); expect(fs.writeFile.args[0][1]).to.eq(writeContents); done(); }); }); }); }); describe('- withPattern function', function() { describe('when pattern is not a string', function() { it('throws error', function() { var transform = sinon.spy(); var afterTransform = sinon.spy(); expect(function() { rewriteFiles.withPattern([], transform, afterTransform); }).to.throw('expected string as first argument'); }); }); describe('when pattern matches no files', function() { it('does no file processing', function(done) { var transform = sinon.spy(); var pattern = 'nope'; rewriteFiles.withPattern(pattern, transform, function() { expect(glob.sync).to.be.calledWith(pattern); expect(transform).not.to.be.called; done(); }); }); }); describe('when pattern matches one or more files', function() { it('does file processing', function(done) { globResults = ['filename']; readContents = 'read file contents'; var writeContents = 'write file contents'; var pattern = 'nope'; var transform = sinon.spy(function(fileName, contents, callback) { callback(null, writeContents); }); rewriteFiles.withPattern(pattern, transform, function() { expect(glob.sync).to.be.calledWith(pattern); expect(transform).to.be.calledOnce; expect(transform.args[0][0]).to.eq(globResults[0]); expect(transform.args[0][1]).to.eq(readContents); expect(fs.writeFile).to.be.calledOnce; expect(fs.writeFile.args[0][0]).to.eq(globResults[0]); expect(fs.writeFile.args[0][1]).to.eq(writeContents); done(); }); }); }); }); });
import THREE from 'three'; import Mesh from './Mesh'; import Iso from './Iso'; export default class Scene { threeScene = new THREE.Scene(); camera = null; constructor(container:HTMLElement) { // Fog this.threeScene.fog = new THREE.FogExp2(0x000000, 5); // Ambient light this.ambientLight = new THREE.AmbientLight(0x404040, 2); this.threeScene.add(this.ambientLight); // Directional light var light = new THREE.DirectionalLight(0xffffff, 1); light.position.set(-30, 40, 20); light.castShadow = true; light.shadow.mapSize = new THREE.Vector2(50, 50); var size = 50; light.shadow.camera.left = -size; light.shadow.camera.right = size; light.shadow.camera.top = -size; light.shadow.camera.bottom = size; light.shadow.camera.near = 10; light.shadow.camera.far = 100; this.threeScene.add(light); // light helper if (Iso.DEBUG) { this.threeScene.add(new THREE.DirectionalLightHelper(light, 0)); this.threeScene.add(new THREE.CameraHelper(light.shadow.camera)); } // axes if (Iso.DEBUG) { this.threeScene.add(new THREE.AxisHelper(40)); } // grid if (Iso.DEBUG) { let geometry = new THREE.PlaneBufferGeometry(100, 100, 10, 10); let material = new THREE.MeshBasicMaterial({ wireframe: true, opacity: 0.5, transparent: true, }); let grid = new THREE.Mesh(geometry, material); grid.rotation.order = 'YXZ'; grid.rotation.y = -Math.PI / 2; grid.rotation.x = -Math.PI / 2; this.threeScene.add(grid); } this.setupCamera(container); } /** * Adds a mesh to the scene * @param {Mesh} mesh * @returns {Scene} */ add(mesh:Mesh):Scene { this.threeScene.add(mesh.threeMesh); return this; } /** * Remove a mesh from the scene * @param {Mesh} mesh * @returns {Scene} */ remove(mesh:Mesh):Scene { this.threeScene.remove(mesh.threeMesh); return this; } /** * Sets the scene's ambient light color * @param color Light's color * @param intensity (optional) Light's intensity * @returns {Scene} */ setAmbientLight(color:Iso.Color, intensity:?number):Scene { this.ambientLight.color = color; if (intensity !== undefined) { this.ambientLight.intensity = intensity; } return this; } setupCamera(container:HTMLElement) { // Setup camera this.camera = new Iso.Camera({ x: 10, z: 10, zoom: 3, }, container); return this; } /** * World resize callback. * @returns {Scene} */ resize():Scene { this.camera.resize(); return this; } clear():Scene { let meshes = this.threeScene.children.filter(c => c instanceof THREE.Mesh); for (let child of meshes) { this.threeScene.remove(child); } return this; } }
'use strict' module.exports = { get today() { return Date.now() }, get todayReadable() { let tstamp = new Date() return tstamp.toDateString() }, now: { seperator: '-', get get() { let o = new Date() let minutes = function() { if (o.getMinutes() < 10) return '0' + o.getMinutes() else return o.getMinutes() }() let month = function() { if (o.getMonth() < 10) return '0' + o.getMonth() else return o.getMonth() }() let dateArr = [ o.getDate(), month, o.getFullYear() ] let timeArr = [ o.getHours(), minutes, o.getSeconds() ] return dateArr.join('.') + this.seperator + timeArr.join(':') }, parseJSON: function(json, callback) { let parsed try { parsed = JSON.parse(json) } catch (err) { callback(err, null) } if (parsed) callback(null, parsed) }, } }
//YouTube iframe player API docs https://developers.google.com/youtube/iframe_api_reference define( ['jquery'], function ( $ ) { 'use strict'; return { loadAPI: function () { // This code loads the IFrame Player API code asynchronously. var tag = document.createElement( 'script' ); tag.src = "http://www.youtube.com/player_api"; var firstScriptTag = document.getElementsByTagName( 'script' )[0]; firstScriptTag.parentNode.insertBefore( tag, firstScriptTag ); }, setPlayerToLoad: function ( $target ) { $target.addClass( 'js-youtube-player-load' ); }, unsetPlayerToLoad: function ( $target ) { $target.removeClass( 'js-youtube-player-load' ); }, loadVideo: function () { var player; var $player = $('.js-youtube-player-load'); var playerId = $player.attr( 'id' ); var videoId = $player.attr( 'data-videoid' ); var width = $player.width(); var height = $player.height(); var playOnLoad = $player.attr( 'data-play-on-load' ) === 'true' ? 1 : 0; player = new YT.Player( playerId, { height: height, width: width, videoId: videoId, events: { "onReady": this.readyToPlay }, playerVars: { autoplay: playOnLoad, rel: 0 } } ); $( '.js-youtube-player-load' ).data( 'player', player ); this.unsetPlayerToLoad( $( '.js-youtube-player-load' ) ); }, readyToPlay: function ( event ) { }, stopVideo: function ( player ) { player.stopVideo(); } }; } );
__lavaBuildMap = null; __geocode_jsonp0 = null; __geocode_jsonp1 = null; __geocode_jsonp2 = null; __geocode_jsonp3 = null; __geocode_jsonp4 = null; __geocode_jsonp5 = null; __geocode_jsonp6 = null;
'use strict'; var mountFolder = function (connect, dir) { return connect.static(require('path').resolve(dir)); }; var webpackDistConfig = require('./webpack.dist.config.js'), webpackDevConfig = require('./webpack.config.js'); module.exports = function (grunt) { // Let *load-grunt-tasks* require everything require('load-grunt-tasks')(grunt); // Read configuration from package.json var pkgConfig = grunt.file.readJSON('package.json'); grunt.initConfig({ pkg: pkgConfig, webpack: { options: webpackDistConfig, dist: { cache: false } }, 'webpack-dev-server': { options: { port: 8000, webpack: webpackDevConfig, publicPath: '/scripts/', contentBase: './<%= pkg.src %>/', }, start: { keepAlive: true, } }, connect: { options: { port: 8000 }, dist: { options: { keepalive: true, middleware: function (connect) { return [ mountFolder(connect, pkgConfig.dist) ]; } } } }, open: { options: { delay: 500 }, dev: { path: 'http://localhost:<%= connect.options.port %>/webpack-dev-server/' }, dist: { path: 'http://localhost:<%= connect.options.port %>/' } }, karma: { unit: { configFile: 'karma.conf.js' } }, copy: { dist: { files: [ // includes files within path { flatten: true, expand: true, src: ['<%= pkg.src %>/*'], dest: '<%= pkg.dist %>/', filter: 'isFile' }, { flatten: true, expand: true, src: ['<%= pkg.src %>/images/*'], dest: '<%= pkg.dist %>/images/' }, ] } }, clean: { dist: { files: [{ dot: true, src: [ '<%= pkg.dist %>' ] }] } } }); grunt.registerTask('serve', function (target) { if (target === 'dist') { return grunt.task.run(['build', 'open:dist', 'connect:dist']); } grunt.task.run([ 'open:dev', 'webpack-dev-server' ]); }); grunt.registerTask('test', ['karma']); grunt.registerTask('build', ['clean', 'copy', 'webpack']); grunt.registerTask('default', []); };
var nparse = function(string){ var q = string[string.length-1]; var regex = /[^0-9]/g; if(q.match(regex)){ return string.slice(0,string.length-1); } else{ return string; } }; if(typeof module !== 'undefined' && typeof require !== 'undefined'){ module.exports = nparse; }
// Copyright (c) 2015-2018 Robert Rypuła - https://audio-network.rypula.pl (function () { 'use strict'; AudioNetwork.Injector .registerService('Audio.ActiveAudioContext', _ActiveAudioContext); _ActiveAudioContext.$inject = [ 'Audio.SimpleAudioContextBuilder' ]; function _ActiveAudioContext( SimpleAudioContextBuilder ) { var simpleAudioContext = null; function $$init() { simpleAudioContext = SimpleAudioContextBuilder.build(); } function initializeCheck() { if (simpleAudioContext === null) { $$init(); } } function loadRecordedAudio(url) { initializeCheck(); return simpleAudioContext.loadRecordedAudio(url); } function getMicrophoneNode() { initializeCheck(); return simpleAudioContext.getMicrophoneNode(); } function getRecordedAudioNode() { initializeCheck(); return simpleAudioContext.getRecordedAudioNode(); } function getSampleRate() { initializeCheck(); return simpleAudioContext.getSampleRate(); } function getDestination() { initializeCheck(); return simpleAudioContext.getDestination(); } function getCurrentTime() { initializeCheck(); return simpleAudioContext.getCurrentTime(); } function createAnalyser() { initializeCheck(); return simpleAudioContext.createAnalyser(); } function createGain() { initializeCheck(); return simpleAudioContext.createGain(); } function createScriptProcessor() { initializeCheck(); return simpleAudioContext.createScriptProcessor(); } return { loadRecordedAudio: loadRecordedAudio, getMicrophoneNode: getMicrophoneNode, getRecordedAudioNode: getRecordedAudioNode, getSampleRate: getSampleRate, getDestination: getDestination, getCurrentTime: getCurrentTime, createAnalyser: createAnalyser, createGain: createGain, createScriptProcessor: createScriptProcessor }; } })();
import initShowEnvironment from '~/environments/mount_show'; document.addEventListener('DOMContentLoaded', () => initShowEnvironment());
import React from 'react'; import { Route, IndexRoute, Redirect } from 'react-router'; import App from './App'; import Index from './views/Index'; import Company from './views/Company'; import Return from './views/Return'; import Validation from './views/Validation'; // export const rootRoute = "/"; export const rootRoute = "/stock-prediction/"; // const gitHubRepoName = 'stock-prediction'; // // The domain for your site // // SET THIS: e.g. http://subdomain.example.tld, or http://www.example.tld // const domain = 'https://bofa.github.io'; // function redirectToDomain() { // window.location.replace(domain); // } // function parseRedirectQuery(query, replace) { // let redirectTo = {}; // if (typeof query.pathname === 'string' && query.pathname !== '') { // redirectTo.pathname = query.pathname; // } // if (typeof query.query === 'string' && query.query !== '') { // let queryObject = {}; // query.query.split('&').map(q => q.split('=')).forEach(arr => { // queryObject[arr[0]] = arr.slice(1).join('='); // }) // redirectTo.query = queryObject; // } // if (typeof query.hash === 'string' && query.hash !== '') { // redirectTo.hash = `#${query.hash}`; // } // replace(redirectTo); // } // function checkForRedirect(nextState, replace) { // const location = nextState.location; // if (location.query.redirect === 'true') { // parseRedirectQuery(location.query, replace); // } else if (location.pathname.split('/')[1] === gitHubRepoName) { // redirectToDomain(); // } // } export default ( <Route path={rootRoute} component={App} /*onEnter={checkForRedirect}*/> <IndexRoute component={Index} /> <Route path="company/:company" component={Company} /> <Route path="return" component={Return} /> <Route path="validation" component={Validation} /> <Redirect from="*" to={rootRoute} /> </Route> );
var crypto, qs, request; process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; request = require('request'); crypto = require('crypto'); qs = require('querystring'); function rest(key, secret, nonceGenerator) { this.url = "https://api.bitfinex.com"; this.version = 'v1'; this.key = key; this.secret = secret; this.nonce = new Date().getTime(); this._nonce = typeof nonceGenerator === "function" ? nonceGenerator : function () { //noinspection JSPotentiallyInvalidUsageOfThis return ++this.nonce; }; } rest.prototype.make_request = function (sub_path, params, cb) { var headers, key, nonce, path, payload, signature, url, value; if (!this.key || !this.secret) { return cb(new Error("missing api key or secret")); } path = '/' + this.version + '/' + sub_path; url = this.url + path; nonce = JSON.stringify(this._nonce()); payload = { request: path, nonce: nonce }; for (key in params) { value = params[key]; payload[key] = value; } payload = new Buffer(JSON.stringify(payload)).toString('base64'); signature = crypto.createHmac("sha384", this.secret).update(payload).digest('hex'); headers = { 'X-BFX-APIKEY': this.key, 'X-BFX-PAYLOAD': payload, 'X-BFX-SIGNATURE': signature }; return request({ url: url, method: "POST", headers: headers, timeout: 15000 }, function (err, response, body) { var error, error1, result; if (err || (response.statusCode !== 200 && response.statusCode !== 400)) { return cb(new Error(err != null ? err : response.statusCode)); } try { result = JSON.parse(body); } catch (error1) { error = error1; return cb(null, { message: body.toString() }); } if (result.message != null) { return cb(new Error(result.message)); } return cb(null, result); }); }; rest.prototype.make_public_request = function (path, cb) { var url; url = this.url + '/v1/' + path; return request({ url: url, method: "GET", timeout: 15000 }, function (err, response, body) { var error, error1, result; if (err || (response.statusCode !== 200 && response.statusCode !== 400)) { return cb(new Error(err != null ? err : response.statusCode)); } try { result = JSON.parse(body); } catch (error1) { error = error1; return cb(null, { message: body.toString() }); } if (result.message != null) { return cb(new Error(result.message)); } return cb(null, result); }); }; rest.prototype.ticker = function (symbol, cb) { if (arguments.length == 0){ symbol = "BTCUSD"; cb = function(error, data){console.log(data)} } return this.make_public_request('pubticker/' + symbol, cb); }; rest.prototype.today = function (symbol, cb) { return this.make_public_request('today/' + symbol, cb); }; rest.prototype.stats = function (symbol, cb) { return this.make_public_request('stats/' + symbol, cb); }; //rest.prototype.candles = function (symbol, cb) { // return this.make_public_request('candles/' + symbol, cb); //}; rest.prototype.fundingbook = function (currency, options, cb) { var err, error1, index, option, query_string, uri, value; index = 0; uri = 'lendbook/' + currency; if (typeof options === 'function') { cb = options; } else { try { for (option in options) { value = options[option]; if (index++ > 0) { query_string += '&' + option + '=' + value; } else { query_string = '/?' + option + '=' + value; } } if (index > 0) { uri += query_string; } } catch (error1) { err = error1; return cb(err); } } return this.make_public_request(uri, cb); }; rest.prototype.orderbook = function (symbol, options, cb) { var err, error1, index, option, query_string, uri, value; index = 0; uri = 'book/' + symbol; if (typeof options === 'function') { cb = options; } else { try { for (option in options) { value = options[option]; if (index++ > 0) { query_string += '&' + option + '=' + value; } else { query_string = '/?' + option + '=' + value; } } if (index > 0) { uri += query_string; } } catch (error1) { err = error1; return cb(err); } } return this.make_public_request(uri, cb); }; rest.prototype.trades = function (symbol, cb) { return this.make_public_request('trades/' + symbol, cb); }; rest.prototype.lends = function (currency, cb) { return this.make_public_request('lends/' + currency, cb); }; rest.prototype.get_symbols = function (cb) { return this.make_public_request('symbols', cb); }; rest.prototype.symbols_details = function (cb) { return this.make_public_request('symbols_details', cb); }; rest.prototype.new_order = function (symbol, amount, price, exchange, side, type, is_hidden, cb) { var params; if (typeof is_hidden === 'function') { cb = is_hidden; is_hidden = false; } params = { symbol: symbol, amount: amount, price: price, exchange: exchange, side: side, type: type }; if (is_hidden) { params['is_hidden'] = true; } return this.make_request('order/new', params, cb); }; rest.prototype.multiple_new_orders = function (orders, cb) { var params; params = { orders: orders }; return this.make_request('order/new/multi', params, cb); }; rest.prototype.cancel_order = function (order_id, cb) { var params; params = { order_id: parseInt(order_id) }; return this.make_request('order/cancel', params, cb); }; rest.prototype.cancel_all_orders = function (cb) { return this.make_request('order/cancel/all', {}, cb); }; rest.prototype.cancel_multiple_orders = function (order_ids, cb) { var params; params = { order_ids: order_ids.map(function (id) { return parseInt(id); }) }; return this.make_request('order/cancel/multi', params, cb); }; rest.prototype.replace_order = function (order_id, symbol, amount, price, exchange, side, type, cb) { var params; params = { order_id: parseInt(order_id), symbol: symbol, amount: amount, price: price, exchange: exchange, side: side, type: type }; return this.make_request('order/cancel/replace', params, cb); }; rest.prototype.order_status = function (order_id, cb) { var params; params = { order_id: order_id }; return this.make_request('order/status', params, cb); }; rest.prototype.active_orders = function (cb) { return this.make_request('orders', {}, cb); }; rest.prototype.active_positions = function (cb) { return this.make_request('positions', {}, cb); }; rest.prototype.claim_position = function (position_id, cb) { var params; params = { position_id: parseInt(position_id) }; return this.make_request('position/claim', params, cb); }; rest.prototype.balance_history = function (currency, options, cb) { var err, error1, option, params, value; params = { currency: currency }; if (typeof options === 'function') { cb = options; } else { try { for (option in options) { value = options[option]; params[option] = value; } } catch (error1) { err = error1; return cb(err); } } return this.make_request('history', params, cb); }; rest.prototype.movements = function (currency, options, cb) { var err, error1, option, params, value; params = { currency: currency }; if (typeof options === 'function') { cb = options; } else { try { for (option in options) { value = options[option]; params[option] = value; } } catch (error1) { err = error1; return cb(err); } } return this.make_request('history/movements', params, cb); }; rest.prototype.past_trades = function (symbol, options, cb) { var err, error1, option, params, value; params = { symbol: symbol }; if (typeof options === 'function') { cb = options; } else { try { for (option in options) { value = options[option]; params[option] = value; } } catch (error1) { err = error1; return cb(err); } } return this.make_request('mytrades', params, cb); }; rest.prototype.new_deposit = function (currency, method, wallet_name, cb) { var params; params = { currency: currency, method: method, wallet_name: wallet_name }; return this.make_request('deposit/new', params, cb); }; rest.prototype.new_offer = function (currency, amount, rate, period, direction, cb) { var params; params = { currency: currency, amount: amount, rate: rate, period: period, direction: direction }; return this.make_request('offer/new', params, cb); }; rest.prototype.cancel_offer = function (offer_id, cb) { var params; params = { offer_id: offer_id }; return this.make_request('offer/cancel', params, cb); }; rest.prototype.offer_status = function (offer_id, cb) { var params; params = { offer_id: offer_id }; return this.make_request('offer/status', params, cb); }; rest.prototype.active_offers = function (cb) { return this.make_request('offers', {}, cb); }; rest.prototype.active_credits = function (cb) { return this.make_request('credits', {}, cb); }; rest.prototype.wallet_balances = function (cb) { return this.make_request('balances', {}, cb); }; rest.prototype.taken_swaps = function (cb) { return this.make_request('taken_funds', {}, cb); }; rest.prototype.total_taken_swaps = function (cb) { return this.make_request('total_taken_funds', {}, cb); }; rest.prototype.close_swap = function (swap_id, cb) { return this.make_request('swap/close', { swap_id: swap_id }, cb); }; rest.prototype.account_infos = function (cb) { return this.make_request('account_infos', {}, cb); }; rest.prototype.margin_infos = function (cb) { return this.make_request('margin_infos', {}, cb); }; /* POST /v1/withdraw Parameters: 'withdraw_type' :string (can be "bitcoin", "litecoin" or "darkcoin" or "mastercoin") 'walletselected' :string (the origin of the wallet to withdraw from, can be "trading", "exchange", or "deposit") 'amount' :decimal (amount to withdraw) 'address' :address (destination address for withdrawal) */ rest.prototype.withdraw = function (withdraw_type, walletselected, amount, address, cb) { var params; params = { withdraw_type: withdraw_type, walletselected: walletselected, amount: amount, address: address }; return this.make_request('withdraw', params, cb); }; /* POST /v1/transfer Parameters: ‘amount’: decimal (amount to transfer) ‘currency’: string, currency of funds to transfer ‘walletfrom’: string. Wallet to transfer from ‘walletto’: string. Wallet to transfer to */ rest.prototype.transfer = function (amount, currency, walletfrom, walletto, cb) { var params; params = { amount: amount, currency: currency, walletfrom: walletfrom, walletto: walletto }; return this.make_request('transfer', params, cb); }; module.exports = rest
// Generated by CoffeeScript 1.10.0 (function() { module.exports = { Padding: require('./Padding') }; }).call(this);
import LatLng from './models/LatLng'; import LatLngBounds from './models/LatLngBounds'; export { LatLng, LatLngBounds }
/** The YUI module contains the components required for building the YUI seed file. This includes the script loading mechanism, a simple queue, and the core utilities for the library. @module yui @main yui @submodule yui-base **/ /*jshint eqeqeq: false*/ if (typeof YUI != 'undefined') { YUI._YUI = YUI; } /** The YUI global namespace object. This is the constructor for all YUI instances. This is a self-instantiable factory function, meaning you don't need to precede it with the `new` operator. You can invoke it directly like this: YUI().use('*', function (Y) { // Y is a new YUI instance. }); But it also works like this: var Y = YUI(); The `YUI` constructor accepts an optional config object, like this: YUI({ debug: true, combine: false }).use('node', function (Y) { // Y.Node is ready to use. }); See the API docs for the <a href="config.html">Config</a> class for the complete list of supported configuration properties accepted by the YUI constuctor. If a global `YUI` object is already defined, the existing YUI object will not be overwritten, to ensure that defined namespaces are preserved. Each YUI instance has full custom event support, but only if the event system is available. @class YUI @uses EventTarget @constructor @global @param {Object} [config]* Zero or more optional configuration objects. Config values are stored in the `Y.config` property. See the <a href="config.html">Config</a> docs for the list of supported properties. **/ /*global YUI*/ /*global YUI_config*/ var YUI = function() { var i = 0, Y = this, args = arguments, l = args.length, instanceOf = function(o, type) { return (o && o.hasOwnProperty && (o instanceof type)); }, gconf = (typeof YUI_config !== 'undefined') && YUI_config; if (!(instanceOf(Y, YUI))) { Y = new YUI(); } else { // set up the core environment Y._init(); /** Master configuration that might span multiple contexts in a non- browser environment. It is applied first to all instances in all contexts. @example YUI.GlobalConfig = { filter: 'debug' }; YUI().use('node', function (Y) { // debug files used here }); YUI({ filter: 'min' }).use('node', function (Y) { // min files used here }); @property {Object} GlobalConfig @global @static **/ if (YUI.GlobalConfig) { Y.applyConfig(YUI.GlobalConfig); } /** Page-level config applied to all YUI instances created on the current page. This is applied after `YUI.GlobalConfig` and before any instance-level configuration. @example // Single global var to include before YUI seed file YUI_config = { filter: 'debug' }; YUI().use('node', function (Y) { // debug files used here }); YUI({ filter: 'min' }).use('node', function (Y) { // min files used here }); @property {Object} YUI_config @global **/ if (gconf) { Y.applyConfig(gconf); } // bind the specified additional modules for this instance if (!l) { Y._setup(); } } if (l) { // Each instance can accept one or more configuration objects. // These are applied after YUI.GlobalConfig and YUI_Config, // overriding values set in those config files if there is a // matching property. for (; i < l; i++) { Y.applyConfig(args[i]); } Y._setup(); } Y.instanceOf = instanceOf; return Y; }; (function() { var proto, prop, VERSION = 'patched-v3.16.0', PERIOD = '.', BASE = 'http://yui.yahooapis.com/', /* These CSS class names can't be generated by getClassName since it is not available at the time they are being used. */ DOC_LABEL = 'yui3-js-enabled', CSS_STAMP_EL = 'yui3-css-stamp', NOOP = function() {}, SLICE = Array.prototype.slice, APPLY_TO_AUTH = { 'io.xdrReady': 1, // the functions applyTo 'io.xdrResponse': 1, // can call. this should 'SWF.eventHandler': 1 }, // be done at build time hasWin = (typeof window != 'undefined'), win = (hasWin) ? window : null, doc = (hasWin) ? win.document : null, docEl = doc && doc.documentElement, docClass = docEl && docEl.className, instances = {}, time = new Date().getTime(), add = function(el, type, fn, capture) { if (el && el.addEventListener) { el.addEventListener(type, fn, capture); } else if (el && el.attachEvent) { el.attachEvent('on' + type, fn); } }, remove = function(el, type, fn, capture) { if (el && el.removeEventListener) { // this can throw an uncaught exception in FF try { el.removeEventListener(type, fn, capture); } catch (ex) {} } else if (el && el.detachEvent) { el.detachEvent('on' + type, fn); } }, handleReady = function() { YUI.Env.DOMReady = true; if (hasWin) { remove(doc, 'DOMContentLoaded', handleReady); } }, handleLoad = function() { YUI.Env.windowLoaded = true; YUI.Env.DOMReady = true; if (hasWin) { remove(window, 'load', handleLoad); } }, getLoader = function(Y, o) { var loader = Y.Env._loader, lCore = [ 'loader-base' ], G_ENV = YUI.Env, mods = G_ENV.mods; if (loader) { //loader._config(Y.config); loader.ignoreRegistered = false; loader.onEnd = null; loader.data = null; loader.required = []; loader.loadType = null; } else { loader = new Y.Loader(Y.config); Y.Env._loader = loader; } if (mods && mods.loader) { lCore = [].concat(lCore, YUI.Env.loaderExtras); } YUI.Env.core = Y.Array.dedupe([].concat(YUI.Env.core, lCore)); return loader; }, clobber = function(r, s) { for (var i in s) { if (s.hasOwnProperty(i)) { r[i] = s[i]; } } }, ALREADY_DONE = { success: true }; // Stamp the documentElement (HTML) with a class of "yui-loaded" to // enable styles that need to key off of JS being enabled. if (docEl && docClass.indexOf(DOC_LABEL) == -1) { if (docClass) { docClass += ' '; } docClass += DOC_LABEL; docEl.className = docClass; } if (VERSION.indexOf('@') > -1) { VERSION = '3.5.0'; // dev time hack for cdn test } proto = { /** Applies a new configuration object to the config of this YUI instance. This will merge new group/module definitions, and will also update the loader cache if necessary. Updating `Y.config` directly will not update the cache. @method applyConfig @param {Object} o the configuration object. @since 3.2.0 **/ applyConfig: function(o) { o = o || NOOP; var attr, name, // detail, config = this.config, mods = config.modules, groups = config.groups, aliases = config.aliases, loader = this.Env._loader; for (name in o) { if (o.hasOwnProperty(name)) { attr = o[name]; if (mods && name == 'modules') { clobber(mods, attr); } else if (aliases && name == 'aliases') { clobber(aliases, attr); } else if (groups && name == 'groups') { clobber(groups, attr); } else if (name == 'win') { config[name] = (attr && attr.contentWindow) || attr; config.doc = config[name] ? config[name].document : null; } else if (name == '_yuid') { // preserve the guid } else { config[name] = attr; } } } if (loader) { loader._config(o); } }, /** Old way to apply a config to this instance (calls `applyConfig` under the hood). @private @method _config @param {Object} o The config to apply **/ _config: function(o) { this.applyConfig(o); }, /** Initializes this YUI instance. @private @method _init **/ _init: function() { var filter, el, Y = this, G_ENV = YUI.Env, Env = Y.Env, prop; /** The version number of this YUI instance. This value is typically updated by a script when a YUI release is built, so it may not reflect the correct version number when YUI is run from the development source tree. @property {String} version **/ Y.version = VERSION; if (!Env) { Y.Env = { core: ['get', 'features', 'intl-base', 'yui-log', 'yui-later'], loaderExtras: ['loader-rollup', 'loader-yui3'], mods: {}, // flat module map versions: {}, // version module map base: BASE, cdn: BASE + VERSION + '/build/', // bootstrapped: false, _idx: 0, _used: {}, _attached: {}, _exported: {}, _missed: [], _yidx: 0, _uidx: 0, _guidp: 'y', _loaded: {}, // serviced: {}, // Regex in English: // I'll start at the \b(yui). // 1. Look in the test string for "yui" or // "yui-base" or "yui-davglass" or "yui-foobar" that comes after a word break. That is, it // can't match "foyui" or "i_heart_yui". This can be anywhere in the string. // 2. After #1 must come a forward slash followed by the string matched in #1, so // "yui-base/yui-base" or "yui-pants/yui-pants". // 3. The second occurence of the #1 token can optionally be followed by "-debug" or "-min", // so "yui/yui-min", "yui/yui-debug", "yui-base/yui-base-debug". NOT "yui/yui-tshirt". // 4. This is followed by ".js", so "yui/yui.js". // 0. Going back to the beginning, now. If all that stuff in 1-4 comes after a "?" in the string, // then capture the junk between the LAST "&" and the string in 1-4. So // "blah?foo/yui/yui.js" will capture "foo/" and "blah?some/thing.js&3.3.0/build/yui-davglass/yui-davglass.js" // will capture "3.3.0/build/" // // Regex Exploded: // (?:\? Find a ? // (?:[^&]*&) followed by 0..n characters followed by an & // * in fact, find as many sets of characters followed by a & as you can // ([^&]*) capture the stuff after the last & in \1 // )? but it's ok if all this ?junk&more_junk stuff isn't even there // \b( after a word break find either the string // yui(?:-\w+)? "yui" optionally followed by a -, then more characters // ) and store the yui-* string in \2 // \/\2 then comes a / followed by the yui-* string in \2 // (?:-(min|debug))? optionally followed by "-min" or "-debug" // .js and ending in ".js" _BASE_RE: /(?:\?(?:[^&]*&)*([^&]*))?\b(yui(?:-\w+)?)\/\2(?:-(min|debug))?\.js/, parseBasePath: function(src, pattern) { var match = src.match(pattern), path, filter; if (match) { path = RegExp.leftContext || src.slice(0, src.indexOf(match[0])); // this is to set up the path to the loader. The file // filter for loader should match the yui include. filter = match[3]; // extract correct path for mixed combo urls // http://yuilibrary.com/projects/yui3/ticket/2528423 if (match[1]) { path += '?' + match[1]; } path = { filter: filter, path: path }; } return path; }, getBase: G_ENV && G_ENV.getBase || function(pattern) { var nodes = (doc && doc.getElementsByTagName('script')) || [], path = Env.cdn, parsed, i, len, src; for (i = 0, len = nodes.length; i < len; ++i) { src = nodes[i].src; if (src) { parsed = Y.Env.parseBasePath(src, pattern); if (parsed) { filter = parsed.filter; path = parsed.path; break; } } } // use CDN default return path; } }; Env = Y.Env; Env._loaded[VERSION] = {}; if (G_ENV && Y !== YUI) { Env._yidx = ++G_ENV._yidx; Env._guidp = ('yui_' + VERSION + '_' + Env._yidx + '_' + time).replace(/[^a-z0-9_]+/g, '_'); } else if (YUI._YUI) { G_ENV = YUI._YUI.Env; Env._yidx += G_ENV._yidx; Env._uidx += G_ENV._uidx; for (prop in G_ENV) { if (!(prop in Env)) { Env[prop] = G_ENV[prop]; } } delete YUI._YUI; } Y.id = Y.stamp(Y); instances[Y.id] = Y; } Y.constructor = YUI; // configuration defaults Y.config = Y.config || { bootstrap: true, cacheUse: true, debug: true, doc: doc, fetchCSS: true, throwFail: true, useBrowserConsole: true, useNativeES5: true, win: win, global: Function('return this')() }; //Register the CSS stamp element if (doc && !doc.getElementById(CSS_STAMP_EL)) { el = doc.createElement('div'); el.innerHTML = '<div id="' + CSS_STAMP_EL + '" style="position: absolute !important; visibility: hidden !important"></div>'; YUI.Env.cssStampEl = el.firstChild; if (doc.body) { doc.body.appendChild(YUI.Env.cssStampEl); } else { docEl.insertBefore(YUI.Env.cssStampEl, docEl.firstChild); } } else if (doc && doc.getElementById(CSS_STAMP_EL) && !YUI.Env.cssStampEl) { YUI.Env.cssStampEl = doc.getElementById(CSS_STAMP_EL); } Y.config.lang = Y.config.lang || 'en-US'; Y.config.base = YUI.config.base || Y.Env.getBase(Y.Env._BASE_RE); if (!filter || (!('mindebug').indexOf(filter))) { filter = 'min'; } filter = (filter) ? '-' + filter : filter; Y.config.loaderPath = YUI.config.loaderPath || 'loader/loader' + filter + '.js'; }, /** Finishes the instance setup. Attaches whatever YUI modules were defined at the time that this instance was created. @method _setup @private **/ _setup: function() { var i, Y = this, core = [], mods = YUI.Env.mods, extras = Y.config.core || [].concat(YUI.Env.core); //Clone it.. for (i = 0; i < extras.length; i++) { if (mods[extras[i]]) { core.push(extras[i]); } } Y._attach(['yui-base']); Y._attach(core); if (Y.Loader) { getLoader(Y); } // Y.log(Y.id + ' initialized', 'info', 'yui'); }, /** Executes the named method on the specified YUI instance if that method is whitelisted. @method applyTo @param {String} id YUI instance id. @param {String} method Name of the method to execute. For example: 'Object.keys'. @param {Array} args Arguments to apply to the method. @return {Mixed} Return value from the applied method, or `null` if the specified instance was not found or the method was not whitelisted. **/ applyTo: function(id, method, args) { if (!(method in APPLY_TO_AUTH)) { this.log(method + ': applyTo not allowed', 'warn', 'yui'); return null; } var instance = instances[id], nest, m, i; if (instance) { nest = method.split('.'); m = instance; for (i = 0; i < nest.length; i = i + 1) { m = m[nest[i]]; if (!m) { this.log('applyTo not found: ' + method, 'warn', 'yui'); } } return m && m.apply(instance, args); } return null; }, /** Registers a YUI module and makes it available for use in a `YUI().use()` call or as a dependency for other modules. The easiest way to create a first-class YUI module is to use <a href="http://yui.github.com/shifter/">Shifter</a>, the YUI component build tool. Shifter will automatically wrap your module code in a `YUI.add()` call along with any configuration info required for the module. @example YUI.add('davglass', function (Y) { Y.davglass = function () { Y.log('Dav was here!'); }; }, '3.4.0', { requires: ['harley-davidson', 'mt-dew'] }); @method add @param {String} name Module name. @param {Function} fn Function containing module code. This function will be executed whenever the module is attached to a specific YUI instance. @param {YUI} fn.Y The YUI instance to which this module is attached. @param {String} fn.name Name of the module @param {String} version Module version number. This is currently used only for informational purposes, and is not used internally by YUI. @param {Object} [config] Module config. @param {Array} [config.requires] Array of other module names that must be attached before this module can be attached. @param {Array} [config.optional] Array of optional module names that should be attached before this module is attached if they've already been loaded. If the `loadOptional` YUI option is `true`, optional modules that have not yet been loaded will be loaded just as if they were hard requirements. @param {Array} [config.use] Array of module names that are included within or otherwise provided by this module, and which should be attached automatically when this module is attached. This makes it possible to create "virtual rollup" modules that simply attach a collection of other modules or submodules. @return {YUI} This YUI instance. **/ add: function(name, fn, version, details) { details = details || {}; var env = YUI.Env, mod = { name: name, fn: fn, version: version, details: details }, //Instance hash so we don't apply it to the same instance twice applied = {}, loader, inst, modInfo, i, versions = env.versions; env.mods[name] = mod; versions[version] = versions[version] || {}; versions[version][name] = mod; for (i in instances) { if (instances.hasOwnProperty(i)) { inst = instances[i]; if (!applied[inst.id]) { applied[inst.id] = true; loader = inst.Env._loader; if (loader) { modInfo = loader.getModuleInfo(name); if (!modInfo || modInfo.temp) { loader.addModule(details, name); } } } } } return this; }, /** Executes the callback function associated with each required module, attaching the module to this YUI instance. @method _attach @param {Array} r The array of modules to attach @param {Boolean} [moot=false] If `true`, don't throw a warning if the module is not attached. @private **/ _attach: function(r, moot) { var i, name, mod, details, req, use, after, mods = YUI.Env.mods, aliases = YUI.Env.aliases, Y = this, j, cache = YUI.Env._renderedMods, loader = Y.Env._loader, done = Y.Env._attached, exported = Y.Env._exported, len = r.length, loader, def, go, c = [], modArgs, esCompat, reqlen, modInfo, condition, __exports__, __imports__; //Check for conditional modules (in a second+ instance) and add their requirements //TODO I hate this entire method, it needs to be fixed ASAP (3.5.0) ^davglass for (i = 0; i < len; i++) { name = r[i]; mod = mods[name]; c.push(name); if (loader && loader.conditions[name]) { for (j in loader.conditions[name]) { if (loader.conditions[name].hasOwnProperty(j)) { def = loader.conditions[name][j]; go = def && ((def.ua && Y.UA[def.ua]) || (def.test && def.test(Y))); if (go) { c.push(def.name); } } } } } r = c; len = r.length; for (i = 0; i < len; i++) { if (!done[r[i]]) { name = r[i]; mod = mods[name]; if (aliases && aliases[name] && !mod) { Y._attach(aliases[name]); continue; } if (!mod) { modInfo = loader && loader.getModuleInfo(name); if (modInfo) { mod = modInfo; moot = true; } // Y.log('no js def for: ' + name, 'info', 'yui'); //if (!loader || !loader.moduleInfo[name]) { //if ((!loader || !loader.moduleInfo[name]) && !moot) { if (!moot && name) { if ((name.indexOf('skin-') === -1) && (name.indexOf('css') === -1)) { Y.Env._missed.push(name); Y.Env._missed = Y.Array.dedupe(Y.Env._missed); Y.message('NOT loaded: ' + name, 'warn', 'yui'); } } } else { done[name] = true; //Don't like this, but in case a mod was asked for once, then we fetch it //We need to remove it from the missed list ^davglass for (j = 0; j < Y.Env._missed.length; j++) { if (Y.Env._missed[j] === name) { Y.message('Found: ' + name + ' (was reported as missing earlier)', 'warn', 'yui'); Y.Env._missed.splice(j, 1); } } /* If it's a temp module, we need to redo it's requirements if it's already loaded since it may have been loaded by another instance and it's dependencies might have been redefined inside the fetched file. */ if (loader && cache && cache[name] && cache[name].temp) { loader.getRequires(cache[name]); req = []; modInfo = loader.getModuleInfo(name); for (j in modInfo.expanded_map) { if (modInfo.expanded_map.hasOwnProperty(j)) { req.push(j); } } Y._attach(req); } details = mod.details; req = details.requires; esCompat = details.es; use = details.use; after = details.after; //Force Intl load if there is a language (Loader logic) @todo fix this shit if (details.lang) { req = req || []; req.unshift('intl'); } if (req) { reqlen = req.length; for (j = 0; j < reqlen; j++) { if (!done[req[j]]) { if (!Y._attach(req)) { return false; } break; } } } if (after) { for (j = 0; j < after.length; j++) { if (!done[after[j]]) { if (!Y._attach(after, true)) { return false; } break; } } } if (mod.fn) { modArgs = [Y, name]; if (esCompat) { __imports__ = {}; __exports__ = {}; // passing `exports` and `imports` onto the module function modArgs.push(__imports__, __exports__); if (req) { reqlen = req.length; for (j = 0; j < reqlen; j++) { __imports__[req[j]] = exported.hasOwnProperty(req[j]) ? exported[req[j]] : Y; } } } if (Y.config.throwFail) { __exports__ = mod.fn.apply(esCompat ? undefined : mod, modArgs); } else { try { __exports__ = mod.fn.apply(esCompat ? undefined : mod, modArgs); } catch (e) { Y.error('Attach error: ' + name, e, name); return false; } } if (esCompat) { // store the `exports` in case others `es` modules requires it exported[name] = __exports__; // If an ES module is conditionally loaded and set // to be used "instead" another module, replace the // trigger module's content with the conditionally // loaded one so the values returned by require() // still makes sense condition = mod.details.condition; if (condition && condition.when === 'instead') { exported[condition.trigger] = __exports__; } } } if (use) { for (j = 0; j < use.length; j++) { if (!done[use[j]]) { if (!Y._attach(use)) { return false; } break; } } } } } } return true; }, /** Delays the `use` callback until another event has taken place such as `window.onload`, `domready`, `contentready`, or `available`. @private @method _delayCallback @param {Function} cb The original `use` callback. @param {String|Object} until Either an event name ('load', 'domready', etc.) or an object containing event/args keys for contentready/available. @return {Function} **/ _delayCallback: function(cb, until) { var Y = this, mod = ['event-base']; until = (Y.Lang.isObject(until) ? until : { event: until }); if (until.event === 'load') { mod.push('event-synthetic'); } Y.log('Delaying use callback until: ' + until.event, 'info', 'yui'); return function() { Y.log('Use callback fired, waiting on delay', 'info', 'yui'); var args = arguments; Y._use(mod, function() { Y.log('Delayed use wrapper callback after dependencies', 'info', 'yui'); Y.on(until.event, function() { args[1].delayUntil = until.event; Y.log('Delayed use callback done after ' + until.event, 'info', 'yui'); cb.apply(Y, args); }, until.args); }); }; }, /** Attaches one or more modules to this YUI instance. When this is executed, the requirements of the desired modules are analyzed, and one of several things can happen: * All required modules have already been loaded, and just need to be attached to this YUI instance. In this case, the `use()` callback will be executed synchronously after the modules are attached. * One or more modules have not yet been loaded, or the Get utility is not available, or the `bootstrap` config option is `false`. In this case, a warning is issued indicating that modules are missing, but all available modules will still be attached and the `use()` callback will be executed synchronously. * One or more modules are missing and the Loader is not available but the Get utility is, and `bootstrap` is not `false`. In this case, the Get utility will be used to load the Loader, and we will then proceed to the following state: * One or more modules are missing and the Loader is available. In this case, the Loader will be used to resolve the dependency tree for the missing modules and load them and their dependencies. When the Loader is finished loading modules, the `use()` callback will be executed asynchronously. @example // Loads and attaches dd and its dependencies. YUI().use('dd', function (Y) { // ... }); // Loads and attaches dd and node as well as all of their dependencies. YUI().use(['dd', 'node'], function (Y) { // ... }); // Attaches all modules that have already been loaded. YUI().use('*', function (Y) { // ... }); // Attaches a gallery module. YUI().use('gallery-yql', function (Y) { // ... }); // Attaches a YUI 2in3 module. YUI().use('yui2-datatable', function (Y) { // ... }); @method use @param {String|Array} modules* One or more module names to attach. @param {Function} [callback] Callback function to be executed once all specified modules and their dependencies have been attached. @param {YUI} callback.Y The YUI instance created for this sandbox. @param {Object} callback.status Object containing `success`, `msg` and `data` properties. @chainable **/ use: function() { var args = SLICE.call(arguments, 0), callback = args[args.length - 1], Y = this, i = 0, name, Env = Y.Env, provisioned = true; // The last argument supplied to use can be a load complete callback if (Y.Lang.isFunction(callback)) { args.pop(); if (Y.config.delayUntil) { callback = Y._delayCallback(callback, Y.config.delayUntil); } } else { callback = null; } if (Y.Lang.isArray(args[0])) { args = args[0]; } if (Y.config.cacheUse) { while ((name = args[i++])) { if (!Env._attached[name]) { provisioned = false; break; } } if (provisioned) { if (args.length) { Y.log('already provisioned: ' + args, 'info', 'yui'); } Y._notify(callback, ALREADY_DONE, args); return Y; } } if (Y._loading) { Y._useQueue = Y._useQueue || new Y.Queue(); Y._useQueue.add([args, callback]); } else { Y._use(args, function(Y, response) { Y._notify(callback, response, args); }); } return Y; }, /** Sugar for loading both legacy and ES6-based YUI modules. @method require @param {String} [modules*] List of module names to import or a single module name. @param {Function} callback Callback that gets called once all the modules were loaded. Each parameter of the callback is the export value of the corresponding module in the list. If the module is a legacy YUI module, the YUI instance is used instead of the module exports. @example ``` YUI().require(['es6-set'], function (Y, imports) { var Set = imports.Set, set = new Set(); }); ``` **/ require: function () { var args = SLICE.call(arguments), callback; if (typeof args[args.length - 1] === 'function') { callback = args.pop(); // only add the callback if one was provided // YUI().require('foo'); is valid args.push(function (Y) { var i, length = args.length, exported = Y.Env._exported, __imports__ = {}; // Get only the imports requested as arguments for (i = 0; i < length; i++) { if (exported.hasOwnProperty(args[i])) { __imports__[args[i]] = exported[args[i]]; } } // Using `undefined` because: // - Using `Y.config.global` would force the value of `this` to be // the global object even in strict mode // - Using `Y` goes against the goal of moving away from a shared // object and start thinking in terms of imported and exported // objects callback.call(undefined, Y, __imports__); }); } // Do not return the Y object. This makes it hard to follow this // traditional pattern: // var Y = YUI().use(...); // This is a good idea in the light of ES6 modules, to avoid working // in the global scope. // This also leaves the door open for returning a promise, once the // YUI loader is based on the ES6 loader which uses // loader.import(...).then(...) this.use.apply(this, args); }, /** Handles Loader notifications about attachment/load errors. @method _notify @param {Function} callback Callback to pass to `Y.config.loadErrorFn`. @param {Object} response Response returned from Loader. @param {Array} args Arguments passed from Loader. @private **/ _notify: function(callback, response, args) { if (!response.success && this.config.loadErrorFn) { this.config.loadErrorFn.call(this, this, callback, response, args); } else if (callback) { if (this.Env._missed && this.Env._missed.length) { response.msg = 'Missing modules: ' + this.Env._missed.join(); response.success = false; } if (this.config.throwFail) { callback(this, response); } else { try { callback(this, response); } catch (e) { this.error('use callback error', e, args); } } } }, /** Called from the `use` method queue to ensure that only one set of loading logic is performed at a time. @method _use @param {String} args* One or more modules to attach. @param {Function} [callback] Function to call once all required modules have been attached. @private **/ _use: function(args, callback) { if (!this.Array) { this._attach(['yui-base']); } var len, loader, handleBoot, Y = this, G_ENV = YUI.Env, mods = G_ENV.mods, Env = Y.Env, used = Env._used, aliases = G_ENV.aliases, queue = G_ENV._loaderQueue, firstArg = args[0], YArray = Y.Array, config = Y.config, boot = config.bootstrap, missing = [], i, r = [], ret = true, fetchCSS = config.fetchCSS, process = function(names, skip) { var i = 0, a = [], name, len, m, req, use; if (!names.length) { return; } if (aliases) { len = names.length; for (i = 0; i < len; i++) { if (aliases[names[i]] && !mods[names[i]]) { a = [].concat(a, aliases[names[i]]); } else { a.push(names[i]); } } names = a; } len = names.length; for (i = 0; i < len; i++) { name = names[i]; if (!skip) { r.push(name); } // only attach a module once if (used[name]) { continue; } m = mods[name]; req = null; use = null; if (m) { used[name] = true; req = m.details.requires; use = m.details.use; } else { // CSS files don't register themselves, see if it has // been loaded if (!G_ENV._loaded[VERSION][name]) { missing.push(name); } else { used[name] = true; // probably css } } // make sure requirements are attached if (req && req.length) { process(req); } // make sure we grab the submodule dependencies too if (use && use.length) { process(use, 1); } } }, handleLoader = function(fromLoader) { var response = fromLoader || { success: true, msg: 'not dynamic' }, redo, origMissing, ret = true, data = response.data; Y._loading = false; if (data) { origMissing = missing; missing = []; r = []; process(data); redo = missing.length; if (redo) { if ([].concat(missing).sort().join() == origMissing.sort().join()) { redo = false; } } } if (redo && data) { Y._loading = true; Y._use(missing, function() { Y.log('Nested use callback: ' + data, 'info', 'yui'); if (Y._attach(data)) { Y._notify(callback, response, data); } }); } else { if (data) { // Y.log('attaching from loader: ' + data, 'info', 'yui'); ret = Y._attach(data); } if (ret) { Y._notify(callback, response, args); } } if (Y._useQueue && Y._useQueue.size() && !Y._loading) { Y._use.apply(Y, Y._useQueue.next()); } }; // Y.log(Y.id + ': use called: ' + a + ' :: ' + callback, 'info', 'yui'); // YUI().use('*'); // bind everything available if (firstArg === '*') { args = []; for (i in mods) { if (mods.hasOwnProperty(i)) { args.push(i); } } ret = Y._attach(args); if (ret) { handleLoader(); } return Y; } if ((mods.loader || mods['loader-base']) && !Y.Loader) { Y.log('Loader was found in meta, but it is not attached. Attaching..', 'info', 'yui'); Y._attach(['loader' + ((!mods.loader) ? '-base' : '')]); } // Y.log('before loader requirements: ' + args, 'info', 'yui'); // use loader to expand dependencies and sort the // requirements if it is available. if (boot && Y.Loader && args.length) { Y.log('Using loader to expand dependencies', 'info', 'yui'); loader = getLoader(Y); loader.require(args); loader.ignoreRegistered = true; loader._boot = true; loader.calculate(null, (fetchCSS) ? null : 'js'); args = loader.sorted; loader._boot = false; } process(args); len = missing.length; if (len) { missing = YArray.dedupe(missing); len = missing.length; Y.log('Modules missing: ' + missing + ', ' + missing.length, 'info', 'yui'); } // dynamic load if (boot && len && Y.Loader) { // Y.log('Using loader to fetch missing deps: ' + missing, 'info', 'yui'); Y.log('Using Loader', 'info', 'yui'); Y._loading = true; loader = getLoader(Y); loader.onEnd = handleLoader; loader.context = Y; loader.data = args; loader.ignoreRegistered = false; loader.require(missing); loader.insert(null, (fetchCSS) ? null : 'js'); } else if (boot && len && Y.Get && !Env.bootstrapped) { Y._loading = true; handleBoot = function() { Y._loading = false; queue.running = false; Env.bootstrapped = true; G_ENV._bootstrapping = false; if (Y._attach(['loader'])) { Y._use(args, callback); } }; if (G_ENV._bootstrapping) { Y.log('Waiting for loader', 'info', 'yui'); queue.add(handleBoot); } else { G_ENV._bootstrapping = true; Y.log('Fetching loader: ' + config.base + config.loaderPath, 'info', 'yui'); Y.Get.script(config.base + config.loaderPath, { onEnd: handleBoot }); } } else { Y.log('Attaching available dependencies: ' + args, 'info', 'yui'); ret = Y._attach(args); if (ret) { handleLoader(); } } return Y; }, /** Utility method for safely creating namespaces if they don't already exist. May be called statically on the YUI global object or as a method on a YUI instance. When called statically, a namespace will be created on the YUI global object: // Create `YUI.your.namespace.here` as nested objects, preserving any // objects that already exist instead of overwriting them. YUI.namespace('your.namespace.here'); When called as a method on a YUI instance, a namespace will be created on that instance: // Creates `Y.property.package`. Y.namespace('property.package'); Dots in the input string cause `namespace` to create nested objects for each token. If any part of the requested namespace already exists, the current object will be left in place and will not be overwritten. This allows multiple calls to `namespace` to preserve existing namespaced properties. If the first token in the namespace string is "YAHOO", that token is discarded. This is legacy behavior for backwards compatibility with YUI 2. Be careful with namespace tokens. Reserved words may work in some browsers and not others. For instance, the following will fail in some browsers because the supported version of JavaScript reserves the word "long": Y.namespace('really.long.nested.namespace'); Note: If you pass multiple arguments to create multiple namespaces, only the last one created is returned from this function. @method namespace @param {String} namespace* One or more namespaces to create. @return {Object} Reference to the last namespace object created. **/ namespace: function() { var a = arguments, o, i = 0, j, d, arg; for (; i < a.length; i++) { o = this; //Reset base object per argument or it will get reused from the last arg = a[i]; if (arg.indexOf(PERIOD) > -1) { //Skip this if no "." is present d = arg.split(PERIOD); for (j = (d[0] == 'YAHOO') ? 1 : 0; j < d.length; j++) { o[d[j]] = o[d[j]] || {}; o = o[d[j]]; } } else { o[arg] = o[arg] || {}; o = o[arg]; //Reset base object to the new object so it's returned } } return o; }, // this is replaced if the log module is included log: NOOP, message: NOOP, // this is replaced if the dump module is included dump: function (o) { return ''+o; }, /** Reports an error. The reporting mechanism is controlled by the `throwFail` configuration attribute. If `throwFail` is falsy, the message is logged. If `throwFail` is truthy, a JS exception is thrown. If an `errorFn` is specified in the config it must return `true` to indicate that the exception was handled and keep it from being thrown. @method error @param {String} msg Error message. @param {Error|String} [e] JavaScript error object or an error string. @param {String} [src] Source of the error (such as the name of the module in which the error occurred). @chainable **/ error: function(msg, e, src) { //TODO Add check for window.onerror here var Y = this, ret; if (Y.config.errorFn) { ret = Y.config.errorFn.apply(Y, arguments); } if (!ret) { throw (e || new Error(msg)); } else { Y.message(msg, 'error', ''+src); // don't scrub this one } return Y; }, /** Generates an id string that is unique among all YUI instances in this execution context. @method guid @param {String} [pre] Prefix. @return {String} Unique id. **/ guid: function(pre) { var id = this.Env._guidp + '_' + (++this.Env._uidx); return (pre) ? (pre + id) : id; }, /** Returns a unique id associated with the given object and (if *readOnly* is falsy) stamps the object with that id so it can be identified in the future. Stamping an object involves adding a `_yuid` property to it that contains the object's id. One exception to this is that in Internet Explorer, DOM nodes have a `uniqueID` property that contains a browser-generated unique id, which will be used instead of a YUI-generated id when available. @method stamp @param {Object} o Object to stamp. @param {Boolean} readOnly If truthy and the given object has not already been stamped, the object will not be modified and `null` will be returned. @return {String} Object's unique id, or `null` if *readOnly* was truthy and the given object was not already stamped. **/ stamp: function(o, readOnly) { var uid; if (!o) { return o; } // IE generates its own unique ID for dom nodes // The uniqueID property of a document node returns a new ID if (o.uniqueID && o.nodeType && o.nodeType !== 9) { uid = o.uniqueID; } else { uid = (typeof o === 'string') ? o : o._yuid; } if (!uid) { uid = this.guid(); if (!readOnly) { try { o._yuid = uid; } catch (e) { uid = null; } } } return uid; }, /** Destroys this YUI instance. @method destroy @since 3.3.0 **/ destroy: function() { var Y = this; if (Y.Event) { Y.Event._unload(); } delete instances[Y.id]; delete Y.Env; delete Y.config; } /** Safe `instanceof` wrapper that works around a memory leak in IE when the object being tested is `window` or `document`. Unless you are testing objects that may be `window` or `document`, you should use the native `instanceof` operator instead of this method. @method instanceOf @param {Object} o Object to check. @param {Object} type Class to check against. @since 3.3.0 **/ }; YUI.prototype = proto; // inheritance utilities are not available yet for (prop in proto) { if (proto.hasOwnProperty(prop)) { YUI[prop] = proto[prop]; } } /** Applies a configuration to all YUI instances in this execution context. The main use case for this method is in "mashups" where several third-party scripts need to write to a global YUI config, but cannot share a single centrally-managed config object. This way they can all call `YUI.applyConfig({})` instead of overwriting the single global config. @example YUI.applyConfig({ modules: { davglass: { fullpath: './davglass.js' } } }); YUI.applyConfig({ modules: { foo: { fullpath: './foo.js' } } }); YUI().use('davglass', function (Y) { // Module davglass will be available here. }); @method applyConfig @param {Object} o Configuration object to apply. @static @since 3.5.0 **/ YUI.applyConfig = function(o) { if (!o) { return; } //If there is a GlobalConfig, apply it first to set the defaults if (YUI.GlobalConfig) { this.prototype.applyConfig.call(this, YUI.GlobalConfig); } //Apply this config to it this.prototype.applyConfig.call(this, o); //Reset GlobalConfig to the combined config YUI.GlobalConfig = this.config; }; // set up the environment YUI._init(); if (hasWin) { add(doc, 'DOMContentLoaded', handleReady); // add a window load event at load time so we can capture // the case where it fires before dynamic loading is // complete. add(window, 'load', handleLoad); } else { handleReady(); handleLoad(); } YUI.Env.add = add; YUI.Env.remove = remove; /*global exports*/ // Support the CommonJS method for exporting our single global if (typeof exports == 'object') { exports.YUI = YUI; /** * Set a method to be called when `Get.script` is called in Node.js * `Get` will open the file, then pass it's content and it's path * to this method before attaching it. Commonly used for code coverage * instrumentation. <strong>Calling this multiple times will only * attach the last hook method</strong>. This method is only * available in Node.js. * @method setLoadHook * @static * @param {Function} fn The function to set * @param {String} fn.data The content of the file * @param {String} fn.path The file path of the file */ YUI.setLoadHook = function(fn) { YUI._getLoadHook = fn; }; /** * Load hook for `Y.Get.script` in Node.js, see `YUI.setLoadHook` * @method _getLoadHook * @private * @param {String} data The content of the file * @param {String} path The file path of the file */ YUI._getLoadHook = null; } YUI.Env[VERSION] = {}; }()); /** Config object that contains all of the configuration options for this `YUI` instance. This object is supplied by the implementer when instantiating YUI. Some properties have default values if they are not supplied by the implementer. This object should not be updated directly because some values are cached. Use `applyConfig()` to update the config object on a YUI instance that has already been configured. @class config @static **/ /** If `true` (the default), YUI will "bootstrap" the YUI Loader and module metadata if they're needed to load additional dependencies and aren't already available. Setting this to `false` will prevent YUI from automatically loading the Loader and module metadata, so you will need to manually ensure that they're available or handle dependency resolution yourself. @property {Boolean} bootstrap @default true **/ /** If `true`, `Y.log()` messages will be written to the browser's debug console when available and when `useBrowserConsole` is also `true`. @property {Boolean} debug @default true **/ /** Log messages to the browser console if `debug` is `true` and the browser has a supported console. @property {Boolean} useBrowserConsole @default true **/ /** A hash of log sources that should be logged. If specified, only messages from these sources will be logged. Others will be discarded. @property {Object} logInclude @type object **/ /** A hash of log sources that should be not be logged. If specified, all sources will be logged *except* those on this list. @property {Object} logExclude **/ /** When the YUI seed file is dynamically loaded after the `window.onload` event has fired, set this to `true` to tell YUI that it shouldn't wait for `window.onload` to occur. This ensures that components that rely on `window.onload` and the `domready` custom event will work as expected even when YUI is dynamically injected. @property {Boolean} injected @default false **/ /** If `true`, `Y.error()` will generate or re-throw a JavaScript error. Otherwise, errors are merely logged silently. @property {Boolean} throwFail @default true **/ /** Reference to the global object for this execution context. In a browser, this is the current `window` object. In Node.js, this is the Node.js `global` object. @property {Object} global **/ /** The browser window or frame that this YUI instance should operate in. When running in Node.js, this property is `undefined`, since there is no `window` object. Use `global` to get a reference to the global object that will work in both browsers and Node.js. @property {Window} win **/ /** The browser `document` object associated with this YUI instance's `win` object. When running in Node.js, this property is `undefined`, since there is no `document` object. @property {Document} doc **/ /** A list of modules that defines the YUI core (overrides the default list). @property {Array} core @type Array @default ['get', 'features', 'intl-base', 'yui-log', 'yui-later', 'loader-base', 'loader-rollup', 'loader-yui3'] **/ /** A list of languages to use in order of preference. This list is matched against the list of available languages in modules that the YUI instance uses to determine the best possible localization of language sensitive modules. Languages are represented using BCP 47 language tags, such as "en-GB" for English as used in the United Kingdom, or "zh-Hans-CN" for simplified Chinese as used in China. The list may be provided as a comma-separated string or as an array. @property {String|String[]} lang **/ /** Default date format. @property {String} dateFormat @deprecated Use configuration in `DataType.Date.format()` instead. **/ /** Default locale. @property {String} locale @deprecated Use `config.lang` instead. **/ /** Default generic polling interval in milliseconds. @property {Number} pollInterval @default 20 **/ /** The number of dynamic `<script>` nodes to insert by default before automatically removing them when loading scripts. This applies only to script nodes because removing the node will not make the evaluated script unavailable. Dynamic CSS nodes are not auto purged, because removing a linked style sheet will also remove the style definitions. @property {Number} purgethreshold @default 20 **/ /** Delay in milliseconds to wait after a window `resize` event before firing the event. If another `resize` event occurs before this delay has elapsed, the delay will start over to ensure that `resize` events are throttled. @property {Number} windowResizeDelay @default 40 **/ /** Base directory for dynamic loading. @property {String} base **/ /** Base URL for a dynamic combo handler. This will be used to make combo-handled module requests if `combine` is set to `true. @property {String} comboBase @default "http://yui.yahooapis.com/combo?" **/ /** Root path to prepend to each module path when creating a combo-handled request. This is updated for each YUI release to point to a specific version of the library; for example: "3.8.0/build/". @property {String} root **/ /** Filter to apply to module urls. This filter will modify the default path for all modules. The default path for the YUI library is the minified version of the files (e.g., event-min.js). The filter property can be a predefined filter or a custom filter. The valid predefined filters are: - **debug**: Loads debug versions of modules (e.g., event-debug.js). - **raw**: Loads raw, non-minified versions of modules without debug logging (e.g., event.js). You can also define a custom filter, which must be an object literal containing a search regular expression and a replacement string: myFilter: { searchExp : "-min\\.js", replaceStr: "-debug.js" } @property {Object|String} filter **/ /** Skin configuration and customizations. @property {Object} skin @param {String} [skin.defaultSkin='sam'] Default skin name. This skin will be applied automatically to skinnable components if not overridden by a component-specific skin name. @param {String} [skin.base='assets/skins/'] Default base path for a skin, relative to Loader's `base` path. @param {Object} [skin.overrides] Component-specific skin name overrides. Specify a component name as the key and, as the value, a string or array of strings for a skin or skins that should be loaded for that component instead of the `defaultSkin`. **/ /** Hash of per-component filter specifications. If specified for a given component, this overrides the global `filter` config. @example YUI({ modules: { 'foo': './foo.js', 'bar': './bar.js', 'baz': './baz.js' }, filters: { 'foo': { searchExp: '.js', replaceStr: '-coverage.js' } } }).use('foo', 'bar', 'baz', function (Y) { // foo-coverage.js is loaded // bar.js is loaded // baz.js is loaded }); @property {Object} filters **/ /** If `true`, YUI will use a combo handler to load multiple modules in as few requests as possible. The YUI CDN (which YUI uses by default) supports combo handling, but other servers may not. If the server from which you're loading YUI does not support combo handling, set this to `false`. Providing a value for the `base` config property will cause `combine` to default to `false` instead of `true`. @property {Boolean} combine @default true */ /** Array of module names that should never be dynamically loaded. @property {String[]} ignore **/ /** Array of module names that should always be loaded when required, even if already present on the page. @property {String[]} force **/ /** DOM element or id that should be used as the insertion point for dynamically added `<script>` and `<link>` nodes. @property {HTMLElement|String} insertBefore **/ /** Object hash containing attributes to add to dynamically added `<script>` nodes. @property {Object} jsAttributes **/ /** Object hash containing attributes to add to dynamically added `<link>` nodes. @property {Object} cssAttributes **/ /** Timeout in milliseconds before a dynamic JS or CSS request will be considered a failure. If not set, no timeout will be enforced. @property {Number} timeout **/ /** A hash of module definitions to add to the list of available YUI modules. These modules can then be dynamically loaded via the `use()` method. This is a hash in which keys are module names and values are objects containing module metadata. See `Loader.addModule()` for the supported module metadata fields. Also see `groups`, which provides a way to configure the base and combo spec for a set of modules. @example modules: { mymod1: { requires: ['node'], fullpath: '/mymod1/mymod1.js' }, mymod2: { requires: ['mymod1'], fullpath: '/mymod2/mymod2.js' }, mymod3: '/js/mymod3.js', mycssmod: '/css/mycssmod.css' } @property {Object} modules **/ /** Aliases are dynamic groups of modules that can be used as shortcuts. @example YUI({ aliases: { davglass: [ 'node', 'yql', 'dd' ], mine: [ 'davglass', 'autocomplete'] } }).use('mine', function (Y) { // Node, YQL, DD & AutoComplete available here. }); @property {Object} aliases **/ /** A hash of module group definitions. For each group you can specify a list of modules and the base path and combo spec to use when dynamically loading the modules. @example groups: { yui2: { // specify whether or not this group has a combo service combine: true, // The comboSeperator to use with this group's combo handler comboSep: ';', // The maxURLLength for this server maxURLLength: 500, // the base path for non-combo paths base: 'http://yui.yahooapis.com/2.8.0r4/build/', // the path to the combo service comboBase: 'http://yui.yahooapis.com/combo?', // a fragment to prepend to the path attribute when // when building combo urls root: '2.8.0r4/build/', // the module definitions modules: { yui2_yde: { path: "yahoo-dom-event/yahoo-dom-event.js" }, yui2_anim: { path: "animation/animation.js", requires: ['yui2_yde'] } } } } @property {Object} groups **/ /** Path to the Loader JS file, relative to the `base` path. This is used to dynamically bootstrap the Loader when it's needed and isn't yet available. @property {String} loaderPath @default "loader/loader-min.js" **/ /** If `true`, YUI will attempt to load CSS dependencies and skins. Set this to `false` to prevent YUI from loading any CSS, or set it to the string `"force"` to force CSS dependencies to be loaded even if their associated JS modules are already loaded. @property {Boolean|String} fetchCSS @default true **/ /** Default gallery version used to build gallery module urls. @property {String} gallery @since 3.1.0 **/ /** Default YUI 2 version used to build YUI 2 module urls. This is used for intrinsic YUI 2 support via the 2in3 project. Also see the `2in3` config for pulling different revisions of the wrapped YUI 2 modules. @property {String} yui2 @default "2.9.0" @since 3.1.0 **/ /** Revision number of YUI 2in3 modules that should be used when loading YUI 2in3. @property {String} 2in3 @default "4" @since 3.1.0 **/ /** Alternate console log function that should be used in environments without a supported native console. This function is executed with the YUI instance as its `this` object. @property {Function} logFn @since 3.1.0 **/ /** The minimum log level to log messages for. Log levels are defined incrementally. Messages greater than or equal to the level specified will be shown. All others will be discarded. The order of log levels in increasing priority is: debug info warn error @property {String} logLevel @default 'debug' @since 3.10.0 **/ /** Callback to execute when `Y.error()` is called. It receives the error message and a JavaScript error object if one was provided. This function is executed with the YUI instance as its `this` object. Returning `true` from this function will prevent an exception from being thrown. @property {Function} errorFn @param {String} errorFn.msg Error message @param {Object} [errorFn.err] Error object (if one was provided). @since 3.2.0 **/ /** A callback to execute when Loader fails to load one or more resources. This could be because of a script load failure. It could also be because a module fails to register itself when the `requireRegistration` config is `true`. If this function is defined, the `use()` callback will only be called when the loader succeeds. Otherwise, `use()` will always executes unless there was a JavaScript error when attaching a module. @property {Function} loadErrorFn @since 3.3.0 **/ /** If `true`, Loader will expect all loaded scripts to be first-class YUI modules that register themselves with the YUI global, and will trigger a failure if a loaded script does not register a YUI module. @property {Boolean} requireRegistration @default false @since 3.3.0 **/ /** Cache serviced use() requests. @property {Boolean} cacheUse @default true @since 3.3.0 @deprecated No longer used. **/ /** Whether or not YUI should use native ES5 functionality when available for features like `Y.Array.each()`, `Y.Object()`, etc. When `false`, YUI will always use its own fallback implementations instead of relying on ES5 functionality, even when ES5 functionality is available. @property {Boolean} useNativeES5 @default true @since 3.5.0 **/ /** * Leverage native JSON stringify if the browser has a native * implementation. In general, this is a good idea. See the Known Issues * section in the JSON user guide for caveats. The default value is true * for browsers with native JSON support. * * @property useNativeJSONStringify * @type Boolean * @default true * @since 3.8.0 */ /** * Leverage native JSON parse if the browser has a native implementation. * In general, this is a good idea. See the Known Issues section in the * JSON user guide for caveats. The default value is true for browsers with * native JSON support. * * @property useNativeJSONParse * @type Boolean * @default true * @since 3.8.0 */ /** Delay the `use` callback until a specific event has passed (`load`, `domready`, `contentready` or `available`) @property {Object|String} delayUntil @since 3.6.0 @example You can use `load` or `domready` strings by default: YUI({ delayUntil: 'domready' }, function (Y) { // This will not execute until 'domeready' occurs. }); Or you can delay until a node is available (with `available` or `contentready`): YUI({ delayUntil: { event: 'available', args : '#foo' } }, function (Y) { // This will not execute until a node matching the selector "#foo" is // available in the DOM. }); **/ YUI.add('yui-base', function (Y, NAME) { /* * YUI stub * @module yui * @submodule yui-base */ /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * Provides core language utilites and extensions used throughout YUI. * * @class Lang * @static */ var L = Y.Lang || (Y.Lang = {}), STRING_PROTO = String.prototype, TOSTRING = Object.prototype.toString, TYPES = { 'undefined' : 'undefined', 'number' : 'number', 'boolean' : 'boolean', 'string' : 'string', '[object Function]': 'function', '[object RegExp]' : 'regexp', '[object Array]' : 'array', '[object Date]' : 'date', '[object Error]' : 'error' }, SUBREGEX = /\{\s*([^|}]+?)\s*(?:\|([^}]*))?\s*\}/g, WHITESPACE = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF", WHITESPACE_CLASS = "[\x09-\x0D\x20\xA0\u1680\u180E\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]+", TRIM_LEFT_REGEX = new RegExp("^" + WHITESPACE_CLASS), TRIM_RIGHT_REGEX = new RegExp(WHITESPACE_CLASS + "$"), TRIMREGEX = new RegExp(TRIM_LEFT_REGEX.source + "|" + TRIM_RIGHT_REGEX.source, "g"), NATIVE_FN_REGEX = /\{\s*\[(?:native code|function)\]\s*\}/i; // -- Protected Methods -------------------------------------------------------- /** Returns `true` if the given function appears to be implemented in native code, `false` otherwise. Will always return `false` -- even in ES5-capable browsers -- if the `useNativeES5` YUI config option is set to `false`. This isn't guaranteed to be 100% accurate and won't work for anything other than functions, but it can be useful for determining whether a function like `Array.prototype.forEach` is native or a JS shim provided by another library. There's a great article by @kangax discussing certain flaws with this technique: <http://perfectionkills.com/detecting-built-in-host-methods/> While his points are valid, it's still possible to benefit from this function as long as it's used carefully and sparingly, and in such a way that false negatives have minimal consequences. It's used internally to avoid using potentially broken non-native ES5 shims that have been added to the page by other libraries. @method _isNative @param {Function} fn Function to test. @return {Boolean} `true` if _fn_ appears to be native, `false` otherwise. @static @protected @since 3.5.0 **/ L._isNative = function (fn) { return !!(Y.config.useNativeES5 && fn && NATIVE_FN_REGEX.test(fn)); }; // -- Public Methods ----------------------------------------------------------- /** * Determines whether or not the provided item is an array. * * Returns `false` for array-like collections such as the function `arguments` * collection or `HTMLElement` collections. Use `Y.Array.test()` if you want to * test for an array-like collection. * * @method isArray * @param o The object to test. * @return {boolean} true if o is an array. * @static */ L.isArray = L._isNative(Array.isArray) ? Array.isArray : function (o) { return L.type(o) === 'array'; }; /** * Determines whether or not the provided item is a boolean. * @method isBoolean * @static * @param o The object to test. * @return {boolean} true if o is a boolean. */ L.isBoolean = function(o) { return typeof o === 'boolean'; }; /** * Determines whether or not the supplied item is a date instance. * @method isDate * @static * @param o The object to test. * @return {boolean} true if o is a date. */ L.isDate = function(o) { return L.type(o) === 'date' && o.toString() !== 'Invalid Date' && !isNaN(o); }; /** * <p> * Determines whether or not the provided item is a function. * Note: Internet Explorer thinks certain functions are objects: * </p> * * <pre> * var obj = document.createElement("object"); * Y.Lang.isFunction(obj.getAttribute) // reports false in IE * &nbsp; * var input = document.createElement("input"); // append to body * Y.Lang.isFunction(input.focus) // reports false in IE * </pre> * * <p> * You will have to implement additional tests if these functions * matter to you. * </p> * * @method isFunction * @static * @param o The object to test. * @return {boolean} true if o is a function. */ L.isFunction = function(o) { return L.type(o) === 'function'; }; /** * Determines whether or not the provided item is null. * @method isNull * @static * @param o The object to test. * @return {boolean} true if o is null. */ L.isNull = function(o) { return o === null; }; /** * Determines whether or not the provided item is a legal number. * @method isNumber * @static * @param o The object to test. * @return {boolean} true if o is a number. */ L.isNumber = function(o) { return typeof o === 'number' && isFinite(o); }; /** * Determines whether or not the provided item is of type object * or function. Note that arrays are also objects, so * <code>Y.Lang.isObject([]) === true</code>. * @method isObject * @static * @param o The object to test. * @param failfn {boolean} fail if the input is a function. * @return {boolean} true if o is an object. * @see isPlainObject */ L.isObject = function(o, failfn) { var t = typeof o; return (o && (t === 'object' || (!failfn && (t === 'function' || L.isFunction(o))))) || false; }; /** * Determines whether or not the provided value is a regexp. * @method isRegExp * @static * @param value The value or object to test. * @return {boolean} true if value is a regexp. */ L.isRegExp = function(value) { return L.type(value) === 'regexp'; }; /** * Determines whether or not the provided item is a string. * @method isString * @static * @param o The object to test. * @return {boolean} true if o is a string. */ L.isString = function(o) { return typeof o === 'string'; }; /** * Determines whether or not the provided item is undefined. * @method isUndefined * @static * @param o The object to test. * @return {boolean} true if o is undefined. */ L.isUndefined = function(o) { return typeof o === 'undefined'; }; /** * A convenience method for detecting a legitimate non-null value. * Returns false for null/undefined/NaN, true for other values, * including 0/false/'' * @method isValue * @static * @param o The item to test. * @return {boolean} true if it is not null/undefined/NaN || false. */ L.isValue = function(o) { var t = L.type(o); switch (t) { case 'number': return isFinite(o); case 'null': // fallthru case 'undefined': return false; default: return !!t; } }; /** * Returns the current time in milliseconds. * * @method now * @return {Number} Current time in milliseconds. * @static * @since 3.3.0 */ L.now = Date.now || function () { return new Date().getTime(); }; /** * Performs `{placeholder}` substitution on a string. The object passed as the * second parameter provides values to replace the `{placeholder}`s. * `{placeholder}` token names must match property names of the object. For example, * *`var greeting = Y.Lang.sub("Hello, {who}!", { who: "World" });` * * `{placeholder}` tokens that are undefined on the object map will be left * in tact (leaving unsightly `{placeholder}`'s in the output string). * * @method sub * @param {string} s String to be modified. * @param {object} o Object containing replacement values. * @return {string} the substitute result. * @static * @since 3.2.0 */ L.sub = function(s, o) { return s.replace ? s.replace(SUBREGEX, function (match, key) { return L.isUndefined(o[key]) ? match : o[key]; }) : s; }; /** * Returns a string without any leading or trailing whitespace. If * the input is not a string, the input will be returned untouched. * @method trim * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trim = L._isNative(STRING_PROTO.trim) && !WHITESPACE.trim() ? function(s) { return s && s.trim ? s.trim() : s; } : function (s) { try { return s.replace(TRIMREGEX, ''); } catch (e) { return s; } }; /** * Returns a string without any leading whitespace. * @method trimLeft * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trimLeft = L._isNative(STRING_PROTO.trimLeft) && !WHITESPACE.trimLeft() ? function (s) { return s.trimLeft(); } : function (s) { return s.replace(TRIM_LEFT_REGEX, ''); }; /** * Returns a string without any trailing whitespace. * @method trimRight * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trimRight = L._isNative(STRING_PROTO.trimRight) && !WHITESPACE.trimRight() ? function (s) { return s.trimRight(); } : function (s) { return s.replace(TRIM_RIGHT_REGEX, ''); }; /** Returns one of the following strings, representing the type of the item passed in: * "array" * "boolean" * "date" * "error" * "function" * "null" * "number" * "object" * "regexp" * "string" * "undefined" Known issues: * `typeof HTMLElementCollection` returns function in Safari, but `Y.Lang.type()` reports "object", which could be a good thing -- but it actually caused the logic in <code>Y.Lang.isObject</code> to fail. @method type @param o the item to test. @return {string} the detected type. @static **/ L.type = function(o) { return TYPES[typeof o] || TYPES[TOSTRING.call(o)] || (o ? 'object' : 'null'); }; /** @module yui @submodule yui-base */ var Lang = Y.Lang, Native = Array.prototype, hasOwn = Object.prototype.hasOwnProperty; /** Provides utility methods for working with arrays. Additional array helpers can be found in the `collection` and `array-extras` modules. `Y.Array(thing)` returns a native array created from _thing_. Depending on _thing_'s type, one of the following will happen: * Arrays are returned unmodified unless a non-zero _startIndex_ is specified. * Array-like collections (see `Array.test()`) are converted to arrays. * For everything else, a new array is created with _thing_ as the sole item. Note: elements that are also collections, such as `<form>` and `<select>` elements, are not automatically converted to arrays. To force a conversion, pass `true` as the value of the _force_ parameter. @class Array @constructor @param {Any} thing The thing to arrayify. @param {Number} [startIndex=0] If non-zero and _thing_ is an array or array-like collection, a subset of items starting at the specified index will be returned. @param {Boolean} [force=false] If `true`, _thing_ will be treated as an array-like collection no matter what. @return {Array} A native array created from _thing_, according to the rules described above. **/ function YArray(thing, startIndex, force) { var len, result; /*jshint expr: true*/ startIndex || (startIndex = 0); if (force || YArray.test(thing)) { // IE throws when trying to slice HTMLElement collections. try { return Native.slice.call(thing, startIndex); } catch (ex) { result = []; for (len = thing.length; startIndex < len; ++startIndex) { result.push(thing[startIndex]); } return result; } } return [thing]; } Y.Array = YArray; /** Dedupes an array of strings, returning an array that's guaranteed to contain only one copy of a given string. This method differs from `Array.unique()` in that it's optimized for use only with arrays consisting entirely of strings or entirely of numbers, whereas `unique` may be used with other value types (but is slower). Using `dedupe()` with values other than strings or numbers, or with arrays containing a mix of strings and numbers, may result in unexpected behavior. @method dedupe @param {String[]|Number[]} array Array of strings or numbers to dedupe. @return {Array} Copy of _array_ containing no duplicate values. @static @since 3.4.0 **/ YArray.dedupe = Lang._isNative(Object.create) ? function (array) { var hash = Object.create(null), results = [], i, item, len; for (i = 0, len = array.length; i < len; ++i) { item = array[i]; if (!hash[item]) { hash[item] = 1; results.push(item); } } return results; } : function (array) { var hash = {}, results = [], i, item, len; for (i = 0, len = array.length; i < len; ++i) { item = array[i]; if (!hasOwn.call(hash, item)) { hash[item] = 1; results.push(item); } } return results; }; /** Executes the supplied function on each item in the array. This method wraps the native ES5 `Array.forEach()` method if available. @method each @param {Array} array Array to iterate. @param {Function} fn Function to execute on each item in the array. The function will receive the following arguments: @param {Any} fn.item Current array item. @param {Number} fn.index Current array index. @param {Array} fn.array Array being iterated. @param {Object} [thisObj] `this` object to use when calling _fn_. @return {YUI} The YUI instance. @static **/ YArray.each = YArray.forEach = Lang._isNative(Native.forEach) ? function (array, fn, thisObj) { Native.forEach.call(array || [], fn, thisObj || Y); return Y; } : function (array, fn, thisObj) { for (var i = 0, len = (array && array.length) || 0; i < len; ++i) { if (i in array) { fn.call(thisObj || Y, array[i], i, array); } } return Y; }; /** Alias for `each()`. @method forEach @static **/ /** Returns an object using the first array as keys and the second as values. If the second array is not provided, or if it doesn't contain the same number of values as the first array, then `true` will be used in place of the missing values. @example Y.Array.hash(['a', 'b', 'c'], ['foo', 'bar']); // => {a: 'foo', b: 'bar', c: true} @method hash @param {String[]} keys Array of strings to use as keys. @param {Array} [values] Array to use as values. @return {Object} Hash using the first array as keys and the second as values. @static **/ YArray.hash = function (keys, values) { var hash = {}, vlen = (values && values.length) || 0, i, len; for (i = 0, len = keys.length; i < len; ++i) { if (i in keys) { hash[keys[i]] = vlen > i && i in values ? values[i] : true; } } return hash; }; /** Returns the index of the first item in the array that's equal (using a strict equality check) to the specified _value_, or `-1` if the value isn't found. This method wraps the native ES5 `Array.indexOf()` method if available. @method indexOf @param {Array} array Array to search. @param {Any} value Value to search for. @param {Number} [from=0] The index at which to begin the search. @return {Number} Index of the item strictly equal to _value_, or `-1` if not found. @static **/ YArray.indexOf = Lang._isNative(Native.indexOf) ? function (array, value, from) { return Native.indexOf.call(array, value, from); } : function (array, value, from) { // http://es5.github.com/#x15.4.4.14 var len = array.length; from = +from || 0; from = (from > 0 || -1) * Math.floor(Math.abs(from)); if (from < 0) { from += len; if (from < 0) { from = 0; } } for (; from < len; ++from) { if (from in array && array[from] === value) { return from; } } return -1; }; /** Numeric sort convenience function. The native `Array.prototype.sort()` function converts values to strings and sorts them in lexicographic order, which is unsuitable for sorting numeric values. Provide `Array.numericSort` as a custom sort function when you want to sort values in numeric order. @example [42, 23, 8, 16, 4, 15].sort(Y.Array.numericSort); // => [4, 8, 15, 16, 23, 42] @method numericSort @param {Number} a First value to compare. @param {Number} b Second value to compare. @return {Number} Difference between _a_ and _b_. @static **/ YArray.numericSort = function (a, b) { return a - b; }; /** Executes the supplied function on each item in the array. Returning a truthy value from the function will stop the processing of remaining items. @method some @param {Array} array Array to iterate over. @param {Function} fn Function to execute on each item. The function will receive the following arguments: @param {Any} fn.value Current array item. @param {Number} fn.index Current array index. @param {Array} fn.array Array being iterated over. @param {Object} [thisObj] `this` object to use when calling _fn_. @return {Boolean} `true` if the function returns a truthy value on any of the items in the array; `false` otherwise. @static **/ YArray.some = Lang._isNative(Native.some) ? function (array, fn, thisObj) { return Native.some.call(array, fn, thisObj); } : function (array, fn, thisObj) { for (var i = 0, len = array.length; i < len; ++i) { if (i in array && fn.call(thisObj, array[i], i, array)) { return true; } } return false; }; /** Evaluates _obj_ to determine if it's an array, an array-like collection, or something else. This is useful when working with the function `arguments` collection and `HTMLElement` collections. Note: This implementation doesn't consider elements that are also collections, such as `<form>` and `<select>`, to be array-like. @method test @param {Object} obj Object to test. @return {Number} A number indicating the results of the test: * 0: Neither an array nor an array-like collection. * 1: Real array. * 2: Array-like collection. @static **/ YArray.test = function (obj) { var result = 0; if (Lang.isArray(obj)) { result = 1; } else if (Lang.isObject(obj)) { try { // indexed, but no tagName (element) or scrollTo/document (window. From DOM.isWindow test which we can't use here), // or functions without apply/call (Safari // HTMLElementCollection bug). if ('length' in obj && !obj.tagName && !(obj.scrollTo && obj.document) && !obj.apply) { result = 2; } } catch (ex) {} } return result; }; /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * A simple FIFO queue. Items are added to the Queue with add(1..n items) and * removed using next(). * * @class Queue * @constructor * @param {MIXED} item* 0..n items to seed the queue. */ function Queue() { this._init(); this.add.apply(this, arguments); } Queue.prototype = { /** * Initialize the queue * * @method _init * @protected */ _init: function() { /** * The collection of enqueued items * * @property _q * @type Array * @protected */ this._q = []; }, /** * Get the next item in the queue. FIFO support * * @method next * @return {MIXED} the next item in the queue. */ next: function() { return this._q.shift(); }, /** * Get the last in the queue. LIFO support. * * @method last * @return {MIXED} the last item in the queue. */ last: function() { return this._q.pop(); }, /** * Add 0..n items to the end of the queue. * * @method add * @param {MIXED} item* 0..n items. * @return {object} this queue. */ add: function() { this._q.push.apply(this._q, arguments); return this; }, /** * Returns the current number of queued items. * * @method size * @return {Number} The size. */ size: function() { return this._q.length; } }; Y.Queue = Queue; YUI.Env._loaderQueue = YUI.Env._loaderQueue || new Queue(); /** The YUI module contains the components required for building the YUI seed file. This includes the script loading mechanism, a simple queue, and the core utilities for the library. @module yui @submodule yui-base **/ var CACHED_DELIMITER = '__', hasOwn = Object.prototype.hasOwnProperty, isObject = Y.Lang.isObject; /** Returns a wrapper for a function which caches the return value of that function, keyed off of the combined string representation of the argument values provided when the wrapper is called. Calling this function again with the same arguments will return the cached value rather than executing the wrapped function. Note that since the cache is keyed off of the string representation of arguments passed to the wrapper function, arguments that aren't strings and don't provide a meaningful `toString()` method may result in unexpected caching behavior. For example, the objects `{}` and `{foo: 'bar'}` would both be converted to the string `[object Object]` when used as a cache key. @method cached @param {Function} source The function to memoize. @param {Object} [cache={}] Object in which to store cached values. You may seed this object with pre-existing cached values if desired. @param {any} [refetch] If supplied, this value is compared with the cached value using a `==` comparison. If the values are equal, the wrapped function is executed again even though a cached value exists. @return {Function} Wrapped function. @for YUI **/ Y.cached = function (source, cache, refetch) { /*jshint expr: true*/ cache || (cache = {}); return function (arg) { var key = arguments.length > 1 ? Array.prototype.join.call(arguments, CACHED_DELIMITER) : String(arg); /*jshint eqeqeq: false*/ if (!(key in cache) || (refetch && cache[key] == refetch)) { cache[key] = source.apply(source, arguments); } return cache[key]; }; }; /** Returns the `location` object from the window/frame in which this YUI instance operates, or `undefined` when executing in a non-browser environment (e.g. Node.js). It is _not_ recommended to hold references to the `window.location` object outside of the scope of a function in which its properties are being accessed or its methods are being called. This is because of a nasty bug/issue that exists in both Safari and MobileSafari browsers: [WebKit Bug 34679](https://bugs.webkit.org/show_bug.cgi?id=34679). @method getLocation @return {location} The `location` object from the window/frame in which this YUI instance operates. @since 3.5.0 **/ Y.getLocation = function () { // It is safer to look this up every time because yui-base is attached to a // YUI instance before a user's config is applied; i.e. `Y.config.win` does // not point the correct window object when this file is loaded. var win = Y.config.win; // It is not safe to hold a reference to the `location` object outside the // scope in which it is being used. The WebKit engine used in Safari and // MobileSafari will "disconnect" the `location` object from the `window` // when a page is restored from back/forward history cache. return win && win.location; }; /** Returns a new object containing all of the properties of all the supplied objects. The properties from later objects will overwrite those in earlier objects. Passing in a single object will create a shallow copy of it. For a deep copy, use `clone()`. @method merge @param {Object} objects* One or more objects to merge. @return {Object} A new merged object. **/ Y.merge = function () { var i = 0, len = arguments.length, result = {}, key, obj; for (; i < len; ++i) { obj = arguments[i]; for (key in obj) { if (hasOwn.call(obj, key)) { result[key] = obj[key]; } } } return result; }; /** Mixes _supplier_'s properties into _receiver_. Properties on _receiver_ or _receiver_'s prototype will not be overwritten or shadowed unless the _overwrite_ parameter is `true`, and will not be merged unless the _merge_ parameter is `true`. In the default mode (0), only properties the supplier owns are copied (prototype properties are not copied). The following copying modes are available: * `0`: _Default_. Object to object. * `1`: Prototype to prototype. * `2`: Prototype to prototype and object to object. * `3`: Prototype to object. * `4`: Object to prototype. @method mix @param {Function|Object} receiver The object or function to receive the mixed properties. @param {Function|Object} supplier The object or function supplying the properties to be mixed. @param {Boolean} [overwrite=false] If `true`, properties that already exist on the receiver will be overwritten with properties from the supplier. @param {String[]} [whitelist] An array of property names to copy. If specified, only the whitelisted properties will be copied, and all others will be ignored. @param {Number} [mode=0] Mix mode to use. See above for available modes. @param {Boolean} [merge=false] If `true`, objects and arrays that already exist on the receiver will have the corresponding object/array from the supplier merged into them, rather than being skipped or overwritten. When both _overwrite_ and _merge_ are `true`, _merge_ takes precedence. @return {Function|Object|YUI} The receiver, or the YUI instance if the specified receiver is falsy. **/ Y.mix = function(receiver, supplier, overwrite, whitelist, mode, merge) { var alwaysOverwrite, exists, from, i, key, len, to; // If no supplier is given, we return the receiver. If no receiver is given, // we return Y. Returning Y doesn't make much sense to me, but it's // grandfathered in for backcompat reasons. if (!receiver || !supplier) { return receiver || Y; } if (mode) { // In mode 2 (prototype to prototype and object to object), we recurse // once to do the proto to proto mix. The object to object mix will be // handled later on. if (mode === 2) { Y.mix(receiver.prototype, supplier.prototype, overwrite, whitelist, 0, merge); } // Depending on which mode is specified, we may be copying from or to // the prototypes of the supplier and receiver. from = mode === 1 || mode === 3 ? supplier.prototype : supplier; to = mode === 1 || mode === 4 ? receiver.prototype : receiver; // If either the supplier or receiver doesn't actually have a // prototype property, then we could end up with an undefined `from` // or `to`. If that happens, we abort and return the receiver. if (!from || !to) { return receiver; } } else { from = supplier; to = receiver; } // If `overwrite` is truthy and `merge` is falsy, then we can skip a // property existence check on each iteration and save some time. alwaysOverwrite = overwrite && !merge; if (whitelist) { for (i = 0, len = whitelist.length; i < len; ++i) { key = whitelist[i]; // We call `Object.prototype.hasOwnProperty` instead of calling // `hasOwnProperty` on the object itself, since the object's // `hasOwnProperty` method may have been overridden or removed. // Also, some native objects don't implement a `hasOwnProperty` // method. if (!hasOwn.call(from, key)) { continue; } // The `key in to` check here is (sadly) intentional for backwards // compatibility reasons. It prevents undesired shadowing of // prototype members on `to`. exists = alwaysOverwrite ? false : key in to; if (merge && exists && isObject(to[key], true) && isObject(from[key], true)) { // If we're in merge mode, and the key is present on both // objects, and the value on both objects is either an object or // an array (but not a function), then we recurse to merge the // `from` value into the `to` value instead of overwriting it. // // Note: It's intentional that the whitelist isn't passed to the // recursive call here. This is legacy behavior that lots of // code still depends on. Y.mix(to[key], from[key], overwrite, null, 0, merge); } else if (overwrite || !exists) { // We're not in merge mode, so we'll only copy the `from` value // to the `to` value if we're in overwrite mode or if the // current key doesn't exist on the `to` object. to[key] = from[key]; } } } else { for (key in from) { // The code duplication here is for runtime performance reasons. // Combining whitelist and non-whitelist operations into a single // loop or breaking the shared logic out into a function both result // in worse performance, and Y.mix is critical enough that the byte // tradeoff is worth it. if (!hasOwn.call(from, key)) { continue; } // The `key in to` check here is (sadly) intentional for backwards // compatibility reasons. It prevents undesired shadowing of // prototype members on `to`. exists = alwaysOverwrite ? false : key in to; if (merge && exists && isObject(to[key], true) && isObject(from[key], true)) { Y.mix(to[key], from[key], overwrite, null, 0, merge); } else if (overwrite || !exists) { to[key] = from[key]; } } // If this is an IE browser with the JScript enumeration bug, force // enumeration of the buggy properties by making a recursive call with // the buggy properties as the whitelist. if (Y.Object._hasEnumBug) { Y.mix(to, from, overwrite, Y.Object._forceEnum, mode, merge); } } return receiver; }; /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * Adds utilities to the YUI instance for working with objects. * * @class Object */ var Lang = Y.Lang, hasOwn = Object.prototype.hasOwnProperty, UNDEFINED, // <-- Note the comma. We're still declaring vars. /** * Returns a new object that uses _obj_ as its prototype. This method wraps the * native ES5 `Object.create()` method if available, but doesn't currently * pass through `Object.create()`'s second argument (properties) in order to * ensure compatibility with older browsers. * * @method () * @param {Object} obj Prototype object. * @return {Object} New object using _obj_ as its prototype. * @static */ O = Y.Object = Lang._isNative(Object.create) ? function (obj) { // We currently wrap the native Object.create instead of simply aliasing it // to ensure consistency with our fallback shim, which currently doesn't // support Object.create()'s second argument (properties). Once we have a // safe fallback for the properties arg, we can stop wrapping // Object.create(). return Object.create(obj); } : (function () { // Reusable constructor function for the Object.create() shim. function F() {} // The actual shim. return function (obj) { F.prototype = obj; return new F(); }; }()), /** * Property names that IE doesn't enumerate in for..in loops, even when they * should be enumerable. When `_hasEnumBug` is `true`, it's necessary to * manually enumerate these properties. * * @property _forceEnum * @type String[] * @protected * @static */ forceEnum = O._forceEnum = [ 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toString', 'toLocaleString', 'valueOf' ], /** * `true` if this browser has the JScript enumeration bug that prevents * enumeration of the properties named in the `_forceEnum` array, `false` * otherwise. * * See: * - <https://developer.mozilla.org/en/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug> * - <http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation> * * @property _hasEnumBug * @type Boolean * @protected * @static */ hasEnumBug = O._hasEnumBug = !{valueOf: 0}.propertyIsEnumerable('valueOf'), /** * `true` if this browser incorrectly considers the `prototype` property of * functions to be enumerable. Currently known to affect Opera 11.50 and Android 2.3.x. * * @property _hasProtoEnumBug * @type Boolean * @protected * @static */ hasProtoEnumBug = O._hasProtoEnumBug = (function () {}).propertyIsEnumerable('prototype'), /** * Returns `true` if _key_ exists on _obj_, `false` if _key_ doesn't exist or * exists only on _obj_'s prototype. This is essentially a safer version of * `obj.hasOwnProperty()`. * * @method owns * @param {Object} obj Object to test. * @param {String} key Property name to look for. * @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise. * @static */ owns = O.owns = function (obj, key) { return !!obj && hasOwn.call(obj, key); }; // <-- End of var declarations. /** * Alias for `owns()`. * * @method hasKey * @param {Object} obj Object to test. * @param {String} key Property name to look for. * @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise. * @static */ O.hasKey = owns; /** * Returns an array containing the object's enumerable keys. Does not include * prototype keys or non-enumerable keys. * * Note that keys are returned in enumeration order (that is, in the same order * that they would be enumerated by a `for-in` loop), which may not be the same * as the order in which they were defined. * * This method is an alias for the native ES5 `Object.keys()` method if * available and non-buggy. The Opera 11.50 and Android 2.3.x versions of * `Object.keys()` have an inconsistency as they consider `prototype` to be * enumerable, so a non-native shim is used to rectify the difference. * * @example * * Y.Object.keys({a: 'foo', b: 'bar', c: 'baz'}); * // => ['a', 'b', 'c'] * * @method keys * @param {Object} obj An object. * @return {String[]} Array of keys. * @static */ O.keys = Lang._isNative(Object.keys) && !hasProtoEnumBug ? Object.keys : function (obj) { if (!Lang.isObject(obj)) { throw new TypeError('Object.keys called on a non-object'); } var keys = [], i, key, len; if (hasProtoEnumBug && typeof obj === 'function') { for (key in obj) { if (owns(obj, key) && key !== 'prototype') { keys.push(key); } } } else { for (key in obj) { if (owns(obj, key)) { keys.push(key); } } } if (hasEnumBug) { for (i = 0, len = forceEnum.length; i < len; ++i) { key = forceEnum[i]; if (owns(obj, key)) { keys.push(key); } } } return keys; }; /** * Returns an array containing the values of the object's enumerable keys. * * Note that values are returned in enumeration order (that is, in the same * order that they would be enumerated by a `for-in` loop), which may not be the * same as the order in which they were defined. * * @example * * Y.Object.values({a: 'foo', b: 'bar', c: 'baz'}); * // => ['foo', 'bar', 'baz'] * * @method values * @param {Object} obj An object. * @return {Array} Array of values. * @static */ O.values = function (obj) { var keys = O.keys(obj), i = 0, len = keys.length, values = []; for (; i < len; ++i) { values.push(obj[keys[i]]); } return values; }; /** * Returns the number of enumerable keys owned by an object. * * @method size * @param {Object} obj An object. * @return {Number} The object's size. * @static */ O.size = function (obj) { try { return O.keys(obj).length; } catch (ex) { return 0; // Legacy behavior for non-objects. } }; /** * Returns `true` if the object owns an enumerable property with the specified * value. * * @method hasValue * @param {Object} obj An object. * @param {any} value The value to search for. * @return {Boolean} `true` if _obj_ contains _value_, `false` otherwise. * @static */ O.hasValue = function (obj, value) { return Y.Array.indexOf(O.values(obj), value) > -1; }; /** * Executes a function on each enumerable property in _obj_. The function * receives the value, the key, and the object itself as parameters (in that * order). * * By default, only properties owned by _obj_ are enumerated. To include * prototype properties, set the _proto_ parameter to `true`. * * @method each * @param {Object} obj Object to enumerate. * @param {Function} fn Function to execute on each enumerable property. * @param {mixed} fn.value Value of the current property. * @param {String} fn.key Key of the current property. * @param {Object} fn.obj Object being enumerated. * @param {Object} [thisObj] `this` object to use when calling _fn_. * @param {Boolean} [proto=false] Include prototype properties. * @return {YUI} the YUI instance. * @chainable * @static */ O.each = function (obj, fn, thisObj, proto) { var key; for (key in obj) { if (proto || owns(obj, key)) { fn.call(thisObj || Y, obj[key], key, obj); } } return Y; }; /** * Executes a function on each enumerable property in _obj_, but halts if the * function returns a truthy value. The function receives the value, the key, * and the object itself as paramters (in that order). * * By default, only properties owned by _obj_ are enumerated. To include * prototype properties, set the _proto_ parameter to `true`. * * @method some * @param {Object} obj Object to enumerate. * @param {Function} fn Function to execute on each enumerable property. * @param {mixed} fn.value Value of the current property. * @param {String} fn.key Key of the current property. * @param {Object} fn.obj Object being enumerated. * @param {Object} [thisObj] `this` object to use when calling _fn_. * @param {Boolean} [proto=false] Include prototype properties. * @return {Boolean} `true` if any execution of _fn_ returns a truthy value, * `false` otherwise. * @static */ O.some = function (obj, fn, thisObj, proto) { var key; for (key in obj) { if (proto || owns(obj, key)) { if (fn.call(thisObj || Y, obj[key], key, obj)) { return true; } } } return false; }; /** * Retrieves the sub value at the provided path, * from the value object provided. * * @method getValue * @static * @param o The object from which to extract the property value. * @param path {Array} A path array, specifying the object traversal path * from which to obtain the sub value. * @return {Any} The value stored in the path, undefined if not found, * undefined if the source is not an object. Returns the source object * if an empty path is provided. */ O.getValue = function(o, path) { if (!Lang.isObject(o)) { return UNDEFINED; } var i, p = Y.Array(path), l = p.length; for (i = 0; o !== UNDEFINED && i < l; i++) { o = o[p[i]]; } return o; }; /** * Sets the sub-attribute value at the provided path on the * value object. Returns the modified value object, or * undefined if the path is invalid. * * @method setValue * @static * @param o The object on which to set the sub value. * @param path {Array} A path array, specifying the object traversal path * at which to set the sub value. * @param val {Any} The new value for the sub-attribute. * @return {Object} The modified object, with the new sub value set, or * undefined, if the path was invalid. */ O.setValue = function(o, path, val) { var i, p = Y.Array(path), leafIdx = p.length - 1, ref = o; if (leafIdx >= 0) { for (i = 0; ref !== UNDEFINED && i < leafIdx; i++) { ref = ref[p[i]]; } if (ref !== UNDEFINED) { ref[p[i]] = val; } else { return UNDEFINED; } } return o; }; /** * Returns `true` if the object has no enumerable properties of its own. * * @method isEmpty * @param {Object} obj An object. * @return {Boolean} `true` if the object is empty. * @static * @since 3.2.0 */ O.isEmpty = function (obj) { return !O.keys(Object(obj)).length; }; /** * The YUI module contains the components required for building the YUI seed * file. This includes the script loading mechanism, a simple queue, and the * core utilities for the library. * @module yui * @submodule yui-base */ /** * YUI user agent detection. * Do not fork for a browser if it can be avoided. Use feature detection when * you can. Use the user agent as a last resort. For all fields listed * as @type float, UA stores a version number for the browser engine, * 0 otherwise. This value may or may not map to the version number of * the browser using the engine. The value is presented as a float so * that it can easily be used for boolean evaluation as well as for * looking for a particular range of versions. Because of this, * some of the granularity of the version info may be lost. The fields that * are @type string default to null. The API docs list the values that * these fields can have. * @class UA * @static */ /** * Static method on `YUI.Env` for parsing a UA string. Called at instantiation * to populate `Y.UA`. * * @static * @method parseUA * @param {String} [subUA=navigator.userAgent] UA string to parse * @return {Object} The Y.UA object */ YUI.Env.parseUA = function(subUA) { var numberify = function(s) { var c = 0; return parseFloat(s.replace(/\./g, function() { return (c++ === 1) ? '' : '.'; })); }, win = Y.config.win, nav = win && win.navigator, o = { /** * Internet Explorer version number or 0. Example: 6 * @property ie * @type float * @static */ ie: 0, /** * Opera version number or 0. Example: 9.2 * @property opera * @type float * @static */ opera: 0, /** * Gecko engine revision number. Will evaluate to 1 if Gecko * is detected but the revision could not be found. Other browsers * will be 0. Example: 1.8 * <pre> * Firefox 1.0.0.4: 1.7.8 <-- Reports 1.7 * Firefox 1.5.0.9: 1.8.0.9 <-- 1.8 * Firefox 2.0.0.3: 1.8.1.3 <-- 1.81 * Firefox 3.0 <-- 1.9 * Firefox 3.5 <-- 1.91 * </pre> * @property gecko * @type float * @static */ gecko: 0, /** * AppleWebKit version. KHTML browsers that are not WebKit browsers * will evaluate to 1, other browsers 0. Example: 418.9 * <pre> * Safari 1.3.2 (312.6): 312.8.1 <-- Reports 312.8 -- currently the * latest available for Mac OSX 10.3. * Safari 2.0.2: 416 <-- hasOwnProperty introduced * Safari 2.0.4: 418 <-- preventDefault fixed * Safari 2.0.4 (419.3): 418.9.1 <-- One version of Safari may run * different versions of webkit * Safari 2.0.4 (419.3): 419 <-- Tiger installations that have been * updated, but not updated * to the latest patch. * Webkit 212 nightly: 522+ <-- Safari 3.0 precursor (with native * SVG and many major issues fixed). * Safari 3.0.4 (523.12) 523.12 <-- First Tiger release - automatic * update from 2.x via the 10.4.11 OS patch. * Webkit nightly 1/2008:525+ <-- Supports DOMContentLoaded event. * yahoo.com user agent hack removed. * </pre> * http://en.wikipedia.org/wiki/Safari_version_history * @property webkit * @type float * @static */ webkit: 0, /** * Safari will be detected as webkit, but this property will also * be populated with the Safari version number * @property safari * @type float * @static */ safari: 0, /** * Chrome will be detected as webkit, but this property will also * be populated with the Chrome version number * @property chrome * @type float * @static */ chrome: 0, /** * The mobile property will be set to a string containing any relevant * user agent information when a modern mobile browser is detected. * Currently limited to Safari on the iPhone/iPod Touch, Nokia N-series * devices with the WebKit-based browser, and Opera Mini. * @property mobile * @type string * @default null * @static */ mobile: null, /** * Adobe AIR version number or 0. Only populated if webkit is detected. * Example: 1.0 * @property air * @type float */ air: 0, /** * PhantomJS version number or 0. Only populated if webkit is detected. * Example: 1.0 * @property phantomjs * @type float */ phantomjs: 0, /** * Detects Apple iPad's OS version * @property ipad * @type float * @static */ ipad: 0, /** * Detects Apple iPhone's OS version * @property iphone * @type float * @static */ iphone: 0, /** * Detects Apples iPod's OS version * @property ipod * @type float * @static */ ipod: 0, /** * General truthy check for iPad, iPhone or iPod * @property ios * @type Boolean * @default null * @static */ ios: null, /** * Detects Googles Android OS version * @property android * @type float * @static */ android: 0, /** * Detects Kindle Silk * @property silk * @type float * @static */ silk: 0, /** * Detects Kindle Silk Acceleration * @property accel * @type Boolean * @static */ accel: false, /** * Detects Palms WebOS version * @property webos * @type float * @static */ webos: 0, /** * Google Caja version number or 0. * @property caja * @type float */ caja: nav && nav.cajaVersion, /** * Set to true if the page appears to be in SSL * @property secure * @type boolean * @static */ secure: false, /** * The operating system. Currently only detecting windows or macintosh * @property os * @type string * @default null * @static */ os: null, /** * The Nodejs Version * @property nodejs * @type float * @default 0 * @static */ nodejs: 0, /** * Window8/IE10 Application host environment * @property winjs * @type Boolean * @static */ winjs: !!((typeof Windows !== "undefined") && Windows.System), /** * Are touch/msPointer events available on this device * @property touchEnabled * @type Boolean * @static */ touchEnabled: false }, ua = subUA || nav && nav.userAgent, loc = win && win.location, href = loc && loc.href, m; /** * The User Agent string that was parsed * @property userAgent * @type String * @static */ o.userAgent = ua; o.secure = href && (href.toLowerCase().indexOf('https') === 0); if (ua) { if ((/windows|win32/i).test(ua)) { o.os = 'windows'; } else if ((/macintosh|mac_powerpc/i).test(ua)) { o.os = 'macintosh'; } else if ((/android/i).test(ua)) { o.os = 'android'; } else if ((/symbos/i).test(ua)) { o.os = 'symbos'; } else if ((/linux/i).test(ua)) { o.os = 'linux'; } else if ((/rhino/i).test(ua)) { o.os = 'rhino'; } // Modern KHTML browsers should qualify as Safari X-Grade if ((/KHTML/).test(ua)) { o.webkit = 1; } if ((/IEMobile|XBLWP7/).test(ua)) { o.mobile = 'windows'; } if ((/Fennec/).test(ua)) { o.mobile = 'gecko'; } // Modern WebKit browsers are at least X-Grade m = ua.match(/AppleWebKit\/([^\s]*)/); if (m && m[1]) { o.webkit = numberify(m[1]); o.safari = o.webkit; if (/PhantomJS/.test(ua)) { m = ua.match(/PhantomJS\/([^\s]*)/); if (m && m[1]) { o.phantomjs = numberify(m[1]); } } // Mobile browser check if (/ Mobile\//.test(ua) || (/iPad|iPod|iPhone/).test(ua)) { o.mobile = 'Apple'; // iPhone or iPod Touch m = ua.match(/OS ([^\s]*)/); if (m && m[1]) { m = numberify(m[1].replace('_', '.')); } o.ios = m; o.os = 'ios'; o.ipad = o.ipod = o.iphone = 0; m = ua.match(/iPad|iPod|iPhone/); if (m && m[0]) { o[m[0].toLowerCase()] = o.ios; } } else { m = ua.match(/NokiaN[^\/]*|webOS\/\d\.\d/); if (m) { // Nokia N-series, webOS, ex: NokiaN95 o.mobile = m[0]; } if (/webOS/.test(ua)) { o.mobile = 'WebOS'; m = ua.match(/webOS\/([^\s]*);/); if (m && m[1]) { o.webos = numberify(m[1]); } } if (/ Android/.test(ua)) { if (/Mobile/.test(ua)) { o.mobile = 'Android'; } m = ua.match(/Android ([^\s]*);/); if (m && m[1]) { o.android = numberify(m[1]); } } if (/Silk/.test(ua)) { m = ua.match(/Silk\/([^\s]*)/); if (m && m[1]) { o.silk = numberify(m[1]); } if (!o.android) { o.android = 2.34; //Hack for desktop mode in Kindle o.os = 'Android'; } if (/Accelerated=true/.test(ua)) { o.accel = true; } } } m = ua.match(/OPR\/(\d+\.\d+)/); if (m && m[1]) { // Opera 15+ with Blink (pretends to be both Chrome and Safari) o.opera = numberify(m[1]); } else { m = ua.match(/(Chrome|CrMo|CriOS)\/([^\s]*)/); if (m && m[1] && m[2]) { o.chrome = numberify(m[2]); // Chrome o.safari = 0; //Reset safari back to 0 if (m[1] === 'CrMo') { o.mobile = 'chrome'; } } else { m = ua.match(/AdobeAIR\/([^\s]*)/); if (m) { o.air = m[0]; // Adobe AIR 1.0 or better } } } } if (!o.webkit) { // not webkit // @todo check Opera/8.01 (J2ME/MIDP; Opera Mini/2.0.4509/1316; fi; U; ssr) if (/Opera/.test(ua)) { m = ua.match(/Opera[\s\/]([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); } m = ua.match(/Version\/([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); // opera 10+ } if (/Opera Mobi/.test(ua)) { o.mobile = 'opera'; m = ua.replace('Opera Mobi', '').match(/Opera ([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); } } m = ua.match(/Opera Mini[^;]*/); if (m) { o.mobile = m[0]; // ex: Opera Mini/2.0.4509/1316 } } else { // not opera or webkit m = ua.match(/MSIE ([^;]*)|Trident.*; rv:([0-9.]+)/); if (m && (m[1] || m[2])) { o.ie = numberify(m[1] || m[2]); } else { // not opera, webkit, or ie m = ua.match(/Gecko\/([^\s]*)/); if (m) { o.gecko = 1; // Gecko detected, look for revision m = ua.match(/rv:([^\s\)]*)/); if (m && m[1]) { o.gecko = numberify(m[1]); if (/Mobile|Tablet/.test(ua)) { o.mobile = "ffos"; } } } } } } } //Check for known properties to tell if touch events are enabled on this device or if //the number of MSPointer touchpoints on this device is greater than 0. if (win && nav && !(o.chrome && o.chrome < 6)) { o.touchEnabled = (("ontouchstart" in win) || (("msMaxTouchPoints" in nav) && (nav.msMaxTouchPoints > 0))); } //It was a parsed UA, do not assign the global value. if (!subUA) { if (typeof process === 'object') { if (process.versions && process.versions.node) { //NodeJS o.os = process.platform; o.nodejs = numberify(process.versions.node); } } YUI.Env.UA = o; } return o; }; Y.UA = YUI.Env.UA || YUI.Env.parseUA(); /** Performs a simple comparison between two version numbers, accounting for standard versioning logic such as the fact that "535.8" is a lower version than "535.24", even though a simple numerical comparison would indicate that it's greater. Also accounts for cases such as "1.1" vs. "1.1.0", which are considered equivalent. Returns -1 if version _a_ is lower than version _b_, 0 if they're equivalent, 1 if _a_ is higher than _b_. Versions may be numbers or strings containing numbers and dots. For example, both `535` and `"535.8.10"` are acceptable. A version string containing non-numeric characters, like `"535.8.beta"`, may produce unexpected results. @method compareVersions @param {Number|String} a First version number to compare. @param {Number|String} b Second version number to compare. @return -1 if _a_ is lower than _b_, 0 if they're equivalent, 1 if _a_ is higher than _b_. **/ Y.UA.compareVersions = function (a, b) { var aPart, aParts, bPart, bParts, i, len; if (a === b) { return 0; } aParts = (a + '').split('.'); bParts = (b + '').split('.'); for (i = 0, len = Math.max(aParts.length, bParts.length); i < len; ++i) { aPart = parseInt(aParts[i], 10); bPart = parseInt(bParts[i], 10); /*jshint expr: true*/ isNaN(aPart) && (aPart = 0); isNaN(bPart) && (bPart = 0); if (aPart < bPart) { return -1; } if (aPart > bPart) { return 1; } } return 0; }; YUI.Env.aliases = { "anim": ["anim-base","anim-color","anim-curve","anim-easing","anim-node-plugin","anim-scroll","anim-xy"], "anim-shape-transform": ["anim-shape"], "app": ["app-base","app-content","app-transitions","lazy-model-list","model","model-list","model-sync-rest","model-sync-local","router","view","view-node-map"], "attribute": ["attribute-base","attribute-complex"], "attribute-events": ["attribute-observable"], "autocomplete": ["autocomplete-base","autocomplete-sources","autocomplete-list","autocomplete-plugin"], "axes": ["axis-numeric","axis-category","axis-time","axis-stacked"], "axes-base": ["axis-numeric-base","axis-category-base","axis-time-base","axis-stacked-base"], "base": ["base-base","base-pluginhost","base-build"], "cache": ["cache-base","cache-offline","cache-plugin"], "charts": ["charts-base"], "collection": ["array-extras","arraylist","arraylist-add","arraylist-filter","array-invoke"], "color": ["color-base","color-hsl","color-harmony"], "controller": ["router"], "dataschema": ["dataschema-base","dataschema-json","dataschema-xml","dataschema-array","dataschema-text"], "datasource": ["datasource-local","datasource-io","datasource-get","datasource-function","datasource-cache","datasource-jsonschema","datasource-xmlschema","datasource-arrayschema","datasource-textschema","datasource-polling"], "datatable": ["datatable-core","datatable-table","datatable-head","datatable-body","datatable-base","datatable-column-widths","datatable-message","datatable-mutable","datatable-sort","datatable-datasource"], "datatype": ["datatype-date","datatype-number","datatype-xml"], "datatype-date": ["datatype-date-parse","datatype-date-format","datatype-date-math"], "datatype-number": ["datatype-number-parse","datatype-number-format"], "datatype-xml": ["datatype-xml-parse","datatype-xml-format"], "dd": ["dd-ddm-base","dd-ddm","dd-ddm-drop","dd-drag","dd-proxy","dd-constrain","dd-drop","dd-scroll","dd-delegate"], "dom": ["dom-base","dom-screen","dom-style","selector-native","selector"], "editor": ["frame","editor-selection","exec-command","editor-base","editor-para","editor-br","editor-bidi","editor-tab","createlink-base"], "event": ["event-base","event-delegate","event-synthetic","event-mousewheel","event-mouseenter","event-key","event-focus","event-resize","event-hover","event-outside","event-touch","event-move","event-flick","event-valuechange","event-tap"], "event-custom": ["event-custom-base","event-custom-complex"], "event-gestures": ["event-flick","event-move"], "handlebars": ["handlebars-compiler"], "highlight": ["highlight-base","highlight-accentfold"], "history": ["history-base","history-hash","history-html5"], "io": ["io-base","io-xdr","io-form","io-upload-iframe","io-queue"], "json": ["json-parse","json-stringify"], "loader": ["loader-base","loader-rollup","loader-yui3"], "node": ["node-base","node-event-delegate","node-pluginhost","node-screen","node-style"], "pluginhost": ["pluginhost-base","pluginhost-config"], "querystring": ["querystring-parse","querystring-stringify"], "recordset": ["recordset-base","recordset-sort","recordset-filter","recordset-indexer"], "resize": ["resize-base","resize-proxy","resize-constrain"], "slider": ["slider-base","slider-value-range","clickable-rail","range-slider"], "template": ["template-base","template-micro"], "text": ["text-accentfold","text-wordbreak"], "widget": ["widget-base","widget-htmlparser","widget-skin","widget-uievents"] }; }, 'patched-v3.16.0', {"use": ["get", "features", "intl-base", "yui-log", "yui-later"]}); YUI.add('get', function (Y, NAME) { /*jslint boss:true, expr:true, laxbreak: true */ /** Provides dynamic loading of remote JavaScript and CSS resources. @module get @class Get @static **/ var Lang = Y.Lang, CUSTOM_ATTRS, // defined lazily in Y.Get.Transaction._createNode() Get, Transaction; Y.Get = Get = { // -- Public Properties ---------------------------------------------------- /** Default options for CSS requests. Options specified here will override global defaults for CSS requests. See the `options` property for all available options. @property cssOptions @type Object @static @since 3.5.0 **/ cssOptions: { attributes: { rel: 'stylesheet' }, doc : Y.config.linkDoc || Y.config.doc, pollInterval: 50 }, /** Default options for JS requests. Options specified here will override global defaults for JS requests. See the `options` property for all available options. @property jsOptions @type Object @static @since 3.5.0 **/ jsOptions: { autopurge: true, doc : Y.config.scriptDoc || Y.config.doc }, /** Default options to use for all requests. Note that while all available options are documented here for ease of discovery, some options (like callback functions) only make sense at the transaction level. Callback functions specified via the options object or the `options` parameter of the `css()`, `js()`, or `load()` methods will receive the transaction object as a parameter. See `Y.Get.Transaction` for details on the properties and methods available on transactions. @static @since 3.5.0 @property {Object} options @property {Boolean} [options.async=false] Whether or not to load scripts asynchronously, meaning they're requested in parallel and execution order is not guaranteed. Has no effect on CSS, since CSS is always loaded asynchronously. @property {Object} [options.attributes] HTML attribute name/value pairs that should be added to inserted nodes. By default, the `charset` attribute will be set to "utf-8" and nodes will be given an auto-generated `id` attribute, but you can override these with your own values if desired. @property {Boolean} [options.autopurge] Whether or not to automatically purge inserted nodes after the purge threshold is reached. This is `true` by default for JavaScript, but `false` for CSS since purging a CSS node will also remove any styling applied by the referenced file. @property {Object} [options.context] `this` object to use when calling callback functions. Defaults to the transaction object. @property {Mixed} [options.data] Arbitrary data object to pass to "on*" callbacks. @property {Document} [options.doc] Document into which nodes should be inserted. By default, the current document is used. @property {HTMLElement|String} [options.insertBefore] HTML element or id string of an element before which all generated nodes should be inserted. If not specified, Get will automatically determine the best place to insert nodes for maximum compatibility. @property {Function} [options.onEnd] Callback to execute after a transaction is complete, regardless of whether it succeeded or failed. @property {Function} [options.onFailure] Callback to execute after a transaction fails, times out, or is aborted. @property {Function} [options.onProgress] Callback to execute after each individual request in a transaction either succeeds or fails. @property {Function} [options.onSuccess] Callback to execute after a transaction completes successfully with no errors. Note that in browsers that don't support the `error` event on CSS `<link>` nodes, a failed CSS request may still be reported as a success because in these browsers it can be difficult or impossible to distinguish between success and failure for CSS resources. @property {Function} [options.onTimeout] Callback to execute after a transaction times out. @property {Number} [options.pollInterval=50] Polling interval (in milliseconds) for detecting CSS load completion in browsers that don't support the `load` event on `<link>` nodes. This isn't used for JavaScript. @property {Number} [options.purgethreshold=20] Number of nodes to insert before triggering an automatic purge when `autopurge` is `true`. @property {Number} [options.timeout] Number of milliseconds to wait before aborting a transaction. When a timeout occurs, the `onTimeout` callback is called, followed by `onFailure` and finally `onEnd`. By default, there is no timeout. @property {String} [options.type] Resource type ("css" or "js"). This option is set automatically by the `css()` and `js()` functions and will be ignored there, but may be useful when using the `load()` function. If not specified, the type will be inferred from the URL, defaulting to "js" if the URL doesn't contain a recognizable file extension. **/ options: { attributes: { charset: 'utf-8' }, purgethreshold: 20 }, // -- Protected Properties ------------------------------------------------- /** Regex that matches a CSS URL. Used to guess the file type when it's not specified. @property REGEX_CSS @type RegExp @final @protected @static @since 3.5.0 **/ REGEX_CSS: /\.css(?:[?;].*)?$/i, /** Regex that matches a JS URL. Used to guess the file type when it's not specified. @property REGEX_JS @type RegExp @final @protected @static @since 3.5.0 **/ REGEX_JS : /\.js(?:[?;].*)?$/i, /** Contains information about the current environment, such as what script and link injection features it supports. This object is created and populated the first time the `_getEnv()` method is called. @property _env @type Object @protected @static @since 3.5.0 **/ /** Mapping of document _yuid strings to <head> or <base> node references so we don't have to look the node up each time we want to insert a request node. @property _insertCache @type Object @protected @static @since 3.5.0 **/ _insertCache: {}, /** Information about the currently pending transaction, if any. This is actually an object with two properties: `callback`, containing the optional callback passed to `css()`, `load()`, or `js()`; and `transaction`, containing the actual transaction instance. @property _pending @type Object @protected @static @since 3.5.0 **/ _pending: null, /** HTML nodes eligible to be purged next time autopurge is triggered. @property _purgeNodes @type HTMLElement[] @protected @static @since 3.5.0 **/ _purgeNodes: [], /** Queued transactions and associated callbacks. @property _queue @type Object[] @protected @static @since 3.5.0 **/ _queue: [], // -- Public Methods ------------------------------------------------------- /** Aborts the specified transaction. This will cause the transaction's `onFailure` callback to be called and will prevent any new script and link nodes from being added to the document, but any resources that have already been requested will continue loading (there's no safe way to prevent this, unfortunately). *Note:* This method is deprecated as of 3.5.0, and will be removed in a future version of YUI. Use the transaction-level `abort()` method instead. @method abort @param {Get.Transaction} transaction Transaction to abort. @deprecated Use the `abort()` method on the transaction instead. @static **/ abort: function (transaction) { var i, id, item, len, pending; Y.log('`Y.Get.abort()` is deprecated as of 3.5.0. Use the `abort()` method on the transaction instead.', 'warn', 'get'); if (!transaction.abort) { id = transaction; pending = this._pending; transaction = null; if (pending && pending.transaction.id === id) { transaction = pending.transaction; this._pending = null; } else { for (i = 0, len = this._queue.length; i < len; ++i) { item = this._queue[i].transaction; if (item.id === id) { transaction = item; this._queue.splice(i, 1); break; } } } } transaction && transaction.abort(); }, /** Loads one or more CSS files. The _urls_ parameter may be provided as a URL string, a request object, or an array of URL strings and/or request objects. A request object is just an object that contains a `url` property and zero or more options that should apply specifically to that request. Request-specific options take priority over transaction-level options and default options. URLs may be relative or absolute, and do not have to have the same origin as the current page. The `options` parameter may be omitted completely and a callback passed in its place, if desired. @example // Load a single CSS file and log a message on completion. Y.Get.css('foo.css', function (err) { if (err) { Y.log('foo.css failed to load!'); } else { Y.log('foo.css was loaded successfully'); } }); // Load multiple CSS files and log a message when all have finished // loading. var urls = ['foo.css', 'http://example.com/bar.css', 'baz/quux.css']; Y.Get.css(urls, function (err) { if (err) { Y.log('one or more files failed to load!'); } else { Y.log('all files loaded successfully'); } }); // Specify transaction-level options, which will apply to all requests // within the transaction. Y.Get.css(urls, { attributes: {'class': 'my-css'}, timeout : 5000 }); // Specify per-request options, which override transaction-level and // default options. Y.Get.css([ {url: 'foo.css', attributes: {id: 'foo'}}, {url: 'bar.css', attributes: {id: 'bar', charset: 'iso-8859-1'}} ]); @method css @param {String|Object|Array} urls URL string, request object, or array of URLs and/or request objects to load. @param {Object} [options] Options for this transaction. See the `Y.Get.options` property for a complete list of available options. @param {Function} [callback] Callback function to be called on completion. This is a general callback and will be called before any more granular callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options` object. @param {Array|null} callback.err Array of errors that occurred during the transaction, or `null` on success. @param {Get.Transaction} callback.transaction Transaction object. @return {Get.Transaction} Transaction object. @static **/ css: function (urls, options, callback) { return this._load('css', urls, options, callback); }, /** Loads one or more JavaScript resources. The _urls_ parameter may be provided as a URL string, a request object, or an array of URL strings and/or request objects. A request object is just an object that contains a `url` property and zero or more options that should apply specifically to that request. Request-specific options take priority over transaction-level options and default options. URLs may be relative or absolute, and do not have to have the same origin as the current page. The `options` parameter may be omitted completely and a callback passed in its place, if desired. Scripts will be executed in the order they're specified unless the `async` option is `true`, in which case they'll be loaded in parallel and executed in whatever order they finish loading. @example // Load a single JS file and log a message on completion. Y.Get.js('foo.js', function (err) { if (err) { Y.log('foo.js failed to load!'); } else { Y.log('foo.js was loaded successfully'); } }); // Load multiple JS files, execute them in order, and log a message when // all have finished loading. var urls = ['foo.js', 'http://example.com/bar.js', 'baz/quux.js']; Y.Get.js(urls, function (err) { if (err) { Y.log('one or more files failed to load!'); } else { Y.log('all files loaded successfully'); } }); // Specify transaction-level options, which will apply to all requests // within the transaction. Y.Get.js(urls, { attributes: {'class': 'my-js'}, timeout : 5000 }); // Specify per-request options, which override transaction-level and // default options. Y.Get.js([ {url: 'foo.js', attributes: {id: 'foo'}}, {url: 'bar.js', attributes: {id: 'bar', charset: 'iso-8859-1'}} ]); @method js @param {String|Object|Array} urls URL string, request object, or array of URLs and/or request objects to load. @param {Object} [options] Options for this transaction. See the `Y.Get.options` property for a complete list of available options. @param {Function} [callback] Callback function to be called on completion. This is a general callback and will be called before any more granular callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options` object. @param {Array|null} callback.err Array of errors that occurred during the transaction, or `null` on success. @param {Get.Transaction} callback.transaction Transaction object. @return {Get.Transaction} Transaction object. @since 3.5.0 @static **/ js: function (urls, options, callback) { return this._load('js', urls, options, callback); }, /** Loads one or more CSS and/or JavaScript resources in the same transaction. Use this method when you want to load both CSS and JavaScript in a single transaction and be notified when all requested URLs have finished loading, regardless of type. Behavior and options are the same as for the `css()` and `js()` methods. If a resource type isn't specified in per-request options or transaction-level options, Get will guess the file type based on the URL's extension (`.css` or `.js`, with or without a following query string). If the file type can't be guessed from the URL, a warning will be logged and Get will assume the URL is a JavaScript resource. @example // Load both CSS and JS files in a single transaction, and log a message // when all files have finished loading. Y.Get.load(['foo.css', 'bar.js', 'baz.css'], function (err) { if (err) { Y.log('one or more files failed to load!'); } else { Y.log('all files loaded successfully'); } }); @method load @param {String|Object|Array} urls URL string, request object, or array of URLs and/or request objects to load. @param {Object} [options] Options for this transaction. See the `Y.Get.options` property for a complete list of available options. @param {Function} [callback] Callback function to be called on completion. This is a general callback and will be called before any more granular callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options` object. @param {Array|null} err Array of errors that occurred during the transaction, or `null` on success. @param {Get.Transaction} Transaction object. @return {Get.Transaction} Transaction object. @since 3.5.0 @static **/ load: function (urls, options, callback) { return this._load(null, urls, options, callback); }, // -- Protected Methods ---------------------------------------------------- /** Triggers an automatic purge if the purge threshold has been reached. @method _autoPurge @param {Number} threshold Purge threshold to use, in milliseconds. @protected @since 3.5.0 @static **/ _autoPurge: function (threshold) { if (threshold && this._purgeNodes.length >= threshold) { Y.log('autopurge triggered after ' + this._purgeNodes.length + ' nodes', 'info', 'get'); this._purge(this._purgeNodes); } }, /** Populates the `_env` property with information about the current environment. @method _getEnv @return {Object} Environment information. @protected @since 3.5.0 @static **/ _getEnv: function () { var doc = Y.config.doc, ua = Y.UA; // Note: some of these checks require browser sniffs since it's not // feasible to load test files on every pageview just to perform a // feature test. I'm sorry if this makes you sad. return (this._env = { // True if this is a browser that supports disabling async mode on // dynamically created script nodes. See // https://developer.mozilla.org/En/HTML/Element/Script#Attributes // IE10 doesn't return true for the MDN feature test, so setting it explicitly, // because it is async by default, and allows you to disable async by setting it to false async: (doc && doc.createElement('script').async === true) || (ua.ie >= 10), // True if this browser fires an event when a dynamically injected // link node fails to load. This is currently true for Firefox 9+ // and WebKit 535.24+ cssFail: ua.gecko >= 9 || ua.compareVersions(ua.webkit, 535.24) >= 0, // True if this browser fires an event when a dynamically injected // link node finishes loading. This is currently true for IE, Opera, // Firefox 9+, and WebKit 535.24+. Note that IE versions <9 fire the // DOM 0 "onload" event, but not "load". All versions of IE fire // "onload". // davglass: Seems that Chrome on Android needs this to be false. cssLoad: ( (!ua.gecko && !ua.webkit) || ua.gecko >= 9 || ua.compareVersions(ua.webkit, 535.24) >= 0 ) && !(ua.chrome && ua.chrome <= 18), // True if this browser preserves script execution order while // loading scripts in parallel as long as the script node's `async` // attribute is set to false to explicitly disable async execution. preservesScriptOrder: !!(ua.gecko || ua.opera || (ua.ie && ua.ie >= 10)) }); }, _getTransaction: function (urls, options) { var requests = [], i, len, req, url; if (!Lang.isArray(urls)) { urls = [urls]; } options = Y.merge(this.options, options); // Clone the attributes object so we don't end up modifying it by ref. options.attributes = Y.merge(this.options.attributes, options.attributes); for (i = 0, len = urls.length; i < len; ++i) { url = urls[i]; req = {attributes: {}}; // If `url` is a string, we create a URL object for it, then mix in // global options and request-specific options. If it's an object // with a "url" property, we assume it's a request object containing // URL-specific options. if (typeof url === 'string') { req.url = url; } else if (url.url) { // URL-specific options override both global defaults and // request-specific options. Y.mix(req, url, false, null, 0, true); url = url.url; // Make url a string so we can use it later. } else { Y.log('URL must be a string or an object with a `url` property.', 'error', 'get'); continue; } Y.mix(req, options, false, null, 0, true); // If we didn't get an explicit type for this URL either in the // request options or the URL-specific options, try to determine // one from the file extension. if (!req.type) { if (this.REGEX_CSS.test(url)) { req.type = 'css'; } else { if (!this.REGEX_JS.test(url)) { Y.log("Can't guess file type from URL. Assuming JS: " + url, 'warn', 'get'); } req.type = 'js'; } } // Mix in type-specific default options, but don't overwrite any // options that have already been set. Y.mix(req, req.type === 'js' ? this.jsOptions : this.cssOptions, false, null, 0, true); // Give the node an id attribute if it doesn't already have one. req.attributes.id || (req.attributes.id = Y.guid()); // Backcompat for <3.5.0 behavior. if (req.win) { Y.log('The `win` option is deprecated as of 3.5.0. Use `doc` instead.', 'warn', 'get'); req.doc = req.win.document; } else { req.win = req.doc.defaultView || req.doc.parentWindow; } if (req.charset) { Y.log('The `charset` option is deprecated as of 3.5.0. Set `attributes.charset` instead.', 'warn', 'get'); req.attributes.charset = req.charset; } requests.push(req); } return new Transaction(requests, options); }, _load: function (type, urls, options, callback) { var transaction; // Allow callback as third param. if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); options.type = type; options._onFinish = Get._onTransactionFinish; if (!this._env) { this._getEnv(); } transaction = this._getTransaction(urls, options); this._queue.push({ callback : callback, transaction: transaction }); this._next(); return transaction; }, _onTransactionFinish : function() { Get._pending = null; Get._next(); }, _next: function () { var item; if (this._pending) { return; } item = this._queue.shift(); if (item) { this._pending = item; item.transaction.execute(item.callback); } }, _purge: function (nodes) { var purgeNodes = this._purgeNodes, isTransaction = nodes !== purgeNodes, index, node; while (node = nodes.pop()) { // assignment // Don't purge nodes that haven't finished loading (or errored out), // since this can hang the transaction. if (!node._yuiget_finished) { continue; } node.parentNode && node.parentNode.removeChild(node); // If this is a transaction-level purge and this node also exists in // the Get-level _purgeNodes array, we need to remove it from // _purgeNodes to avoid creating a memory leak. The indexOf lookup // sucks, but until we get WeakMaps, this is the least troublesome // way to do this (we can't just hold onto node ids because they may // not be in the same document). if (isTransaction) { index = Y.Array.indexOf(purgeNodes, node); if (index > -1) { purgeNodes.splice(index, 1); } } } } }; /** Alias for `js()`. @method script @static **/ Get.script = Get.js; /** Represents a Get transaction, which may contain requests for one or more JS or CSS files. This class should not be instantiated manually. Instances will be created and returned as needed by Y.Get's `css()`, `js()`, and `load()` methods. @class Get.Transaction @constructor @since 3.5.0 **/ Get.Transaction = Transaction = function (requests, options) { var self = this; self.id = Transaction._lastId += 1; self.data = options.data; self.errors = []; self.nodes = []; self.options = options; self.requests = requests; self._callbacks = []; // callbacks to call after execution finishes self._queue = []; self._reqsWaiting = 0; // Deprecated pre-3.5.0 properties. self.tId = self.id; // Use `id` instead. self.win = options.win || Y.config.win; }; /** Arbitrary data object associated with this transaction. This object comes from the options passed to `Get.css()`, `Get.js()`, or `Get.load()`, and will be `undefined` if no data object was specified. @property {Object} data **/ /** Array of errors that have occurred during this transaction, if any. Each error object has the following properties: `errors.error`: Error message. `errors.request`: Request object related to the error. @since 3.5.0 @property {Object[]} errors **/ /** Numeric id for this transaction, unique among all transactions within the same YUI sandbox in the current pageview. @property {Number} id @since 3.5.0 **/ /** HTMLElement nodes (native ones, not YUI Node instances) that have been inserted during the current transaction. @property {HTMLElement[]} nodes **/ /** Options associated with this transaction. See `Get.options` for the full list of available options. @property {Object} options @since 3.5.0 **/ /** Request objects contained in this transaction. Each request object represents one CSS or JS URL that will be (or has been) requested and loaded into the page. @property {Object} requests @since 3.5.0 **/ /** Id of the most recent transaction. @property _lastId @type Number @protected @static **/ Transaction._lastId = 0; Transaction.prototype = { // -- Public Properties ---------------------------------------------------- /** Current state of this transaction. One of "new", "executing", or "done". @property _state @type String @protected **/ _state: 'new', // "new", "executing", or "done" // -- Public Methods ------------------------------------------------------- /** Aborts this transaction. This will cause the transaction's `onFailure` callback to be called and will prevent any new script and link nodes from being added to the document, but any resources that have already been requested will continue loading (there's no safe way to prevent this, unfortunately). @method abort @param {String} [msg="Aborted."] Optional message to use in the `errors` array describing why the transaction was aborted. **/ abort: function (msg) { this._pending = null; this._pendingCSS = null; this._pollTimer = clearTimeout(this._pollTimer); this._queue = []; this._reqsWaiting = 0; this.errors.push({error: msg || 'Aborted'}); this._finish(); }, /** Begins execting the transaction. There's usually no reason to call this manually, since Get will call it automatically when other pending transactions have finished. If you really want to execute your transaction before Get does, you can, but be aware that this transaction's scripts may end up executing before the scripts in other pending transactions. If the transaction is already executing, the specified callback (if any) will be queued and called after execution finishes. If the transaction has already finished, the callback will be called immediately (the transaction will not be executed again). @method execute @param {Function} callback Callback function to execute after all requests in the transaction are complete, or after the transaction is aborted. **/ execute: function (callback) { var self = this, requests = self.requests, state = self._state, i, len, queue, req; if (state === 'done') { callback && callback(self.errors.length ? self.errors : null, self); return; } else { callback && self._callbacks.push(callback); if (state === 'executing') { return; } } self._state = 'executing'; self._queue = queue = []; if (self.options.timeout) { self._timeout = setTimeout(function () { self.abort('Timeout'); }, self.options.timeout); } self._reqsWaiting = requests.length; for (i = 0, len = requests.length; i < len; ++i) { req = requests[i]; if (req.async || req.type === 'css') { // No need to queue CSS or fully async JS. self._insert(req); } else { queue.push(req); } } self._next(); }, /** Manually purges any `<script>` or `<link>` nodes this transaction has created. Be careful when purging a transaction that contains CSS requests, since removing `<link>` nodes will also remove any styles they applied. @method purge **/ purge: function () { Get._purge(this.nodes); }, // -- Protected Methods ---------------------------------------------------- _createNode: function (name, attrs, doc) { var node = doc.createElement(name), attr, testEl; if (!CUSTOM_ATTRS) { // IE6 and IE7 expect property names rather than attribute names for // certain attributes. Rather than sniffing, we do a quick feature // test the first time _createNode() runs to determine whether we // need to provide a workaround. testEl = doc.createElement('div'); testEl.setAttribute('class', 'a'); CUSTOM_ATTRS = testEl.className === 'a' ? {} : { 'for' : 'htmlFor', 'class': 'className' }; } for (attr in attrs) { if (attrs.hasOwnProperty(attr)) { node.setAttribute(CUSTOM_ATTRS[attr] || attr, attrs[attr]); } } return node; }, _finish: function () { var errors = this.errors.length ? this.errors : null, options = this.options, thisObj = options.context || this, data, i, len; if (this._state === 'done') { return; } this._state = 'done'; for (i = 0, len = this._callbacks.length; i < len; ++i) { this._callbacks[i].call(thisObj, errors, this); } data = this._getEventData(); if (errors) { if (options.onTimeout && errors[errors.length - 1].error === 'Timeout') { options.onTimeout.call(thisObj, data); } if (options.onFailure) { options.onFailure.call(thisObj, data); } } else if (options.onSuccess) { options.onSuccess.call(thisObj, data); } if (options.onEnd) { options.onEnd.call(thisObj, data); } if (options._onFinish) { options._onFinish(); } }, _getEventData: function (req) { if (req) { // This merge is necessary for backcompat. I hate it. return Y.merge(this, { abort : this.abort, // have to copy these because the prototype isn't preserved purge : this.purge, request: req, url : req.url, win : req.win }); } else { return this; } }, _getInsertBefore: function (req) { var doc = req.doc, el = req.insertBefore, cache, docStamp; if (el) { return typeof el === 'string' ? doc.getElementById(el) : el; } cache = Get._insertCache; docStamp = Y.stamp(doc); if ((el = cache[docStamp])) { // assignment return el; } // Inserting before a <base> tag apparently works around an IE bug // (according to a comment from pre-3.5.0 Y.Get), but I'm not sure what // bug that is, exactly. Better safe than sorry? if ((el = doc.getElementsByTagName('base')[0])) { // assignment return (cache[docStamp] = el); } // Look for a <head> element. el = doc.head || doc.getElementsByTagName('head')[0]; if (el) { // Create a marker node at the end of <head> to use as an insertion // point. Inserting before this node will ensure that all our CSS // gets inserted in the correct order, to maintain style precedence. el.appendChild(doc.createTextNode('')); return (cache[docStamp] = el.lastChild); } // If all else fails, just insert before the first script node on the // page, which is virtually guaranteed to exist. return (cache[docStamp] = doc.getElementsByTagName('script')[0]); }, _insert: function (req) { var env = Get._env, insertBefore = this._getInsertBefore(req), isScript = req.type === 'js', node = req.node, self = this, ua = Y.UA, cssTimeout, nodeType; if (!node) { if (isScript) { nodeType = 'script'; } else if (!env.cssLoad && ua.gecko) { nodeType = 'style'; } else { nodeType = 'link'; } node = req.node = this._createNode(nodeType, req.attributes, req.doc); } function onError() { self._progress('Failed to load ' + req.url, req); } function onLoad() { if (cssTimeout) { clearTimeout(cssTimeout); } self._progress(null, req); } // Deal with script asynchronicity. if (isScript) { node.setAttribute('src', req.url); if (req.async) { // Explicitly indicate that we want the browser to execute this // script asynchronously. This is necessary for older browsers // like Firefox <4. node.async = true; } else { if (env.async) { // This browser treats injected scripts as async by default // (standard HTML5 behavior) but asynchronous loading isn't // desired, so tell the browser not to mark this script as // async. node.async = false; } // If this browser doesn't preserve script execution order based // on insertion order, we'll need to avoid inserting other // scripts until this one finishes loading. if (!env.preservesScriptOrder) { this._pending = req; } } } else { if (!env.cssLoad && ua.gecko) { // In Firefox <9, we can import the requested URL into a <style> // node and poll for the existence of node.sheet.cssRules. This // gives us a reliable way to determine CSS load completion that // also works for cross-domain stylesheets. // // Props to Zach Leatherman for calling my attention to this // technique. node.innerHTML = (req.attributes.charset ? '@charset "' + req.attributes.charset + '";' : '') + '@import "' + req.url + '";'; } else { node.setAttribute('href', req.url); } } // Inject the node. if (isScript && ua.ie && (ua.ie < 9 || (document.documentMode && document.documentMode < 9))) { // Script on IE < 9, and IE 9+ when in IE 8 or older modes, including quirks mode. node.onreadystatechange = function () { if (/loaded|complete/.test(node.readyState)) { node.onreadystatechange = null; onLoad(); } }; } else if (!isScript && !env.cssLoad) { // CSS on Firefox <9 or WebKit. this._poll(req); } else { // Script or CSS on everything else. Using DOM 0 events because that // evens the playing field with older IEs. if (ua.ie >= 10) { // We currently need to introduce a timeout for IE10, since it // calls onerror/onload synchronously for 304s - messing up existing // program flow. // Remove this block if the following bug gets fixed by GA /*jshint maxlen: 1500 */ // https://connect.microsoft.com/IE/feedback/details/763871/dynamically-loaded-scripts-with-304s-responses-interrupt-the-currently-executing-js-thread-onload node.onerror = function() { setTimeout(onError, 0); }; node.onload = function() { setTimeout(onLoad, 0); }; } else { node.onerror = onError; node.onload = onLoad; } // If this browser doesn't fire an event when CSS fails to load, // fail after a timeout to avoid blocking the transaction queue. if (!env.cssFail && !isScript) { cssTimeout = setTimeout(onError, req.timeout || 3000); } } this.nodes.push(node); insertBefore.parentNode.insertBefore(node, insertBefore); }, _next: function () { if (this._pending) { return; } // If there are requests in the queue, insert the next queued request. // Otherwise, if we're waiting on already-inserted requests to finish, // wait longer. If there are no queued requests and we're not waiting // for anything to load, then we're done! if (this._queue.length) { this._insert(this._queue.shift()); } else if (!this._reqsWaiting) { this._finish(); } }, _poll: function (newReq) { var self = this, pendingCSS = self._pendingCSS, isWebKit = Y.UA.webkit, i, hasRules, j, nodeHref, req, sheets; if (newReq) { pendingCSS || (pendingCSS = self._pendingCSS = []); pendingCSS.push(newReq); if (self._pollTimer) { // A poll timeout is already pending, so no need to create a // new one. return; } } self._pollTimer = null; // Note: in both the WebKit and Gecko hacks below, a CSS URL that 404s // will still be treated as a success. There's no good workaround for // this. for (i = 0; i < pendingCSS.length; ++i) { req = pendingCSS[i]; if (isWebKit) { // Look for a stylesheet matching the pending URL. sheets = req.doc.styleSheets; j = sheets.length; nodeHref = req.node.href; while (--j >= 0) { if (sheets[j].href === nodeHref) { pendingCSS.splice(i, 1); i -= 1; self._progress(null, req); break; } } } else { // Many thanks to Zach Leatherman for calling my attention to // the @import-based cross-domain technique used here, and to // Oleg Slobodskoi for an earlier same-domain implementation. // // See Zach's blog for more details: // http://www.zachleat.com/web/2010/07/29/load-css-dynamically/ try { // We don't really need to store this value since we never // use it again, but if we don't store it, Closure Compiler // assumes the code is useless and removes it. hasRules = !!req.node.sheet.cssRules; // If we get here, the stylesheet has loaded. pendingCSS.splice(i, 1); i -= 1; self._progress(null, req); } catch (ex) { // An exception means the stylesheet is still loading. } } } if (pendingCSS.length) { self._pollTimer = setTimeout(function () { self._poll.call(self); }, self.options.pollInterval); } }, _progress: function (err, req) { var options = this.options; if (err) { req.error = err; this.errors.push({ error : err, request: req }); Y.log(err, 'error', 'get'); } req.node._yuiget_finished = req.finished = true; if (options.onProgress) { options.onProgress.call(options.context || this, this._getEventData(req)); } if (req.autopurge) { // Pre-3.5.0 Get always excludes the most recent node from an // autopurge. I find this odd, but I'm keeping that behavior for // the sake of backcompat. Get._autoPurge(this.options.purgethreshold); Get._purgeNodes.push(req.node); } if (this._pending === req) { this._pending = null; } this._reqsWaiting -= 1; this._next(); } }; }, 'patched-v3.16.0', {"requires": ["yui-base"]}); YUI.add('features', function (Y, NAME) { var feature_tests = {}; /** Contains the core of YUI's feature test architecture. @module features */ /** * Feature detection * @class Features * @static */ Y.mix(Y.namespace('Features'), { /** * Object hash of all registered feature tests * @property tests * @type Object */ tests: feature_tests, /** * Add a test to the system * * ``` * Y.Features.add("load", "1", {}); * ``` * * @method add * @param {String} cat The category, right now only 'load' is supported * @param {String} name The number sequence of the test, how it's reported in the URL or config: 1, 2, 3 * @param {Object} o Object containing test properties * @param {String} o.name The name of the test * @param {Function} o.test The test function to execute, the only argument to the function is the `Y` instance * @param {String} o.trigger The module that triggers this test. */ add: function(cat, name, o) { feature_tests[cat] = feature_tests[cat] || {}; feature_tests[cat][name] = o; }, /** * Execute all tests of a given category and return the serialized results * * ``` * caps=1:1;2:1;3:0 * ``` * @method all * @param {String} cat The category to execute * @param {Array} args The arguments to pass to the test function * @return {String} A semi-colon separated string of tests and their success/failure: 1:1;2:1;3:0 */ all: function(cat, args) { var cat_o = feature_tests[cat], // results = {}; result = []; if (cat_o) { Y.Object.each(cat_o, function(v, k) { result.push(k + ':' + (Y.Features.test(cat, k, args) ? 1 : 0)); }); } return (result.length) ? result.join(';') : ''; }, /** * Run a sepecific test and return a Boolean response. * * ``` * Y.Features.test("load", "1"); * ``` * * @method test * @param {String} cat The category of the test to run * @param {String} name The name of the test to run * @param {Array} args The arguments to pass to the test function * @return {Boolean} True or false if the test passed/failed. */ test: function(cat, name, args) { args = args || []; var result, ua, test, cat_o = feature_tests[cat], feature = cat_o && cat_o[name]; if (!feature) { Y.log('Feature test ' + cat + ', ' + name + ' not found'); } else { result = feature.result; if (Y.Lang.isUndefined(result)) { ua = feature.ua; if (ua) { result = (Y.UA[ua]); } test = feature.test; if (test && ((!ua) || result)) { result = test.apply(Y, args); } feature.result = result; } } return result; } }); // Y.Features.add("load", "1", {}); // Y.Features.test("load", "1"); // caps=1:1;2:0;3:1; /* This file is auto-generated by (yogi loader --yes --mix --start ../) */ /*jshint maxlen:900, eqeqeq: false */ var add = Y.Features.add; // app-transitions-native add('load', '0', { "name": "app-transitions-native", "test": function (Y) { var doc = Y.config.doc, node = doc ? doc.documentElement : null; if (node && node.style) { return ('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style); } return false; }, "trigger": "app-transitions" }); // autocomplete-list-keys add('load', '1', { "name": "autocomplete-list-keys", "test": function (Y) { // Only add keyboard support to autocomplete-list if this doesn't appear to // be an iOS or Android-based mobile device. // // There's currently no feasible way to actually detect whether a device has // a hardware keyboard, so this sniff will have to do. It can easily be // overridden by manually loading the autocomplete-list-keys module. // // Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari // doesn't fire the keyboard events used by AutoCompleteList, so there's // no point loading the -keys module even when a bluetooth keyboard may be // available. return !(Y.UA.ios || Y.UA.android); }, "trigger": "autocomplete-list" }); // dd-gestures add('load', '2', { "name": "dd-gestures", "trigger": "dd-drag", "ua": "touchEnabled" }); // dom-style-ie add('load', '3', { "name": "dom-style-ie", "test": function (Y) { var testFeature = Y.Features.test, addFeature = Y.Features.add, WINDOW = Y.config.win, DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', ret = false; addFeature('style', 'computedStyle', { test: function() { return WINDOW && 'getComputedStyle' in WINDOW; } }); addFeature('style', 'opacity', { test: function() { return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style; } }); ret = (!testFeature('style', 'opacity') && !testFeature('style', 'computedStyle')); return ret; }, "trigger": "dom-style" }); // editor-para-ie add('load', '4', { "name": "editor-para-ie", "trigger": "editor-para", "ua": "ie", "when": "instead" }); // event-base-ie add('load', '5', { "name": "event-base-ie", "test": function(Y) { var imp = Y.config.doc && Y.config.doc.implementation; return (imp && (!imp.hasFeature('Events', '2.0'))); }, "trigger": "node-base" }); // graphics-canvas add('load', '6', { "name": "graphics-canvas", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-canvas-default add('load', '7', { "name": "graphics-canvas-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-svg add('load', '8', { "name": "graphics-svg", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // graphics-svg-default add('load', '9', { "name": "graphics-svg-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // graphics-vml add('load', '10', { "name": "graphics-vml", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // graphics-vml-default add('load', '11', { "name": "graphics-vml-default", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // history-hash-ie add('load', '12', { "name": "history-hash-ie", "test": function (Y) { var docMode = Y.config.doc && Y.config.doc.documentMode; return Y.UA.ie && (!('onhashchange' in Y.config.win) || !docMode || docMode < 8); }, "trigger": "history-hash" }); // io-nodejs add('load', '13', { "name": "io-nodejs", "trigger": "io-base", "ua": "nodejs" }); // json-parse-shim add('load', '14', { "name": "json-parse-shim", "test": function (Y) { var _JSON = Y.config.global.JSON, Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON, nativeSupport = Y.config.useNativeJSONParse !== false && !!Native; function workingNative( k, v ) { return k === "ok" ? true : v; } // Double check basic functionality. This is mainly to catch early broken // implementations of the JSON API in Firefox 3.1 beta1 and beta2 if ( nativeSupport ) { try { nativeSupport = ( Native.parse( '{"ok":false}', workingNative ) ).ok; } catch ( e ) { nativeSupport = false; } } return !nativeSupport; }, "trigger": "json-parse" }); // json-stringify-shim add('load', '15', { "name": "json-stringify-shim", "test": function (Y) { var _JSON = Y.config.global.JSON, Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON, nativeSupport = Y.config.useNativeJSONStringify !== false && !!Native; // Double check basic native functionality. This is primarily to catch broken // early JSON API implementations in Firefox 3.1 beta1 and beta2. if ( nativeSupport ) { try { nativeSupport = ( '0' === Native.stringify(0) ); } catch ( e ) { nativeSupport = false; } } return !nativeSupport; }, "trigger": "json-stringify" }); // scrollview-base-ie add('load', '16', { "name": "scrollview-base-ie", "trigger": "scrollview-base", "ua": "ie" }); // selector-css2 add('load', '17', { "name": "selector-css2", "test": function (Y) { var DOCUMENT = Y.config.doc, ret = DOCUMENT && !('querySelectorAll' in DOCUMENT); return ret; }, "trigger": "selector" }); // transition-timer add('load', '18', { "name": "transition-timer", "test": function (Y) { var DOCUMENT = Y.config.doc, node = (DOCUMENT) ? DOCUMENT.documentElement: null, ret = true; if (node && node.style) { ret = !('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style); } return ret; }, "trigger": "transition" }); // widget-base-ie add('load', '19', { "name": "widget-base-ie", "trigger": "widget-base", "ua": "ie" }); // yql-jsonp add('load', '20', { "name": "yql-jsonp", "test": function (Y) { /* Only load the JSONP module when not in nodejs or winjs TODO Make the winjs module a CORS module */ return (!Y.UA.nodejs && !Y.UA.winjs); }, "trigger": "yql" }); // yql-nodejs add('load', '21', { "name": "yql-nodejs", "trigger": "yql", "ua": "nodejs" }); // yql-winjs add('load', '22', { "name": "yql-winjs", "trigger": "yql", "ua": "winjs" }); }, 'patched-v3.16.0', {"requires": ["yui-base"]}); YUI.add('intl-base', function (Y, NAME) { /** * The Intl utility provides a central location for managing sets of * localized resources (strings and formatting patterns). * * @class Intl * @uses EventTarget * @static */ var SPLIT_REGEX = /[, ]/; Y.mix(Y.namespace('Intl'), { /** * Returns the language among those available that * best matches the preferred language list, using the Lookup * algorithm of BCP 47. * If none of the available languages meets the user's preferences, * then "" is returned. * Extended language ranges are not supported. * * @method lookupBestLang * @param {String[] | String} preferredLanguages The list of preferred * languages in descending preference order, represented as BCP 47 * language tags. A string array or a comma-separated list. * @param {String[]} availableLanguages The list of languages * that the application supports, represented as BCP 47 language * tags. * * @return {String} The available language that best matches the * preferred language list, or "". * @since 3.1.0 */ lookupBestLang: function(preferredLanguages, availableLanguages) { var i, language, result, index; // check whether the list of available languages contains language; // if so return it function scan(language) { var i; for (i = 0; i < availableLanguages.length; i += 1) { if (language.toLowerCase() === availableLanguages[i].toLowerCase()) { return availableLanguages[i]; } } } if (Y.Lang.isString(preferredLanguages)) { preferredLanguages = preferredLanguages.split(SPLIT_REGEX); } for (i = 0; i < preferredLanguages.length; i += 1) { language = preferredLanguages[i]; if (!language || language === '*') { continue; } // check the fallback sequence for one language while (language.length > 0) { result = scan(language); if (result) { return result; } else { index = language.lastIndexOf('-'); if (index >= 0) { language = language.substring(0, index); // one-character subtags get cut along with the // following subtag if (index >= 2 && language.charAt(index - 2) === '-') { language = language.substring(0, index - 2); } } else { // nothing available for this language break; } } } } return ''; } }); }, 'patched-v3.16.0', {"requires": ["yui-base"]}); YUI.add('yui-log', function (Y, NAME) { /** * Provides console log capability and exposes a custom event for * console implementations. This module is a `core` YUI module, * <a href="../classes/YUI.html#method_log">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-log */ var INSTANCE = Y, LOGEVENT = 'yui:log', UNDEFINED = 'undefined', LEVELS = { debug: 1, info: 2, warn: 4, error: 8 }; /** * If the 'debug' config is true, a 'yui:log' event will be * dispatched, which the Console widget and anything else * can consume. If the 'useBrowserConsole' config is true, it will * write to the browser console if available. YUI-specific log * messages will only be present in the -debug versions of the * JS files. The build system is supposed to remove log statements * from the raw and minified versions of the files. * * @method log * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", "debug". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.log = function(msg, cat, src, silent) { var bail, excl, incl, m, f, minlevel, Y = INSTANCE, c = Y.config, publisher = (Y.fire) ? Y : YUI.Env.globalEvents; // suppress log message if the config is off or the event stack // or the event call stack contains a consumer of the yui:log event if (c.debug) { // apply source filters src = src || ""; if (typeof src !== "undefined") { excl = c.logExclude; incl = c.logInclude; if (incl && !(src in incl)) { bail = 1; } else if (incl && (src in incl)) { bail = !incl[src]; } else if (excl && (src in excl)) { bail = excl[src]; } // Set a default category of info if the category was not defined. if ((typeof cat === 'undefined')) { cat = 'info'; } // Determine the current minlevel as defined in configuration Y.config.logLevel = Y.config.logLevel || 'debug'; minlevel = LEVELS[Y.config.logLevel.toLowerCase()]; if (cat in LEVELS && LEVELS[cat] < minlevel) { // Skip this message if the we don't meet the defined minlevel bail = 1; } } if (!bail) { if (c.useBrowserConsole) { m = (src) ? src + ': ' + msg : msg; if (Y.Lang.isFunction(c.logFn)) { c.logFn.call(Y, msg, cat, src); } else if (typeof console !== UNDEFINED && console.log) { f = (cat && console[cat] && (cat in LEVELS)) ? cat : 'log'; console[f](m); } else if (typeof opera !== UNDEFINED) { opera.postError(m); } } if (publisher && !silent) { if (publisher === Y && (!publisher.getEvent(LOGEVENT))) { publisher.publish(LOGEVENT, { broadcast: 2 }); } publisher.fire(LOGEVENT, { msg: msg, cat: cat, src: src }); } } } return Y; }; /** * Write a system message. This message will be preserved in the * minified and raw versions of the YUI files, unlike log statements. * @method message * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", "debug". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.message = function() { return INSTANCE.log.apply(INSTANCE, arguments); }; }, 'patched-v3.16.0', {"requires": ["yui-base"]}); YUI.add('yui-later', function (Y, NAME) { /** * Provides a setTimeout/setInterval wrapper. This module is a `core` YUI module, * <a href="../classes/YUI.html#method_later">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-later */ var NO_ARGS = []; /** * Executes the supplied function in the context of the supplied * object 'when' milliseconds later. Executes the function a * single time unless periodic is set to true. * @for YUI * @method later * @param when {Number} the number of milliseconds to wait until the fn * is executed. * @param o the context object. * @param fn {Function|String} the function to execute or the name of * the method in the 'o' object to execute. * @param data [Array] data that is provided to the function. This * accepts either a single item or an array. If an array is provided, * the function is executed with one parameter for each array item. * If you need to pass a single array parameter, it needs to be wrapped * in an array [myarray]. * * Note: native methods in IE may not have the call and apply methods. * In this case, it will work, but you are limited to four arguments. * * @param periodic {boolean} if true, executes continuously at supplied * interval until canceled. * @return {object} a timer object. Call the cancel() method on this * object to stop the timer. */ Y.later = function(when, o, fn, data, periodic) { when = when || 0; data = (!Y.Lang.isUndefined(data)) ? Y.Array(data) : NO_ARGS; o = o || Y.config.win || Y; var cancelled = false, method = (o && Y.Lang.isString(fn)) ? o[fn] : fn, wrapper = function() { // IE 8- may execute a setInterval callback one last time // after clearInterval was called, so in order to preserve // the cancel() === no more runny-run, we have to jump through // an extra hoop. if (!cancelled) { if (!method.apply) { method(data[0], data[1], data[2], data[3]); } else { method.apply(o, data || NO_ARGS); } } }, id = (periodic) ? setInterval(wrapper, when) : setTimeout(wrapper, when); return { id: id, interval: periodic, cancel: function() { cancelled = true; if (this.interval) { clearInterval(id); } else { clearTimeout(id); } } }; }; Y.Lang.later = Y.later; }, 'patched-v3.16.0', {"requires": ["yui-base"]}); YUI.add('yui', function (Y, NAME) {}, 'patched-v3.16.0', {"use": ["get", "features", "intl-base", "yui-log", "yui-later"]});
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var PushData = new Schema({ user_id:{type:String, required:true}, token:{type:String, require:true}, timestamp:{type:Date, default:Date.now} }) var SMS = new Schema({ message:{type:String, required:true}, to:{type:String,required:true}, from:{type:String, default:'default'}, message_id:{type:String,default:''}, timestamp:{type:Date, default:Date.now}, sent:{type:Boolean,default:false} }) var Email = new Schema({ text:{type:String, required:true}, headers:{type:String}, to:{type:String,required:true}, from:{type:String, required:true}, email_id:{type:String,default:''}, timestamp:{type:Date, default:Date.now}, sent:{type:Boolean,default:false}, user_id:{type:String} }) var EmailQueue = new Schema({ content:{type:Object, required:true}, recipients:{type:Object, required:true}, timestamp:{type:Date, default:Date.now}, sent:{type:Boolean, default:false} }) var PushNotification = new Schema({ payload:{type:Object,required:true}, timestamp:{type:Date, default:Date.now}, sent:{type:Boolean, default:false}, sent_by:{type:String,required:true}, to:{type:Array, required:true}, response:{type:Object} }) module.exports = { SMS:mongoose.model('SMS',SMS), Email:mongoose.model('Email',Email), EmailQueue:mongoose.model('EmailQueue',EmailQueue), PushData:mongoose.model('PushData',PushData), PushNotification:mongoose.model('PushNotification',PushNotification), }
import React from 'react' import {connect} from 'react-redux' import 'semantic-ui-css/semantic.min.css' import Navbar from './NavigationBar/NavigationBar' import Sidebar from './Sidebar/Sidebar' import TradeArea from './TradeArea/TradeArea' const App = () => ( <div className='container flex-columns'> <Navbar /> <div className='flex-row container'> <Sidebar /> <div className='flex-child-1'> <TradeArea /> </div> </div> </div> ) function mapStateToProps (state) { return {...state} } export default connect(mapStateToProps)(App)
/** * @author dforrer / https://github.com/dforrer * Developed as part of a project at University of Applied Sciences and Arts Northwestern Switzerland (www.fhnw.ch) */ /** * @param scene containing children to import * @constructor */ export var SetSceneCommand = function ( scene ) { Command.call( this ); this.type = 'SetSceneCommand'; this.name = 'Set Scene'; this.cmdArray = []; if ( scene !== undefined ) { this.cmdArray.push( new SetUuidCommand( this.editor.scene, scene.uuid ) ); this.cmdArray.push( new SetValueCommand( this.editor.scene, 'name', scene.name ) ); this.cmdArray.push( new SetValueCommand( this.editor.scene, 'userData', JSON.parse( JSON.stringify( scene.userData ) ) ) ); while ( scene.children.length > 0 ) { var child = scene.children.pop(); this.cmdArray.push( new AddObjectCommand( child ) ); } } }; SetSceneCommand.prototype = { execute: function () { this.editor.signals.sceneGraphChanged.active = false; for ( var i = 0; i < this.cmdArray.length; i ++ ) { this.cmdArray[ i ].execute(); } this.editor.signals.sceneGraphChanged.active = true; this.editor.signals.sceneGraphChanged.dispatch(); }, undo: function () { this.editor.signals.sceneGraphChanged.active = false; for ( var i = this.cmdArray.length - 1; i >= 0; i -- ) { this.cmdArray[ i ].undo(); } this.editor.signals.sceneGraphChanged.active = true; this.editor.signals.sceneGraphChanged.dispatch(); }, toJSON: function () { var output = Command.prototype.toJSON.call( this ); var cmds = []; for ( var i = 0; i < this.cmdArray.length; i ++ ) { cmds.push( this.cmdArray[ i ].toJSON() ); } output.cmds = cmds; return output; }, fromJSON: function ( json ) { Command.prototype.fromJSON.call( this, json ); var cmds = json.cmds; for ( var i = 0; i < cmds.length; i ++ ) { var cmd = new window[ cmds[ i ].type ](); // creates a new object of type "json.type" cmd.fromJSON( cmds[ i ] ); this.cmdArray.push( cmd ); } } };
/* jshint node: true */ 'use strict'; var csso = require('broccoli-csso'); module.exports = { name: 'untitled-ui', postprocessTree: function(type, tree) { return type === 'css' ? csso(tree) : tree; }, isDevelopingAddon: function() { return true; } };
import * as React from 'react'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import { prepareMarkdown } from 'docs/src/modules/utils/parseMarkdown'; const pageFilename = 'components/tabs'; const requireDemo = require.context('docs/src/pages/components/tabs', false, /\.(js|tsx)$/); const requireRaw = require.context( '!raw-loader!../../src/pages/components/tabs', false, /\.(js|md|tsx)$/, ); export default function Page({ demos, docs }) { return <MarkdownDocs demos={demos} docs={docs} requireDemo={requireDemo} />; } Page.getInitialProps = () => { const { demos, docs } = prepareMarkdown({ pageFilename, requireRaw }); return { demos, docs }; };
module.exports = {"main":{"js":"/main.js?b056c25769a38d0d8fdc"}};
(function() { var checkVersion = Dagaz.Model.checkVersion; Dagaz.Model.checkVersion = function(design, name, value) { if (name != "paper-go-extension") { checkVersion(design, name, value); } } if (!_.isUndefined(Dagaz.Controller.addSound)) { Dagaz.Controller.addSound(0, "../sounds/step.ogg"); } var expand = function(design, board, player, group, dame) { for (var i = 0; i < group.length; i++) { var pos = group[i]; _.each(design.allDirections(), function(dir) { var p = design.navigate(player, pos, dir); if (p !== null) { var piece = board.getPiece(p); if (piece !== null) { if (piece.type == 0) { if ((piece.player == player) && (_.indexOf(group, p) < 0)) { group.push(p); } } } else { if (_.indexOf(dame, p) < 0) dame.push(p); } } }); } } var capture = function(move, board, group) { _.each(group, function(pos) { var piece = board.getPiece(pos); if (piece !== null) { piece = piece.promote(1); move.movePiece(pos, pos, piece); } }); } var change = function(move, board, group, dame) { _.each(group, function(pos) { var piece = board.getPiece(pos); if (piece !== null) { piece = piece.setValue(0, dame); move.movePiece(pos, pos, piece); } }); } var CheckInvariants = Dagaz.Model.CheckInvariants; Dagaz.Model.CheckInvariants = function(board) { var design = Dagaz.Model.design; _.each(board.moves, function(move) { if ((move.actions.length == 1) && (move.actions[0][1] !== null) && (move.actions[0][2] !== null)) { var pos = move.actions[0][1][0]; var captured = []; var group = []; var enemies = []; var dame = [ pos ]; _.each(design.allDirections(), function(dir) { var p = design.navigate(board.player, pos, dir); if ((p !== null) && (_.indexOf(enemies, p) < 0)) { var piece = board.getPiece(p); if (piece !== null) { if (piece.type == 0) { if (piece.getValue(0) === null) { move.failed = true; return; } var value = +piece.getValue(0); if (piece.player == board.player) { group.push(p); } else { if (value <= 1) { captured.push(p); expand(design, board, piece.player, captured, []); _.each(captured, function(q) { enemies.push(q); }); } else { var g = [ p ]; expand(design, board, piece.player, g, []); _.each(g, function(q) { enemies.push(q); }); change(move, board, g, value - 1); } } } } else { dame.push(p); } } }); expand(design, board, board.player, group, dame); if (captured.length > 0) { capture(move, board, captured); var friends = []; _.each(captured, function(e) { _.each(design.allDirections(), function(dir) { var p = design.navigate(board.player, e, dir); if ((p !== null) && (_.indexOf(group, p) < 0) && (_.indexOf(friends, p) < 0)) { var g = [ p ]; var d = []; expand(design, board, board.player, g, d); _.each(g, function(q) { friends.push(q); var piece = board.getPiece(q); if ((piece !== null) && (piece.player == board.player)) { piece = piece.setValue(0, d.length); move.movePiece(q, q, piece); } }); } }); }); } else { if (dame.length <= 1) { move.failed = true; return; } } change(move, board, group, dame.length - 1); var piece = move.actions[0][2][0].setValue(0, dame.length - 1); move.actions[0][2] = [ piece ]; } }); CheckInvariants(board); } })();
/** * @license Angular v4.4.4 * (c) 2010-2017 Google, Inc. https://angular.io/ * License: MIT */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/animations')) : typeof define === 'function' && define.amd ? define(['exports', '@angular/animations'], factory) : (factory((global.ng = global.ng || {}, global.ng.animations = global.ng.animations || {}, global.ng.animations.browser = global.ng.animations.browser || {}),global.ng.animations)); }(this, (function (exports,_angular_animations) { 'use strict'; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } /** * @license Angular v4.4.4 * (c) 2010-2017 Google, Inc. https://angular.io/ * License: MIT */ /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ function optimizeGroupPlayer(players) { switch (players.length) { case 0: return new _angular_animations.NoopAnimationPlayer(); case 1: return players[0]; default: return new _angular_animations.ɵAnimationGroupPlayer(players); } } function normalizeKeyframes(driver, normalizer, element, keyframes, preStyles, postStyles) { if (preStyles === void 0) { preStyles = {}; } if (postStyles === void 0) { postStyles = {}; } var errors = []; var normalizedKeyframes = []; var previousOffset = -1; var previousKeyframe = null; keyframes.forEach(function (kf) { var offset = kf['offset']; var isSameOffset = offset == previousOffset; var normalizedKeyframe = (isSameOffset && previousKeyframe) || {}; Object.keys(kf).forEach(function (prop) { var normalizedProp = prop; var normalizedValue = kf[prop]; if (prop !== 'offset') { normalizedProp = normalizer.normalizePropertyName(normalizedProp, errors); switch (normalizedValue) { case _angular_animations.ɵPRE_STYLE: normalizedValue = preStyles[prop]; break; case _angular_animations.AUTO_STYLE: normalizedValue = postStyles[prop]; break; default: normalizedValue = normalizer.normalizeStyleValue(prop, normalizedProp, normalizedValue, errors); break; } } normalizedKeyframe[normalizedProp] = normalizedValue; }); if (!isSameOffset) { normalizedKeyframes.push(normalizedKeyframe); } previousKeyframe = normalizedKeyframe; previousOffset = offset; }); if (errors.length) { var LINE_START = '\n - '; throw new Error("Unable to animate due to the following errors:" + LINE_START + errors.join(LINE_START)); } return normalizedKeyframes; } function listenOnPlayer(player, eventName, event, callback) { switch (eventName) { case 'start': player.onStart(function () { return callback(event && copyAnimationEvent(event, 'start', player.totalTime)); }); break; case 'done': player.onDone(function () { return callback(event && copyAnimationEvent(event, 'done', player.totalTime)); }); break; case 'destroy': player.onDestroy(function () { return callback(event && copyAnimationEvent(event, 'destroy', player.totalTime)); }); break; } } function copyAnimationEvent(e, phaseName, totalTime) { var event = makeAnimationEvent(e.element, e.triggerName, e.fromState, e.toState, phaseName || e.phaseName, totalTime == undefined ? e.totalTime : totalTime); var data = e['_data']; if (data != null) { event['_data'] = data; } return event; } function makeAnimationEvent(element, triggerName, fromState, toState, phaseName, totalTime) { if (phaseName === void 0) { phaseName = ''; } if (totalTime === void 0) { totalTime = 0; } return { element: element, triggerName: triggerName, fromState: fromState, toState: toState, phaseName: phaseName, totalTime: totalTime }; } function getOrSetAsInMap(map, key, defaultValue) { var value; if (map instanceof Map) { value = map.get(key); if (!value) { map.set(key, value = defaultValue); } } else { value = map[key]; if (!value) { value = map[key] = defaultValue; } } return value; } function parseTimelineCommand(command) { var separatorPos = command.indexOf(':'); var id = command.substring(1, separatorPos); var action = command.substr(separatorPos + 1); return [id, action]; } var _contains = function (elm1, elm2) { return false; }; var _matches = function (element, selector) { return false; }; var _query = function (element, selector, multi) { return []; }; if (typeof Element != 'undefined') { // this is well supported in all browsers _contains = function (elm1, elm2) { return elm1.contains(elm2); }; if (Element.prototype.matches) { _matches = function (element, selector) { return element.matches(selector); }; } else { var proto = Element.prototype; var fn_1 = proto.matchesSelector || proto.mozMatchesSelector || proto.msMatchesSelector || proto.oMatchesSelector || proto.webkitMatchesSelector; if (fn_1) { _matches = function (element, selector) { return fn_1.apply(element, [selector]); }; } } _query = function (element, selector, multi) { var results = []; if (multi) { results.push.apply(results, element.querySelectorAll(selector)); } else { var elm = element.querySelector(selector); if (elm) { results.push(elm); } } return results; }; } var matchesElement = _matches; var containsElement = _contains; var invokeQuery = _query; /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @experimental */ var NoopAnimationDriver = (function () { function NoopAnimationDriver() { } NoopAnimationDriver.prototype.matchesElement = function (element, selector) { return matchesElement(element, selector); }; NoopAnimationDriver.prototype.containsElement = function (elm1, elm2) { return containsElement(elm1, elm2); }; NoopAnimationDriver.prototype.query = function (element, selector, multi) { return invokeQuery(element, selector, multi); }; NoopAnimationDriver.prototype.computeStyle = function (element, prop, defaultValue) { return defaultValue || ''; }; NoopAnimationDriver.prototype.animate = function (element, keyframes, duration, delay, easing, previousPlayers) { if (previousPlayers === void 0) { previousPlayers = []; } return new _angular_animations.NoopAnimationPlayer(); }; return NoopAnimationDriver; }()); /** * @experimental */ var AnimationDriver = (function () { function AnimationDriver() { } return AnimationDriver; }()); AnimationDriver.NOOP = new NoopAnimationDriver(); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var ONE_SECOND = 1000; var SUBSTITUTION_EXPR_START = '{{'; var SUBSTITUTION_EXPR_END = '}}'; var ENTER_CLASSNAME = 'ng-enter'; var LEAVE_CLASSNAME = 'ng-leave'; var ENTER_SELECTOR = '.ng-enter'; var LEAVE_SELECTOR = '.ng-leave'; var NG_TRIGGER_CLASSNAME = 'ng-trigger'; var NG_TRIGGER_SELECTOR = '.ng-trigger'; var NG_ANIMATING_CLASSNAME = 'ng-animating'; var NG_ANIMATING_SELECTOR = '.ng-animating'; function resolveTimingValue(value) { if (typeof value == 'number') return value; var matches = value.match(/^(-?[\.\d]+)(m?s)/); if (!matches || matches.length < 2) return 0; return _convertTimeValueToMS(parseFloat(matches[1]), matches[2]); } function _convertTimeValueToMS(value, unit) { switch (unit) { case 's': return value * ONE_SECOND; default: return value; } } function resolveTiming(timings, errors, allowNegativeValues) { return timings.hasOwnProperty('duration') ? timings : parseTimeExpression(timings, errors, allowNegativeValues); } function parseTimeExpression(exp, errors, allowNegativeValues) { var regex = /^(-?[\.\d]+)(m?s)(?:\s+(-?[\.\d]+)(m?s))?(?:\s+([-a-z]+(?:\(.+?\))?))?$/i; var duration; var delay = 0; var easing = ''; if (typeof exp === 'string') { var matches = exp.match(regex); if (matches === null) { errors.push("The provided timing value \"" + exp + "\" is invalid."); return { duration: 0, delay: 0, easing: '' }; } duration = _convertTimeValueToMS(parseFloat(matches[1]), matches[2]); var delayMatch = matches[3]; if (delayMatch != null) { delay = _convertTimeValueToMS(Math.floor(parseFloat(delayMatch)), matches[4]); } var easingVal = matches[5]; if (easingVal) { easing = easingVal; } } else { duration = exp; } if (!allowNegativeValues) { var containsErrors = false; var startIndex = errors.length; if (duration < 0) { errors.push("Duration values below 0 are not allowed for this animation step."); containsErrors = true; } if (delay < 0) { errors.push("Delay values below 0 are not allowed for this animation step."); containsErrors = true; } if (containsErrors) { errors.splice(startIndex, 0, "The provided timing value \"" + exp + "\" is invalid."); } } return { duration: duration, delay: delay, easing: easing }; } function copyObj(obj, destination) { if (destination === void 0) { destination = {}; } Object.keys(obj).forEach(function (prop) { destination[prop] = obj[prop]; }); return destination; } function normalizeStyles(styles) { var normalizedStyles = {}; if (Array.isArray(styles)) { styles.forEach(function (data) { return copyStyles(data, false, normalizedStyles); }); } else { copyStyles(styles, false, normalizedStyles); } return normalizedStyles; } function copyStyles(styles, readPrototype, destination) { if (destination === void 0) { destination = {}; } if (readPrototype) { // we make use of a for-in loop so that the // prototypically inherited properties are // revealed from the backFill map for (var prop in styles) { destination[prop] = styles[prop]; } } else { copyObj(styles, destination); } return destination; } function setStyles(element, styles) { if (element['style']) { Object.keys(styles).forEach(function (prop) { var camelProp = dashCaseToCamelCase(prop); element.style[camelProp] = styles[prop]; }); } } function eraseStyles(element, styles) { if (element['style']) { Object.keys(styles).forEach(function (prop) { var camelProp = dashCaseToCamelCase(prop); element.style[camelProp] = ''; }); } } function normalizeAnimationEntry(steps) { if (Array.isArray(steps)) { if (steps.length == 1) return steps[0]; return _angular_animations.sequence(steps); } return steps; } function validateStyleParams(value, options, errors) { var params = options.params || {}; var matches = extractStyleParams(value); if (matches.length) { matches.forEach(function (varName) { if (!params.hasOwnProperty(varName)) { errors.push("Unable to resolve the local animation param " + varName + " in the given list of values"); } }); } } var PARAM_REGEX = new RegExp(SUBSTITUTION_EXPR_START + "\\s*(.+?)\\s*" + SUBSTITUTION_EXPR_END, 'g'); function extractStyleParams(value) { var params = []; if (typeof value === 'string') { var val = value.toString(); var match = void 0; while (match = PARAM_REGEX.exec(val)) { params.push(match[1]); } PARAM_REGEX.lastIndex = 0; } return params; } function interpolateParams(value, params, errors) { var original = value.toString(); var str = original.replace(PARAM_REGEX, function (_, varName) { var localVal = params[varName]; // this means that the value was never overidden by the data passed in by the user if (!params.hasOwnProperty(varName)) { errors.push("Please provide a value for the animation param " + varName); localVal = ''; } return localVal.toString(); }); // we do this to assert that numeric values stay as they are return str == original ? value : str; } function iteratorToArray(iterator) { var arr = []; var item = iterator.next(); while (!item.done) { arr.push(item.value); item = iterator.next(); } return arr; } var DASH_CASE_REGEXP = /-+([a-z0-9])/g; function dashCaseToCamelCase(input) { return input.replace(DASH_CASE_REGEXP, function () { var m = []; for (var _i = 0; _i < arguments.length; _i++) { m[_i] = arguments[_i]; } return m[1].toUpperCase(); }); } function allowPreviousPlayerStylesMerge(duration, delay) { return duration === 0 || delay === 0; } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var EMPTY_ANIMATION_OPTIONS = {}; /** * @abstract */ var Ast = (function () { function Ast() { this.options = EMPTY_ANIMATION_OPTIONS; } /** * @abstract * @param {?} ast * @param {?} context * @return {?} */ Ast.prototype.visit = function (ast, context) { }; Object.defineProperty(Ast.prototype, "params", { /** * @return {?} */ get: function () { return this.options['params'] || null; }, enumerable: true, configurable: true }); return Ast; }()); var TriggerAst = (function (_super) { __extends(TriggerAst, _super); /** * @param {?} name * @param {?} states * @param {?} transitions */ function TriggerAst(name, states, transitions) { var _this = _super.call(this) || this; _this.name = name; _this.states = states; _this.transitions = transitions; _this.queryCount = 0; _this.depCount = 0; return _this; } /** * @param {?} visitor * @param {?} context * @return {?} */ TriggerAst.prototype.visit = function (visitor, context) { return visitor.visitTrigger(this, context); }; return TriggerAst; }(Ast)); var StateAst = (function (_super) { __extends(StateAst, _super); /** * @param {?} name * @param {?} style */ function StateAst(name, style$$1) { var _this = _super.call(this) || this; _this.name = name; _this.style = style$$1; return _this; } /** * @param {?} visitor * @param {?} context * @return {?} */ StateAst.prototype.visit = function (visitor, context) { return visitor.visitState(this, context); }; return StateAst; }(Ast)); var TransitionAst = (function (_super) { __extends(TransitionAst, _super); /** * @param {?} matchers * @param {?} animation */ function TransitionAst(matchers, animation) { var _this = _super.call(this) || this; _this.matchers = matchers; _this.animation = animation; _this.queryCount = 0; _this.depCount = 0; return _this; } /** * @param {?} visitor * @param {?} context * @return {?} */ TransitionAst.prototype.visit = function (visitor, context) { return visitor.visitTransition(this, context); }; return TransitionAst; }(Ast)); var SequenceAst = (function (_super) { __extends(SequenceAst, _super); /** * @param {?} steps */ function SequenceAst(steps) { var _this = _super.call(this) || this; _this.steps = steps; return _this; } /** * @param {?} visitor * @param {?} context * @return {?} */ SequenceAst.prototype.visit = function (visitor, context) { return visitor.visitSequence(this, context); }; return SequenceAst; }(Ast)); var GroupAst = (function (_super) { __extends(GroupAst, _super); /** * @param {?} steps */ function GroupAst(steps) { var _this = _super.call(this) || this; _this.steps = steps; return _this; } /** * @param {?} visitor * @param {?} context * @return {?} */ GroupAst.prototype.visit = function (visitor, context) { return visitor.visitGroup(this, context); }; return GroupAst; }(Ast)); var AnimateAst = (function (_super) { __extends(AnimateAst, _super); /** * @param {?} timings * @param {?} style */ function AnimateAst(timings, style$$1) { var _this = _super.call(this) || this; _this.timings = timings; _this.style = style$$1; return _this; } /** * @param {?} visitor * @param {?} context * @return {?} */ AnimateAst.prototype.visit = function (visitor, context) { return visitor.visitAnimate(this, context); }; return AnimateAst; }(Ast)); var StyleAst = (function (_super) { __extends(StyleAst, _super); /** * @param {?} styles * @param {?} easing * @param {?} offset */ function StyleAst(styles, easing, offset) { var _this = _super.call(this) || this; _this.styles = styles; _this.easing = easing; _this.offset = offset; _this.isEmptyStep = false; _this.containsDynamicStyles = false; return _this; } /** * @param {?} visitor * @param {?} context * @return {?} */ StyleAst.prototype.visit = function (visitor, context) { return visitor.visitStyle(this, context); }; return StyleAst; }(Ast)); var KeyframesAst = (function (_super) { __extends(KeyframesAst, _super); /** * @param {?} styles */ function KeyframesAst(styles) { var _this = _super.call(this) || this; _this.styles = styles; return _this; } /** * @param {?} visitor * @param {?} context * @return {?} */ KeyframesAst.prototype.visit = function (visitor, context) { return visitor.visitKeyframes(this, context); }; return KeyframesAst; }(Ast)); var ReferenceAst = (function (_super) { __extends(ReferenceAst, _super); /** * @param {?} animation */ function ReferenceAst(animation) { var _this = _super.call(this) || this; _this.animation = animation; return _this; } /** * @param {?} visitor * @param {?} context * @return {?} */ ReferenceAst.prototype.visit = function (visitor, context) { return visitor.visitReference(this, context); }; return ReferenceAst; }(Ast)); var AnimateChildAst = (function (_super) { __extends(AnimateChildAst, _super); function AnimateChildAst() { return _super.call(this) || this; } /** * @param {?} visitor * @param {?} context * @return {?} */ AnimateChildAst.prototype.visit = function (visitor, context) { return visitor.visitAnimateChild(this, context); }; return AnimateChildAst; }(Ast)); var AnimateRefAst = (function (_super) { __extends(AnimateRefAst, _super); /** * @param {?} animation */ function AnimateRefAst(animation) { var _this = _super.call(this) || this; _this.animation = animation; return _this; } /** * @param {?} visitor * @param {?} context * @return {?} */ AnimateRefAst.prototype.visit = function (visitor, context) { return visitor.visitAnimateRef(this, context); }; return AnimateRefAst; }(Ast)); var QueryAst = (function (_super) { __extends(QueryAst, _super); /** * @param {?} selector * @param {?} limit * @param {?} optional * @param {?} includeSelf * @param {?} animation */ function QueryAst(selector, limit, optional, includeSelf, animation) { var _this = _super.call(this) || this; _this.selector = selector; _this.limit = limit; _this.optional = optional; _this.includeSelf = includeSelf; _this.animation = animation; return _this; } /** * @param {?} visitor * @param {?} context * @return {?} */ QueryAst.prototype.visit = function (visitor, context) { return visitor.visitQuery(this, context); }; return QueryAst; }(Ast)); var StaggerAst = (function (_super) { __extends(StaggerAst, _super); /** * @param {?} timings * @param {?} animation */ function StaggerAst(timings, animation) { var _this = _super.call(this) || this; _this.timings = timings; _this.animation = animation; return _this; } /** * @param {?} visitor * @param {?} context * @return {?} */ StaggerAst.prototype.visit = function (visitor, context) { return visitor.visitStagger(this, context); }; return StaggerAst; }(Ast)); var TimingAst = (function (_super) { __extends(TimingAst, _super); /** * @param {?} duration * @param {?=} delay * @param {?=} easing */ function TimingAst(duration, delay, easing) { if (delay === void 0) { delay = 0; } if (easing === void 0) { easing = null; } var _this = _super.call(this) || this; _this.duration = duration; _this.delay = delay; _this.easing = easing; return _this; } /** * @param {?} visitor * @param {?} context * @return {?} */ TimingAst.prototype.visit = function (visitor, context) { return visitor.visitTiming(this, context); }; return TimingAst; }(Ast)); var DynamicTimingAst = (function (_super) { __extends(DynamicTimingAst, _super); /** * @param {?} value */ function DynamicTimingAst(value) { var _this = _super.call(this, 0, 0, '') || this; _this.value = value; return _this; } /** * @param {?} visitor * @param {?} context * @return {?} */ DynamicTimingAst.prototype.visit = function (visitor, context) { return visitor.visitTiming(this, context); }; return DynamicTimingAst; }(TimingAst)); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @param {?} visitor * @param {?} node * @param {?} context * @return {?} */ function visitAnimationNode(visitor, node, context) { switch (node.type) { case 7 /* Trigger */: return visitor.visitTrigger(/** @type {?} */ (node), context); case 0 /* State */: return visitor.visitState(/** @type {?} */ (node), context); case 1 /* Transition */: return visitor.visitTransition(/** @type {?} */ (node), context); case 2 /* Sequence */: return visitor.visitSequence(/** @type {?} */ (node), context); case 3 /* Group */: return visitor.visitGroup(/** @type {?} */ (node), context); case 4 /* Animate */: return visitor.visitAnimate(/** @type {?} */ (node), context); case 5 /* Keyframes */: return visitor.visitKeyframes(/** @type {?} */ (node), context); case 6 /* Style */: return visitor.visitStyle(/** @type {?} */ (node), context); case 8 /* Reference */: return visitor.visitReference(/** @type {?} */ (node), context); case 9 /* AnimateChild */: return visitor.visitAnimateChild(/** @type {?} */ (node), context); case 10 /* AnimateRef */: return visitor.visitAnimateRef(/** @type {?} */ (node), context); case 11 /* Query */: return visitor.visitQuery(/** @type {?} */ (node), context); case 12 /* Stagger */: return visitor.visitStagger(/** @type {?} */ (node), context); default: throw new Error("Unable to resolve animation metadata node #" + node.type); } } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var ANY_STATE = '*'; /** * @param {?} transitionValue * @param {?} errors * @return {?} */ function parseTransitionExpr(transitionValue, errors) { var /** @type {?} */ expressions = []; if (typeof transitionValue == 'string') { ((transitionValue)) .split(/\s*,\s*/) .forEach(function (str) { return parseInnerTransitionStr(str, expressions, errors); }); } else { expressions.push(/** @type {?} */ (transitionValue)); } return expressions; } /** * @param {?} eventStr * @param {?} expressions * @param {?} errors * @return {?} */ function parseInnerTransitionStr(eventStr, expressions, errors) { if (eventStr[0] == ':') { eventStr = parseAnimationAlias(eventStr, errors); } var /** @type {?} */ match = eventStr.match(/^(\*|[-\w]+)\s*(<?[=-]>)\s*(\*|[-\w]+)$/); if (match == null || match.length < 4) { errors.push("The provided transition expression \"" + eventStr + "\" is not supported"); return expressions; } var /** @type {?} */ fromState = match[1]; var /** @type {?} */ separator = match[2]; var /** @type {?} */ toState = match[3]; expressions.push(makeLambdaFromStates(fromState, toState)); var /** @type {?} */ isFullAnyStateExpr = fromState == ANY_STATE && toState == ANY_STATE; if (separator[0] == '<' && !isFullAnyStateExpr) { expressions.push(makeLambdaFromStates(toState, fromState)); } } /** * @param {?} alias * @param {?} errors * @return {?} */ function parseAnimationAlias(alias, errors) { switch (alias) { case ':enter': return 'void => *'; case ':leave': return '* => void'; default: errors.push("The transition alias value \"" + alias + "\" is not supported"); return '* => *'; } } /** * @param {?} lhs * @param {?} rhs * @return {?} */ function makeLambdaFromStates(lhs, rhs) { return function (fromState, toState) { var /** @type {?} */ lhsMatch = lhs == ANY_STATE || lhs == fromState; var /** @type {?} */ rhsMatch = rhs == ANY_STATE || rhs == toState; if (!lhsMatch && typeof fromState === 'boolean') { lhsMatch = fromState ? lhs === 'true' : lhs === 'false'; } if (!rhsMatch && typeof toState === 'boolean') { rhsMatch = toState ? rhs === 'true' : rhs === 'false'; } return lhsMatch && rhsMatch; }; } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var SELF_TOKEN = ':self'; var SELF_TOKEN_REGEX = new RegExp("s*" + SELF_TOKEN + "s*,?", 'g'); /** * @param {?} metadata * @param {?} errors * @return {?} */ function buildAnimationAst(metadata, errors) { return new AnimationAstBuilderVisitor().build(metadata, errors); } var LEAVE_TOKEN = ':leave'; var LEAVE_TOKEN_REGEX = new RegExp(LEAVE_TOKEN, 'g'); var ENTER_TOKEN = ':enter'; var ENTER_TOKEN_REGEX = new RegExp(ENTER_TOKEN, 'g'); var ROOT_SELECTOR = ''; var AnimationAstBuilderVisitor = (function () { function AnimationAstBuilderVisitor() { } /** * @param {?} metadata * @param {?} errors * @return {?} */ AnimationAstBuilderVisitor.prototype.build = function (metadata, errors) { var /** @type {?} */ context = new AnimationAstBuilderContext(errors); this._resetContextStyleTimingState(context); return (visitAnimationNode(this, normalizeAnimationEntry(metadata), context)); }; /** * @param {?} context * @return {?} */ AnimationAstBuilderVisitor.prototype._resetContextStyleTimingState = function (context) { context.currentQuerySelector = ROOT_SELECTOR; context.collectedStyles = {}; context.collectedStyles[ROOT_SELECTOR] = {}; context.currentTime = 0; }; /** * @param {?} metadata * @param {?} context * @return {?} */ AnimationAstBuilderVisitor.prototype.visitTrigger = function (metadata, context) { var _this = this; var /** @type {?} */ queryCount = context.queryCount = 0; var /** @type {?} */ depCount = context.depCount = 0; var /** @type {?} */ states = []; var /** @type {?} */ transitions = []; metadata.definitions.forEach(function (def) { _this._resetContextStyleTimingState(context); if (def.type == 0 /* State */) { var /** @type {?} */ stateDef_1 = (def); var /** @type {?} */ name = stateDef_1.name; name.split(/\s*,\s*/).forEach(function (n) { stateDef_1.name = n; states.push(_this.visitState(stateDef_1, context)); }); stateDef_1.name = name; } else if (def.type == 1 /* Transition */) { var /** @type {?} */ transition = _this.visitTransition(/** @type {?} */ (def), context); queryCount += transition.queryCount; depCount += transition.depCount; transitions.push(transition); } else { context.errors.push('only state() and transition() definitions can sit inside of a trigger()'); } }); var /** @type {?} */ ast = new TriggerAst(metadata.name, states, transitions); ast.options = normalizeAnimationOptions(metadata.options); ast.queryCount = queryCount; ast.depCount = depCount; return ast; }; /** * @param {?} metadata * @param {?} context * @return {?} */ AnimationAstBuilderVisitor.prototype.visitState = function (metadata, context) { var /** @type {?} */ styleAst = this.visitStyle(metadata.styles, context); var /** @type {?} */ astParams = (metadata.options && metadata.options.params) || null; if (styleAst.containsDynamicStyles) { var /** @type {?} */ missingSubs_1 = new Set(); var /** @type {?} */ params_1 = astParams || {}; styleAst.styles.forEach(function (value) { if (isObject(value)) { var /** @type {?} */ stylesObj_1 = (value); Object.keys(stylesObj_1).forEach(function (prop) { extractStyleParams(stylesObj_1[prop]).forEach(function (sub) { if (!params_1.hasOwnProperty(sub)) { missingSubs_1.add(sub); } }); }); } }); if (missingSubs_1.size) { var /** @type {?} */ missingSubsArr = iteratorToArray(missingSubs_1.values()); context.errors.push("state(\"" + metadata.name + "\", ...) must define default values for all the following style substitutions: " + missingSubsArr.join(', ')); } } var /** @type {?} */ stateAst = new StateAst(metadata.name, styleAst); if (astParams) { stateAst.options = { params: astParams }; } return stateAst; }; /** * @param {?} metadata * @param {?} context * @return {?} */ AnimationAstBuilderVisitor.prototype.visitTransition = function (metadata, context) { context.queryCount = 0; context.depCount = 0; var /** @type {?} */ entry = visitAnimationNode(this, normalizeAnimationEntry(metadata.animation), context); var /** @type {?} */ matchers = parseTransitionExpr(metadata.expr, context.errors); var /** @type {?} */ ast = new TransitionAst(matchers, entry); ast.options = normalizeAnimationOptions(metadata.options); ast.queryCount = context.queryCount; ast.depCount = context.depCount; return ast; }; /** * @param {?} metadata * @param {?} context * @return {?} */ AnimationAstBuilderVisitor.prototype.visitSequence = function (metadata, context) { var _this = this; var /** @type {?} */ ast = new SequenceAst(metadata.steps.map(function (s) { return visitAnimationNode(_this, s, context); })); ast.options = normalizeAnimationOptions(metadata.options); return ast; }; /** * @param {?} metadata * @param {?} context * @return {?} */ AnimationAstBuilderVisitor.prototype.visitGroup = function (metadata, context) { var _this = this; var /** @type {?} */ currentTime = context.currentTime; var /** @type {?} */ furthestTime = 0; var /** @type {?} */ steps = metadata.steps.map(function (step) { context.currentTime = currentTime; var /** @type {?} */ innerAst = visitAnimationNode(_this, step, context); furthestTime = Math.max(furthestTime, context.currentTime); return innerAst; }); context.currentTime = furthestTime; var /** @type {?} */ ast = new GroupAst(steps); ast.options = normalizeAnimationOptions(metadata.options); return ast; }; /** * @param {?} metadata * @param {?} context * @return {?} */ AnimationAstBuilderVisitor.prototype.visitAnimate = function (metadata, context) { var /** @type {?} */ timingAst = constructTimingAst(metadata.timings, context.errors); context.currentAnimateTimings = timingAst; var /** @type {?} */ styles; var /** @type {?} */ styleMetadata = metadata.styles ? metadata.styles : _angular_animations.style({}); if (styleMetadata.type == 5 /* Keyframes */) { styles = this.visitKeyframes(/** @type {?} */ (styleMetadata), context); } else { var /** @type {?} */ styleMetadata_1 = (metadata.styles); var /** @type {?} */ isEmpty = false; if (!styleMetadata_1) { isEmpty = true; var /** @type {?} */ newStyleData = {}; if (timingAst.easing) { newStyleData['easing'] = timingAst.easing; } styleMetadata_1 = _angular_animations.style(newStyleData); } context.currentTime += timingAst.duration + timingAst.delay; var /** @type {?} */ styleAst = this.visitStyle(styleMetadata_1, context); styleAst.isEmptyStep = isEmpty; styles = styleAst; } context.currentAnimateTimings = null; return new AnimateAst(timingAst, styles); }; /** * @param {?} metadata * @param {?} context * @return {?} */ AnimationAstBuilderVisitor.prototype.visitStyle = function (metadata, context) { var /** @type {?} */ ast = this._makeStyleAst(metadata, context); this._validateStyleAst(ast, context); return ast; }; /** * @param {?} metadata * @param {?} context * @return {?} */ AnimationAstBuilderVisitor.prototype._makeStyleAst = function (metadata, context) { var /** @type {?} */ styles = []; if (Array.isArray(metadata.styles)) { ((metadata.styles)).forEach(function (styleTuple) { if (typeof styleTuple == 'string') { if (styleTuple == _angular_animations.AUTO_STYLE) { styles.push(/** @type {?} */ (styleTuple)); } else { context.errors.push("The provided style string value " + styleTuple + " is not allowed."); } } else { styles.push(/** @type {?} */ (styleTuple)); } }); } else { styles.push(metadata.styles); } var /** @type {?} */ containsDynamicStyles = false; var /** @type {?} */ collectedEasing = null; styles.forEach(function (styleData) { if (isObject(styleData)) { var /** @type {?} */ styleMap = (styleData); var /** @type {?} */ easing = styleMap['easing']; if (easing) { collectedEasing = (easing); delete styleMap['easing']; } if (!containsDynamicStyles) { for (var /** @type {?} */ prop in styleMap) { var /** @type {?} */ value = styleMap[prop]; if (value.toString().indexOf(SUBSTITUTION_EXPR_START) >= 0) { containsDynamicStyles = true; break; } } } } }); var /** @type {?} */ ast = new StyleAst(styles, collectedEasing, metadata.offset); ast.containsDynamicStyles = containsDynamicStyles; return ast; }; /** * @param {?} ast * @param {?} context * @return {?} */ AnimationAstBuilderVisitor.prototype._validateStyleAst = function (ast, context) { var /** @type {?} */ timings = context.currentAnimateTimings; var /** @type {?} */ endTime = context.currentTime; var /** @type {?} */ startTime = context.currentTime; if (timings && startTime > 0) { startTime -= timings.duration + timings.delay; } ast.styles.forEach(function (tuple) { if (typeof tuple == 'string') return; Object.keys(tuple).forEach(function (prop) { var /** @type {?} */ collectedStyles = context.collectedStyles[((context.currentQuerySelector))]; var /** @type {?} */ collectedEntry = collectedStyles[prop]; var /** @type {?} */ updateCollectedStyle = true; if (collectedEntry) { if (startTime != endTime && startTime >= collectedEntry.startTime && endTime <= collectedEntry.endTime) { context.errors.push("The CSS property \"" + prop + "\" that exists between the times of \"" + collectedEntry.startTime + "ms\" and \"" + collectedEntry.endTime + "ms\" is also being animated in a parallel animation between the times of \"" + startTime + "ms\" and \"" + endTime + "ms\""); updateCollectedStyle = false; } // we always choose the smaller start time value since we // want to have a record of the entire animation window where // the style property is being animated in between startTime = collectedEntry.startTime; } if (updateCollectedStyle) { collectedStyles[prop] = { startTime: startTime, endTime: endTime }; } if (context.options) { validateStyleParams(tuple[prop], context.options, context.errors); } }); }); }; /** * @param {?} metadata * @param {?} context * @return {?} */ AnimationAstBuilderVisitor.prototype.visitKeyframes = function (metadata, context) { var _this = this; if (!context.currentAnimateTimings) { context.errors.push("keyframes() must be placed inside of a call to animate()"); return new KeyframesAst([]); } var /** @type {?} */ MAX_KEYFRAME_OFFSET = 1; var /** @type {?} */ totalKeyframesWithOffsets = 0; var /** @type {?} */ offsets = []; var /** @type {?} */ offsetsOutOfOrder = false; var /** @type {?} */ keyframesOutOfRange = false; var /** @type {?} */ previousOffset = 0; var /** @type {?} */ keyframes = metadata.steps.map(function (styles) { var /** @type {?} */ style$$1 = _this._makeStyleAst(styles, context); var /** @type {?} */ offsetVal = style$$1.offset != null ? style$$1.offset : consumeOffset(style$$1.styles); var /** @type {?} */ offset = 0; if (offsetVal != null) { totalKeyframesWithOffsets++; offset = style$$1.offset = offsetVal; } keyframesOutOfRange = keyframesOutOfRange || offset < 0 || offset > 1; offsetsOutOfOrder = offsetsOutOfOrder || offset < previousOffset; previousOffset = offset; offsets.push(offset); return style$$1; }); if (keyframesOutOfRange) { context.errors.push("Please ensure that all keyframe offsets are between 0 and 1"); } if (offsetsOutOfOrder) { context.errors.push("Please ensure that all keyframe offsets are in order"); } var /** @type {?} */ length = metadata.steps.length; var /** @type {?} */ generatedOffset = 0; if (totalKeyframesWithOffsets > 0 && totalKeyframesWithOffsets < length) { context.errors.push("Not all style() steps within the declared keyframes() contain offsets"); } else if (totalKeyframesWithOffsets == 0) { generatedOffset = MAX_KEYFRAME_OFFSET / (length - 1); } var /** @type {?} */ limit = length - 1; var /** @type {?} */ currentTime = context.currentTime; var /** @type {?} */ currentAnimateTimings = ((context.currentAnimateTimings)); var /** @type {?} */ animateDuration = currentAnimateTimings.duration; keyframes.forEach(function (kf, i) { var /** @type {?} */ offset = generatedOffset > 0 ? (i == limit ? 1 : (generatedOffset * i)) : offsets[i]; var /** @type {?} */ durationUpToThisFrame = offset * animateDuration; context.currentTime = currentTime + currentAnimateTimings.delay + durationUpToThisFrame; currentAnimateTimings.duration = durationUpToThisFrame; _this._validateStyleAst(kf, context); kf.offset = offset; }); return new KeyframesAst(keyframes); }; /** * @param {?} metadata * @param {?} context * @return {?} */ AnimationAstBuilderVisitor.prototype.visitReference = function (metadata, context) { var /** @type {?} */ entry = visitAnimationNode(this, normalizeAnimationEntry(metadata.animation), context); var /** @type {?} */ ast = new ReferenceAst(entry); ast.options = normalizeAnimationOptions(metadata.options); return ast; }; /** * @param {?} metadata * @param {?} context * @return {?} */ AnimationAstBuilderVisitor.prototype.visitAnimateChild = function (metadata, context) { context.depCount++; var /** @type {?} */ ast = new AnimateChildAst(); ast.options = normalizeAnimationOptions(metadata.options); return ast; }; /** * @param {?} metadata * @param {?} context * @return {?} */ AnimationAstBuilderVisitor.prototype.visitAnimateRef = function (metadata, context) { var /** @type {?} */ animation = this.visitReference(metadata.animation, context); var /** @type {?} */ ast = new AnimateRefAst(animation); ast.options = normalizeAnimationOptions(metadata.options); return ast; }; /** * @param {?} metadata * @param {?} context * @return {?} */ AnimationAstBuilderVisitor.prototype.visitQuery = function (metadata, context) { var /** @type {?} */ parentSelector = ((context.currentQuerySelector)); var /** @type {?} */ options = ((metadata.options || {})); context.queryCount++; context.currentQuery = metadata; var _a = normalizeSelector(metadata.selector), selector = _a[0], includeSelf = _a[1]; context.currentQuerySelector = parentSelector.length ? (parentSelector + ' ' + selector) : selector; getOrSetAsInMap(context.collectedStyles, context.currentQuerySelector, {}); var /** @type {?} */ entry = visitAnimationNode(this, normalizeAnimationEntry(metadata.animation), context); context.currentQuery = null; context.currentQuerySelector = parentSelector; var /** @type {?} */ ast = new QueryAst(selector, options.limit || 0, !!options.optional, includeSelf, entry); ast.originalSelector = metadata.selector; ast.options = normalizeAnimationOptions(metadata.options); return ast; }; /** * @param {?} metadata * @param {?} context * @return {?} */ AnimationAstBuilderVisitor.prototype.visitStagger = function (metadata, context) { if (!context.currentQuery) { context.errors.push("stagger() can only be used inside of query()"); } var /** @type {?} */ timings = metadata.timings === 'full' ? { duration: 0, delay: 0, easing: 'full' } : resolveTiming(metadata.timings, context.errors, true); var /** @type {?} */ animation = visitAnimationNode(this, normalizeAnimationEntry(metadata.animation), context); return new StaggerAst(timings, animation); }; return AnimationAstBuilderVisitor; }()); /** * @param {?} selector * @return {?} */ function normalizeSelector(selector) { var /** @type {?} */ hasAmpersand = selector.split(/\s*,\s*/).find(function (token) { return token == SELF_TOKEN; }) ? true : false; if (hasAmpersand) { selector = selector.replace(SELF_TOKEN_REGEX, ''); } selector = selector.replace(ENTER_TOKEN_REGEX, ENTER_SELECTOR) .replace(LEAVE_TOKEN_REGEX, LEAVE_SELECTOR) .replace(/@\*/g, NG_TRIGGER_SELECTOR) .replace(/@\w+/g, function (match) { return NG_TRIGGER_SELECTOR + '-' + match.substr(1); }) .replace(/:animating/g, NG_ANIMATING_SELECTOR); return [selector, hasAmpersand]; } /** * @param {?} obj * @return {?} */ function normalizeParams(obj) { return obj ? copyObj(obj) : null; } var AnimationAstBuilderContext = (function () { /** * @param {?} errors */ function AnimationAstBuilderContext(errors) { this.errors = errors; this.queryCount = 0; this.depCount = 0; this.currentTransition = null; this.currentQuery = null; this.currentQuerySelector = null; this.currentAnimateTimings = null; this.currentTime = 0; this.collectedStyles = {}; this.options = null; } return AnimationAstBuilderContext; }()); /** * @param {?} styles * @return {?} */ function consumeOffset(styles) { if (typeof styles == 'string') return null; var /** @type {?} */ offset = null; if (Array.isArray(styles)) { styles.forEach(function (styleTuple) { if (isObject(styleTuple) && styleTuple.hasOwnProperty('offset')) { var /** @type {?} */ obj = (styleTuple); offset = parseFloat(/** @type {?} */ (obj['offset'])); delete obj['offset']; } }); } else if (isObject(styles) && styles.hasOwnProperty('offset')) { var /** @type {?} */ obj = (styles); offset = parseFloat(/** @type {?} */ (obj['offset'])); delete obj['offset']; } return offset; } /** * @param {?} value * @return {?} */ function isObject(value) { return !Array.isArray(value) && typeof value == 'object'; } /** * @param {?} value * @param {?} errors * @return {?} */ function constructTimingAst(value, errors) { var /** @type {?} */ timings = null; if (value.hasOwnProperty('duration')) { timings = (value); } else if (typeof value == 'number') { var /** @type {?} */ duration = resolveTiming(/** @type {?} */ (value), errors).duration; return new TimingAst(/** @type {?} */ (value), 0, ''); } var /** @type {?} */ strValue = (value); var /** @type {?} */ isDynamic = strValue.split(/\s+/).some(function (v) { return v.charAt(0) == '{' && v.charAt(1) == '{'; }); if (isDynamic) { return new DynamicTimingAst(strValue); } timings = timings || resolveTiming(strValue, errors); return new TimingAst(timings.duration, timings.delay, timings.easing); } /** * @param {?} options * @return {?} */ function normalizeAnimationOptions(options) { if (options) { options = copyObj(options); if (options['params']) { options['params'] = ((normalizeParams(options['params']))); } } else { options = {}; } return options; } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @param {?} element * @param {?} keyframes * @param {?} preStyleProps * @param {?} postStyleProps * @param {?} duration * @param {?} delay * @param {?=} easing * @param {?=} subTimeline * @return {?} */ function createTimelineInstruction(element, keyframes, preStyleProps, postStyleProps, duration, delay, easing, subTimeline) { if (easing === void 0) { easing = null; } if (subTimeline === void 0) { subTimeline = false; } return { type: 1 /* TimelineAnimation */, element: element, keyframes: keyframes, preStyleProps: preStyleProps, postStyleProps: postStyleProps, duration: duration, delay: delay, totalTime: duration + delay, easing: easing, subTimeline: subTimeline }; } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var ElementInstructionMap = (function () { function ElementInstructionMap() { this._map = new Map(); } /** * @param {?} element * @return {?} */ ElementInstructionMap.prototype.consume = function (element) { var /** @type {?} */ instructions = this._map.get(element); if (instructions) { this._map.delete(element); } else { instructions = []; } return instructions; }; /** * @param {?} element * @param {?} instructions * @return {?} */ ElementInstructionMap.prototype.append = function (element, instructions) { var /** @type {?} */ existingInstructions = this._map.get(element); if (!existingInstructions) { this._map.set(element, existingInstructions = []); } existingInstructions.push.apply(existingInstructions, instructions); }; /** * @param {?} element * @return {?} */ ElementInstructionMap.prototype.has = function (element) { return this._map.has(element); }; /** * @return {?} */ ElementInstructionMap.prototype.clear = function () { this._map.clear(); }; return ElementInstructionMap; }()); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var ONE_FRAME_IN_MILLISECONDS = 1; /** * @param {?} driver * @param {?} rootElement * @param {?} ast * @param {?=} startingStyles * @param {?=} finalStyles * @param {?=} options * @param {?=} subInstructions * @param {?=} errors * @return {?} */ function buildAnimationTimelines(driver, rootElement, ast, startingStyles, finalStyles, options, subInstructions, errors) { if (startingStyles === void 0) { startingStyles = {}; } if (finalStyles === void 0) { finalStyles = {}; } if (errors === void 0) { errors = []; } return new AnimationTimelineBuilderVisitor().buildKeyframes(driver, rootElement, ast, startingStyles, finalStyles, options, subInstructions, errors); } var AnimationTimelineBuilderVisitor = (function () { function AnimationTimelineBuilderVisitor() { } /** * @param {?} driver * @param {?} rootElement * @param {?} ast * @param {?} startingStyles * @param {?} finalStyles * @param {?} options * @param {?=} subInstructions * @param {?=} errors * @return {?} */ AnimationTimelineBuilderVisitor.prototype.buildKeyframes = function (driver, rootElement, ast, startingStyles, finalStyles, options, subInstructions, errors) { if (errors === void 0) { errors = []; } subInstructions = subInstructions || new ElementInstructionMap(); var /** @type {?} */ context = new AnimationTimelineContext(driver, rootElement, subInstructions, errors, []); context.options = options; context.currentTimeline.setStyles([startingStyles], null, context.errors, options); ast.visit(this, context); // this checks to see if an actual animation happened var /** @type {?} */ timelines = context.timelines.filter(function (timeline) { return timeline.containsAnimation(); }); if (timelines.length && Object.keys(finalStyles).length) { var /** @type {?} */ tl = timelines[timelines.length - 1]; if (!tl.allowOnlyTimelineStyles()) { tl.setStyles([finalStyles], null, context.errors, options); } } return timelines.length ? timelines.map(function (timeline) { return timeline.buildKeyframes(); }) : [createTimelineInstruction(rootElement, [], [], [], 0, 0, '', false)]; }; /** * @param {?} ast * @param {?} context * @return {?} */ AnimationTimelineBuilderVisitor.prototype.visitTrigger = function (ast, context) { // these values are not visited in this AST }; /** * @param {?} ast * @param {?} context * @return {?} */ AnimationTimelineBuilderVisitor.prototype.visitState = function (ast, context) { // these values are not visited in this AST }; /** * @param {?} ast * @param {?} context * @return {?} */ AnimationTimelineBuilderVisitor.prototype.visitTransition = function (ast, context) { // these values are not visited in this AST }; /** * @param {?} ast * @param {?} context * @return {?} */ AnimationTimelineBuilderVisitor.prototype.visitAnimateChild = function (ast, context) { var /** @type {?} */ elementInstructions = context.subInstructions.consume(context.element); if (elementInstructions) { var /** @type {?} */ innerContext = context.createSubContext(ast.options); var /** @type {?} */ startTime = context.currentTimeline.currentTime; var /** @type {?} */ endTime = this._visitSubInstructions(elementInstructions, innerContext, /** @type {?} */ (innerContext.options)); if (startTime != endTime) { // we do this on the upper context because we created a sub context for // the sub child animations context.transformIntoNewTimeline(endTime); } } context.previousNode = ast; }; /** * @param {?} ast * @param {?} context * @return {?} */ AnimationTimelineBuilderVisitor.prototype.visitAnimateRef = function (ast, context) { var /** @type {?} */ innerContext = context.createSubContext(ast.options); innerContext.transformIntoNewTimeline(); this.visitReference(ast.animation, innerContext); context.transformIntoNewTimeline(innerContext.currentTimeline.currentTime); context.previousNode = ast; }; /** * @param {?} instructions * @param {?} context * @param {?} options * @return {?} */ AnimationTimelineBuilderVisitor.prototype._visitSubInstructions = function (instructions, context, options) { var /** @type {?} */ startTime = context.currentTimeline.currentTime; var /** @type {?} */ furthestTime = startTime; // this is a special-case for when a user wants to skip a sub // animation from being fired entirely. var /** @type {?} */ duration = options.duration != null ? resolveTimingValue(options.duration) : null; var /** @type {?} */ delay = options.delay != null ? resolveTimingValue(options.delay) : null; if (duration !== 0) { instructions.forEach(function (instruction) { var /** @type {?} */ instructionTimings = context.appendInstructionToTimeline(instruction, duration, delay); furthestTime = Math.max(furthestTime, instructionTimings.duration + instructionTimings.delay); }); } return furthestTime; }; /** * @param {?} ast * @param {?} context * @return {?} */ AnimationTimelineBuilderVisitor.prototype.visitReference = function (ast, context) { context.updateOptions(ast.options, true); ast.animation.visit(this, context); context.previousNode = ast; }; /** * @param {?} ast * @param {?} context * @return {?} */ AnimationTimelineBuilderVisitor.prototype.visitSequence = function (ast, context) { var _this = this; var /** @type {?} */ subContextCount = context.subContextCount; var /** @type {?} */ ctx = context; var /** @type {?} */ options = ast.options; if (options && (options.params || options.delay)) { ctx = context.createSubContext(options); ctx.transformIntoNewTimeline(); if (options.delay != null) { if (ctx.previousNode instanceof StyleAst) { ctx.currentTimeline.snapshotCurrentStyles(); ctx.previousNode = DEFAULT_NOOP_PREVIOUS_NODE; } var /** @type {?} */ delay = resolveTimingValue(options.delay); ctx.delayNextStep(delay); } } if (ast.steps.length) { ast.steps.forEach(function (s) { return s.visit(_this, ctx); }); // this is here just incase the inner steps only contain or end with a style() call ctx.currentTimeline.applyStylesToKeyframe(); // this means that some animation function within the sequence // ended up creating a sub timeline (which means the current // timeline cannot overlap with the contents of the sequence) if (ctx.subContextCount > subContextCount) { ctx.transformIntoNewTimeline(); } } context.previousNode = ast; }; /** * @param {?} ast * @param {?} context * @return {?} */ AnimationTimelineBuilderVisitor.prototype.visitGroup = function (ast, context) { var _this = this; var /** @type {?} */ innerTimelines = []; var /** @type {?} */ furthestTime = context.currentTimeline.currentTime; var /** @type {?} */ delay = ast.options && ast.options.delay ? resolveTimingValue(ast.options.delay) : 0; ast.steps.forEach(function (s) { var /** @type {?} */ innerContext = context.createSubContext(ast.options); if (delay) { innerContext.delayNextStep(delay); } s.visit(_this, innerContext); furthestTime = Math.max(furthestTime, innerContext.currentTimeline.currentTime); innerTimelines.push(innerContext.currentTimeline); }); // this operation is run after the AST loop because otherwise // if the parent timeline's collected styles were updated then // it would pass in invalid data into the new-to-be forked items innerTimelines.forEach(function (timeline) { return context.currentTimeline.mergeTimelineCollectedStyles(timeline); }); context.transformIntoNewTimeline(furthestTime); context.previousNode = ast; }; /** * @param {?} ast * @param {?} context * @return {?} */ AnimationTimelineBuilderVisitor.prototype.visitTiming = function (ast, context) { if (ast instanceof DynamicTimingAst) { var /** @type {?} */ strValue = context.params ? interpolateParams(ast.value, context.params, context.errors) : ast.value.toString(); return resolveTiming(strValue, context.errors); } else { return { duration: ast.duration, delay: ast.delay, easing: ast.easing }; } }; /** * @param {?} ast * @param {?} context * @return {?} */ AnimationTimelineBuilderVisitor.prototype.visitAnimate = function (ast, context) { var /** @type {?} */ timings = context.currentAnimateTimings = this.visitTiming(ast.timings, context); var /** @type {?} */ timeline = context.currentTimeline; if (timings.delay) { context.incrementTime(timings.delay); timeline.snapshotCurrentStyles(); } var /** @type {?} */ style$$1 = ast.style; if (style$$1 instanceof KeyframesAst) { this.visitKeyframes(style$$1, context); } else { context.incrementTime(timings.duration); this.visitStyle(/** @type {?} */ (style$$1), context); timeline.applyStylesToKeyframe(); } context.currentAnimateTimings = null; context.previousNode = ast; }; /** * @param {?} ast * @param {?} context * @return {?} */ AnimationTimelineBuilderVisitor.prototype.visitStyle = function (ast, context) { var /** @type {?} */ timeline = context.currentTimeline; var /** @type {?} */ timings = ((context.currentAnimateTimings)); // this is a special case for when a style() call // directly follows an animate() call (but not inside of an animate() call) if (!timings && timeline.getCurrentStyleProperties().length) { timeline.forwardFrame(); } var /** @type {?} */ easing = (timings && timings.easing) || ast.easing; if (ast.isEmptyStep) { timeline.applyEmptyStep(easing); } else { timeline.setStyles(ast.styles, easing, context.errors, context.options); } context.previousNode = ast; }; /** * @param {?} ast * @param {?} context * @return {?} */ AnimationTimelineBuilderVisitor.prototype.visitKeyframes = function (ast, context) { var /** @type {?} */ currentAnimateTimings = ((context.currentAnimateTimings)); var /** @type {?} */ startTime = (((context.currentTimeline))).duration; var /** @type {?} */ duration = currentAnimateTimings.duration; var /** @type {?} */ innerContext = context.createSubContext(); var /** @type {?} */ innerTimeline = innerContext.currentTimeline; innerTimeline.easing = currentAnimateTimings.easing; ast.styles.forEach(function (step) { var /** @type {?} */ offset = step.offset || 0; innerTimeline.forwardTime(offset * duration); innerTimeline.setStyles(step.styles, step.easing, context.errors, context.options); innerTimeline.applyStylesToKeyframe(); }); // this will ensure that the parent timeline gets all the styles from // the child even if the new timeline below is not used context.currentTimeline.mergeTimelineCollectedStyles(innerTimeline); // we do this because the window between this timeline and the sub timeline // should ensure that the styles within are exactly the same as they were before context.transformIntoNewTimeline(startTime + duration); context.previousNode = ast; }; /** * @param {?} ast * @param {?} context * @return {?} */ AnimationTimelineBuilderVisitor.prototype.visitQuery = function (ast, context) { var _this = this; // in the event that the first step before this is a style step we need // to ensure the styles are applied before the children are animated var /** @type {?} */ startTime = context.currentTimeline.currentTime; var /** @type {?} */ options = ((ast.options || {})); var /** @type {?} */ delay = options.delay ? resolveTimingValue(options.delay) : 0; if (delay && (context.previousNode instanceof StyleAst || (startTime == 0 && context.currentTimeline.getCurrentStyleProperties().length))) { context.currentTimeline.snapshotCurrentStyles(); context.previousNode = DEFAULT_NOOP_PREVIOUS_NODE; } var /** @type {?} */ furthestTime = startTime; var /** @type {?} */ elms = context.invokeQuery(ast.selector, ast.originalSelector, ast.limit, ast.includeSelf, options.optional ? true : false, context.errors); context.currentQueryTotal = elms.length; var /** @type {?} */ sameElementTimeline = null; elms.forEach(function (element, i) { context.currentQueryIndex = i; var /** @type {?} */ innerContext = context.createSubContext(ast.options, element); if (delay) { innerContext.delayNextStep(delay); } if (element === context.element) { sameElementTimeline = innerContext.currentTimeline; } ast.animation.visit(_this, innerContext); // this is here just incase the inner steps only contain or end // with a style() call (which is here to signal that this is a preparatory // call to style an element before it is animated again) innerContext.currentTimeline.applyStylesToKeyframe(); var /** @type {?} */ endTime = innerContext.currentTimeline.currentTime; furthestTime = Math.max(furthestTime, endTime); }); context.currentQueryIndex = 0; context.currentQueryTotal = 0; context.transformIntoNewTimeline(furthestTime); if (sameElementTimeline) { context.currentTimeline.mergeTimelineCollectedStyles(sameElementTimeline); context.currentTimeline.snapshotCurrentStyles(); } context.previousNode = ast; }; /** * @param {?} ast * @param {?} context * @return {?} */ AnimationTimelineBuilderVisitor.prototype.visitStagger = function (ast, context) { var /** @type {?} */ parentContext = ((context.parentContext)); var /** @type {?} */ tl = context.currentTimeline; var /** @type {?} */ timings = ast.timings; var /** @type {?} */ duration = Math.abs(timings.duration); var /** @type {?} */ maxTime = duration * (context.currentQueryTotal - 1); var /** @type {?} */ delay = duration * context.currentQueryIndex; var /** @type {?} */ staggerTransformer = timings.duration < 0 ? 'reverse' : timings.easing; switch (staggerTransformer) { case 'reverse': delay = maxTime - delay; break; case 'full': delay = parentContext.currentStaggerTime; break; } var /** @type {?} */ timeline = context.currentTimeline; if (delay) { timeline.delayNextStep(delay); } var /** @type {?} */ startingTime = timeline.currentTime; ast.animation.visit(this, context); context.previousNode = ast; // time = duration + delay // the reason why this computation is so complex is because // the inner timeline may either have a delay value or a stretched // keyframe depending on if a subtimeline is not used or is used. parentContext.currentStaggerTime = (tl.currentTime - startingTime) + (tl.startTime - parentContext.currentTimeline.startTime); }; return AnimationTimelineBuilderVisitor; }()); var DEFAULT_NOOP_PREVIOUS_NODE = ({}); var AnimationTimelineContext = (function () { /** * @param {?} _driver * @param {?} element * @param {?} subInstructions * @param {?} errors * @param {?} timelines * @param {?=} initialTimeline */ function AnimationTimelineContext(_driver, element, subInstructions, errors, timelines, initialTimeline) { this._driver = _driver; this.element = element; this.subInstructions = subInstructions; this.errors = errors; this.timelines = timelines; this.parentContext = null; this.currentAnimateTimings = null; this.previousNode = DEFAULT_NOOP_PREVIOUS_NODE; this.subContextCount = 0; this.options = {}; this.currentQueryIndex = 0; this.currentQueryTotal = 0; this.currentStaggerTime = 0; this.currentTimeline = initialTimeline || new TimelineBuilder(element, 0); timelines.push(this.currentTimeline); } Object.defineProperty(AnimationTimelineContext.prototype, "params", { /** * @return {?} */ get: function () { return this.options.params; }, enumerable: true, configurable: true }); /** * @param {?} options * @param {?=} skipIfExists * @return {?} */ AnimationTimelineContext.prototype.updateOptions = function (options, skipIfExists) { var _this = this; if (!options) return; var /** @type {?} */ newOptions = (options); var /** @type {?} */ optionsToUpdate = this.options; // NOTE: this will get patched up when other animation methods support duration overrides if (newOptions.duration != null) { ((optionsToUpdate)).duration = resolveTimingValue(newOptions.duration); } if (newOptions.delay != null) { optionsToUpdate.delay = resolveTimingValue(newOptions.delay); } var /** @type {?} */ newParams = newOptions.params; if (newParams) { var /** @type {?} */ paramsToUpdate_1 = ((optionsToUpdate.params)); if (!paramsToUpdate_1) { paramsToUpdate_1 = this.options.params = {}; } Object.keys(newParams).forEach(function (name) { if (!skipIfExists || !paramsToUpdate_1.hasOwnProperty(name)) { paramsToUpdate_1[name] = interpolateParams(newParams[name], paramsToUpdate_1, _this.errors); } }); } }; /** * @return {?} */ AnimationTimelineContext.prototype._copyOptions = function () { var /** @type {?} */ options = {}; if (this.options) { var /** @type {?} */ oldParams_1 = this.options.params; if (oldParams_1) { var /** @type {?} */ params_2 = options['params'] = {}; Object.keys(this.options.params).forEach(function (name) { params_2[name] = oldParams_1[name]; }); } } return options; }; /** * @param {?=} options * @param {?=} element * @param {?=} newTime * @return {?} */ AnimationTimelineContext.prototype.createSubContext = function (options, element, newTime) { if (options === void 0) { options = null; } var /** @type {?} */ target = element || this.element; var /** @type {?} */ context = new AnimationTimelineContext(this._driver, target, this.subInstructions, this.errors, this.timelines, this.currentTimeline.fork(target, newTime || 0)); context.previousNode = this.previousNode; context.currentAnimateTimings = this.currentAnimateTimings; context.options = this._copyOptions(); context.updateOptions(options); context.currentQueryIndex = this.currentQueryIndex; context.currentQueryTotal = this.currentQueryTotal; context.parentContext = this; this.subContextCount++; return context; }; /** * @param {?=} newTime * @return {?} */ AnimationTimelineContext.prototype.transformIntoNewTimeline = function (newTime) { this.previousNode = DEFAULT_NOOP_PREVIOUS_NODE; this.currentTimeline = this.currentTimeline.fork(this.element, newTime); this.timelines.push(this.currentTimeline); return this.currentTimeline; }; /** * @param {?} instruction * @param {?} duration * @param {?} delay * @return {?} */ AnimationTimelineContext.prototype.appendInstructionToTimeline = function (instruction, duration, delay) { var /** @type {?} */ updatedTimings = { duration: duration != null ? duration : instruction.duration, delay: this.currentTimeline.currentTime + (delay != null ? delay : 0) + instruction.delay, easing: '' }; var /** @type {?} */ builder = new SubTimelineBuilder(instruction.element, instruction.keyframes, instruction.preStyleProps, instruction.postStyleProps, updatedTimings, instruction.stretchStartingKeyframe); this.timelines.push(builder); return updatedTimings; }; /** * @param {?} time * @return {?} */ AnimationTimelineContext.prototype.incrementTime = function (time) { this.currentTimeline.forwardTime(this.currentTimeline.duration + time); }; /** * @param {?} delay * @return {?} */ AnimationTimelineContext.prototype.delayNextStep = function (delay) { // negative delays are not yet supported if (delay > 0) { this.currentTimeline.delayNextStep(delay); } }; /** * @param {?} selector * @param {?} originalSelector * @param {?} limit * @param {?} includeSelf * @param {?} optional * @param {?} errors * @return {?} */ AnimationTimelineContext.prototype.invokeQuery = function (selector, originalSelector, limit, includeSelf, optional, errors) { var /** @type {?} */ results = []; if (includeSelf) { results.push(this.element); } if (selector.length > 0) { var /** @type {?} */ multi = limit != 1; var /** @type {?} */ elements = this._driver.query(this.element, selector, multi); if (limit !== 0) { elements = elements.slice(0, limit); } results.push.apply(results, elements); } if (!optional && results.length == 0) { errors.push("`query(\"" + originalSelector + "\")` returned zero elements. (Use `query(\"" + originalSelector + "\", { optional: true })` if you wish to allow this.)"); } return results; }; return AnimationTimelineContext; }()); var TimelineBuilder = (function () { /** * @param {?} element * @param {?} startTime * @param {?=} _elementTimelineStylesLookup */ function TimelineBuilder(element, startTime, _elementTimelineStylesLookup) { this.element = element; this.startTime = startTime; this._elementTimelineStylesLookup = _elementTimelineStylesLookup; this.duration = 0; this._previousKeyframe = {}; this._currentKeyframe = {}; this._keyframes = new Map(); this._styleSummary = {}; this._pendingStyles = {}; this._backFill = {}; this._currentEmptyStepKeyframe = null; if (!this._elementTimelineStylesLookup) { this._elementTimelineStylesLookup = new Map(); } this._localTimelineStyles = Object.create(this._backFill, {}); this._globalTimelineStyles = this._elementTimelineStylesLookup.get(element); if (!this._globalTimelineStyles) { this._globalTimelineStyles = this._localTimelineStyles; this._elementTimelineStylesLookup.set(element, this._localTimelineStyles); } this._loadKeyframe(); } /** * @return {?} */ TimelineBuilder.prototype.containsAnimation = function () { switch (this._keyframes.size) { case 0: return false; case 1: return this.getCurrentStyleProperties().length > 0; default: return true; } }; /** * @return {?} */ TimelineBuilder.prototype.getCurrentStyleProperties = function () { return Object.keys(this._currentKeyframe); }; Object.defineProperty(TimelineBuilder.prototype, "currentTime", { /** * @return {?} */ get: function () { return this.startTime + this.duration; }, enumerable: true, configurable: true }); /** * @param {?} delay * @return {?} */ TimelineBuilder.prototype.delayNextStep = function (delay) { // in the event that a style() step is placed right before a stagger() // and that style() step is the very first style() value in the animation // then we need to make a copy of the keyframe [0, copy, 1] so that the delay // properly applies the style() values to work with the stagger... var /** @type {?} */ hasPreStyleStep = this._keyframes.size == 1 && Object.keys(this._pendingStyles).length; if (this.duration || hasPreStyleStep) { this.forwardTime(this.currentTime + delay); if (hasPreStyleStep) { this.snapshotCurrentStyles(); } } else { this.startTime += delay; } }; /** * @param {?} element * @param {?=} currentTime * @return {?} */ TimelineBuilder.prototype.fork = function (element, currentTime) { this.applyStylesToKeyframe(); return new TimelineBuilder(element, currentTime || this.currentTime, this._elementTimelineStylesLookup); }; /** * @return {?} */ TimelineBuilder.prototype._loadKeyframe = function () { if (this._currentKeyframe) { this._previousKeyframe = this._currentKeyframe; } this._currentKeyframe = ((this._keyframes.get(this.duration))); if (!this._currentKeyframe) { this._currentKeyframe = Object.create(this._backFill, {}); this._keyframes.set(this.duration, this._currentKeyframe); } }; /** * @return {?} */ TimelineBuilder.prototype.forwardFrame = function () { this.duration += ONE_FRAME_IN_MILLISECONDS; this._loadKeyframe(); }; /** * @param {?} time * @return {?} */ TimelineBuilder.prototype.forwardTime = function (time) { this.applyStylesToKeyframe(); this.duration = time; this._loadKeyframe(); }; /** * @param {?} prop * @param {?} value * @return {?} */ TimelineBuilder.prototype._updateStyle = function (prop, value) { this._localTimelineStyles[prop] = value; this._globalTimelineStyles[prop] = value; this._styleSummary[prop] = { time: this.currentTime, value: value }; }; /** * @return {?} */ TimelineBuilder.prototype.allowOnlyTimelineStyles = function () { return this._currentEmptyStepKeyframe !== this._currentKeyframe; }; /** * @param {?} easing * @return {?} */ TimelineBuilder.prototype.applyEmptyStep = function (easing) { var _this = this; if (easing) { this._previousKeyframe['easing'] = easing; } // special case for animate(duration): // all missing styles are filled with a `*` value then // if any destination styles are filled in later on the same // keyframe then they will override the overridden styles // We use `_globalTimelineStyles` here because there may be // styles in previous keyframes that are not present in this timeline Object.keys(this._globalTimelineStyles).forEach(function (prop) { _this._backFill[prop] = _this._globalTimelineStyles[prop] || _angular_animations.AUTO_STYLE; _this._currentKeyframe[prop] = _angular_animations.AUTO_STYLE; }); this._currentEmptyStepKeyframe = this._currentKeyframe; }; /** * @param {?} input * @param {?} easing * @param {?} errors * @param {?=} options * @return {?} */ TimelineBuilder.prototype.setStyles = function (input, easing, errors, options) { var _this = this; if (easing) { this._previousKeyframe['easing'] = easing; } var /** @type {?} */ params = (options && options.params) || {}; var /** @type {?} */ styles = flattenStyles(input, this._globalTimelineStyles); Object.keys(styles).forEach(function (prop) { var /** @type {?} */ val = interpolateParams(styles[prop], params, errors); _this._pendingStyles[prop] = val; if (!_this._localTimelineStyles.hasOwnProperty(prop)) { _this._backFill[prop] = _this._globalTimelineStyles.hasOwnProperty(prop) ? _this._globalTimelineStyles[prop] : _angular_animations.AUTO_STYLE; } _this._updateStyle(prop, val); }); }; /** * @return {?} */ TimelineBuilder.prototype.applyStylesToKeyframe = function () { var _this = this; var /** @type {?} */ styles = this._pendingStyles; var /** @type {?} */ props = Object.keys(styles); if (props.length == 0) return; this._pendingStyles = {}; props.forEach(function (prop) { var /** @type {?} */ val = styles[prop]; _this._currentKeyframe[prop] = val; }); Object.keys(this._localTimelineStyles).forEach(function (prop) { if (!_this._currentKeyframe.hasOwnProperty(prop)) { _this._currentKeyframe[prop] = _this._localTimelineStyles[prop]; } }); }; /** * @return {?} */ TimelineBuilder.prototype.snapshotCurrentStyles = function () { var _this = this; Object.keys(this._localTimelineStyles).forEach(function (prop) { var /** @type {?} */ val = _this._localTimelineStyles[prop]; _this._pendingStyles[prop] = val; _this._updateStyle(prop, val); }); }; /** * @return {?} */ TimelineBuilder.prototype.getFinalKeyframe = function () { return this._keyframes.get(this.duration); }; Object.defineProperty(TimelineBuilder.prototype, "properties", { /** * @return {?} */ get: function () { var /** @type {?} */ properties = []; for (var /** @type {?} */ prop in this._currentKeyframe) { properties.push(prop); } return properties; }, enumerable: true, configurable: true }); /** * @param {?} timeline * @return {?} */ TimelineBuilder.prototype.mergeTimelineCollectedStyles = function (timeline) { var _this = this; Object.keys(timeline._styleSummary).forEach(function (prop) { var /** @type {?} */ details0 = _this._styleSummary[prop]; var /** @type {?} */ details1 = timeline._styleSummary[prop]; if (!details0 || details1.time > details0.time) { _this._updateStyle(prop, details1.value); } }); }; /** * @return {?} */ TimelineBuilder.prototype.buildKeyframes = function () { var _this = this; this.applyStylesToKeyframe(); var /** @type {?} */ preStyleProps = new Set(); var /** @type {?} */ postStyleProps = new Set(); var /** @type {?} */ isEmpty = this._keyframes.size === 1 && this.duration === 0; var /** @type {?} */ finalKeyframes = []; this._keyframes.forEach(function (keyframe, time) { var /** @type {?} */ finalKeyframe = copyStyles(keyframe, true); Object.keys(finalKeyframe).forEach(function (prop) { var /** @type {?} */ value = finalKeyframe[prop]; if (value == _angular_animations.ɵPRE_STYLE) { preStyleProps.add(prop); } else if (value == _angular_animations.AUTO_STYLE) { postStyleProps.add(prop); } }); if (!isEmpty) { finalKeyframe['offset'] = time / _this.duration; } finalKeyframes.push(finalKeyframe); }); var /** @type {?} */ preProps = preStyleProps.size ? iteratorToArray(preStyleProps.values()) : []; var /** @type {?} */ postProps = postStyleProps.size ? iteratorToArray(postStyleProps.values()) : []; // special case for a 0-second animation (which is designed just to place styles onscreen) if (isEmpty) { var /** @type {?} */ kf0 = finalKeyframes[0]; var /** @type {?} */ kf1 = copyObj(kf0); kf0['offset'] = 0; kf1['offset'] = 1; finalKeyframes = [kf0, kf1]; } return createTimelineInstruction(this.element, finalKeyframes, preProps, postProps, this.duration, this.startTime, this.easing, false); }; return TimelineBuilder; }()); var SubTimelineBuilder = (function (_super) { __extends(SubTimelineBuilder, _super); /** * @param {?} element * @param {?} keyframes * @param {?} preStyleProps * @param {?} postStyleProps * @param {?} timings * @param {?=} _stretchStartingKeyframe */ function SubTimelineBuilder(element, keyframes, preStyleProps, postStyleProps, timings, _stretchStartingKeyframe) { if (_stretchStartingKeyframe === void 0) { _stretchStartingKeyframe = false; } var _this = _super.call(this, element, timings.delay) || this; _this.element = element; _this.keyframes = keyframes; _this.preStyleProps = preStyleProps; _this.postStyleProps = postStyleProps; _this._stretchStartingKeyframe = _stretchStartingKeyframe; _this.timings = { duration: timings.duration, delay: timings.delay, easing: timings.easing }; return _this; } /** * @return {?} */ SubTimelineBuilder.prototype.containsAnimation = function () { return this.keyframes.length > 1; }; /** * @return {?} */ SubTimelineBuilder.prototype.buildKeyframes = function () { var /** @type {?} */ keyframes = this.keyframes; var _a = this.timings, delay = _a.delay, duration = _a.duration, easing = _a.easing; if (this._stretchStartingKeyframe && delay) { var /** @type {?} */ newKeyframes = []; var /** @type {?} */ totalTime = duration + delay; var /** @type {?} */ startingGap = delay / totalTime; // the original starting keyframe now starts once the delay is done var /** @type {?} */ newFirstKeyframe = copyStyles(keyframes[0], false); newFirstKeyframe['offset'] = 0; newKeyframes.push(newFirstKeyframe); var /** @type {?} */ oldFirstKeyframe = copyStyles(keyframes[0], false); oldFirstKeyframe['offset'] = roundOffset(startingGap); newKeyframes.push(oldFirstKeyframe); /* When the keyframe is stretched then it means that the delay before the animation starts is gone. Instead the first keyframe is placed at the start of the animation and it is then copied to where it starts when the original delay is over. This basically means nothing animates during that delay, but the styles are still renderered. For this to work the original offset values that exist in the original keyframes must be "warped" so that they can take the new keyframe + delay into account. delay=1000, duration=1000, keyframes = 0 .5 1 turns into delay=0, duration=2000, keyframes = 0 .33 .66 1 */ // offsets between 1 ... n -1 are all warped by the keyframe stretch var /** @type {?} */ limit = keyframes.length - 1; for (var /** @type {?} */ i = 1; i <= limit; i++) { var /** @type {?} */ kf = copyStyles(keyframes[i], false); var /** @type {?} */ oldOffset = (kf['offset']); var /** @type {?} */ timeAtKeyframe = delay + oldOffset * duration; kf['offset'] = roundOffset(timeAtKeyframe / totalTime); newKeyframes.push(kf); } // the new starting keyframe should be added at the start duration = totalTime; delay = 0; easing = ''; keyframes = newKeyframes; } return createTimelineInstruction(this.element, keyframes, this.preStyleProps, this.postStyleProps, duration, delay, easing, true); }; return SubTimelineBuilder; }(TimelineBuilder)); /** * @param {?} offset * @param {?=} decimalPoints * @return {?} */ function roundOffset(offset, decimalPoints) { if (decimalPoints === void 0) { decimalPoints = 3; } var /** @type {?} */ mult = Math.pow(10, decimalPoints - 1); return Math.round(offset * mult) / mult; } /** * @param {?} input * @param {?} allStyles * @return {?} */ function flattenStyles(input, allStyles) { var /** @type {?} */ styles = {}; var /** @type {?} */ allProperties; input.forEach(function (token) { if (token === '*') { allProperties = allProperties || Object.keys(allStyles); allProperties.forEach(function (prop) { styles[prop] = _angular_animations.AUTO_STYLE; }); } else { copyStyles(/** @type {?} */ (token), false, styles); } }); return styles; } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var Animation = (function () { /** * @param {?} _driver * @param {?} input */ function Animation(_driver, input) { this._driver = _driver; var errors = []; var ast = buildAnimationAst(input, errors); if (errors.length) { var errorMessage = "animation validation failed:\n" + errors.join("\n"); throw new Error(errorMessage); } this._animationAst = ast; } /** * @param {?} element * @param {?} startingStyles * @param {?} destinationStyles * @param {?} options * @param {?=} subInstructions * @return {?} */ Animation.prototype.buildTimelines = function (element, startingStyles, destinationStyles, options, subInstructions) { var /** @type {?} */ start = Array.isArray(startingStyles) ? normalizeStyles(startingStyles) : (startingStyles); var /** @type {?} */ dest = Array.isArray(destinationStyles) ? normalizeStyles(destinationStyles) : (destinationStyles); var /** @type {?} */ errors = []; subInstructions = subInstructions || new ElementInstructionMap(); var /** @type {?} */ result = buildAnimationTimelines(this._driver, element, this._animationAst, start, dest, options, subInstructions, errors); if (errors.length) { var /** @type {?} */ errorMessage = "animation building failed:\n" + errors.join("\n"); throw new Error(errorMessage); } return result; }; return Animation; }()); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @experimental Animation support is experimental. */ /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var AnimationStyleNormalizer = (function () { function AnimationStyleNormalizer() { } return AnimationStyleNormalizer; }()); /** * @experimental Animation support is experimental. */ var NoopAnimationStyleNormalizer = (function () { function NoopAnimationStyleNormalizer() { } NoopAnimationStyleNormalizer.prototype.normalizePropertyName = function (propertyName, errors) { return propertyName; }; NoopAnimationStyleNormalizer.prototype.normalizeStyleValue = function (userProvidedProperty, normalizedProperty, value, errors) { return value; }; return NoopAnimationStyleNormalizer; }()); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var WebAnimationsStyleNormalizer = (function (_super) { __extends(WebAnimationsStyleNormalizer, _super); function WebAnimationsStyleNormalizer() { return _super !== null && _super.apply(this, arguments) || this; } /** * @param {?} propertyName * @param {?} errors * @return {?} */ WebAnimationsStyleNormalizer.prototype.normalizePropertyName = function (propertyName, errors) { return dashCaseToCamelCase(propertyName); }; /** * @param {?} userProvidedProperty * @param {?} normalizedProperty * @param {?} value * @param {?} errors * @return {?} */ WebAnimationsStyleNormalizer.prototype.normalizeStyleValue = function (userProvidedProperty, normalizedProperty, value, errors) { var /** @type {?} */ unit = ''; var /** @type {?} */ strVal = value.toString().trim(); if (DIMENSIONAL_PROP_MAP[normalizedProperty] && value !== 0 && value !== '0') { if (typeof value === 'number') { unit = 'px'; } else { var /** @type {?} */ valAndSuffixMatch = value.match(/^[+-]?[\d\.]+([a-z]*)$/); if (valAndSuffixMatch && valAndSuffixMatch[1].length == 0) { errors.push("Please provide a CSS unit value for " + userProvidedProperty + ":" + value); } } } return strVal + unit; }; return WebAnimationsStyleNormalizer; }(AnimationStyleNormalizer)); var DIMENSIONAL_PROP_MAP = makeBooleanMap('width,height,minWidth,minHeight,maxWidth,maxHeight,left,top,bottom,right,fontSize,outlineWidth,outlineOffset,paddingTop,paddingLeft,paddingBottom,paddingRight,marginTop,marginLeft,marginBottom,marginRight,borderRadius,borderWidth,borderTopWidth,borderLeftWidth,borderRightWidth,borderBottomWidth,textIndent,perspective' .split(',')); /** * @param {?} keys * @return {?} */ function makeBooleanMap(keys) { var /** @type {?} */ map = {}; keys.forEach(function (key) { return map[key] = true; }); return map; } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @param {?} element * @param {?} triggerName * @param {?} fromState * @param {?} toState * @param {?} isRemovalTransition * @param {?} fromStyles * @param {?} toStyles * @param {?} timelines * @param {?} queriedElements * @param {?} preStyleProps * @param {?} postStyleProps * @param {?=} errors * @return {?} */ function createTransitionInstruction(element, triggerName, fromState, toState, isRemovalTransition, fromStyles, toStyles, timelines, queriedElements, preStyleProps, postStyleProps, errors) { return { type: 0 /* TransitionAnimation */, element: element, triggerName: triggerName, isRemovalTransition: isRemovalTransition, fromState: fromState, fromStyles: fromStyles, toState: toState, toStyles: toStyles, timelines: timelines, queriedElements: queriedElements, preStyleProps: preStyleProps, postStyleProps: postStyleProps, errors: errors }; } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var EMPTY_OBJECT = {}; var AnimationTransitionFactory = (function () { /** * @param {?} _triggerName * @param {?} ast * @param {?} _stateStyles */ function AnimationTransitionFactory(_triggerName, ast, _stateStyles) { this._triggerName = _triggerName; this.ast = ast; this._stateStyles = _stateStyles; } /** * @param {?} currentState * @param {?} nextState * @return {?} */ AnimationTransitionFactory.prototype.match = function (currentState, nextState) { return oneOrMoreTransitionsMatch(this.ast.matchers, currentState, nextState); }; /** * @param {?} stateName * @param {?} params * @param {?} errors * @return {?} */ AnimationTransitionFactory.prototype.buildStyles = function (stateName, params, errors) { var /** @type {?} */ backupStateStyler = this._stateStyles['*']; var /** @type {?} */ stateStyler = this._stateStyles[stateName]; var /** @type {?} */ backupStyles = backupStateStyler ? backupStateStyler.buildStyles(params, errors) : {}; return stateStyler ? stateStyler.buildStyles(params, errors) : backupStyles; }; /** * @param {?} driver * @param {?} element * @param {?} currentState * @param {?} nextState * @param {?=} currentOptions * @param {?=} nextOptions * @param {?=} subInstructions * @return {?} */ AnimationTransitionFactory.prototype.build = function (driver, element, currentState, nextState, currentOptions, nextOptions, subInstructions) { var /** @type {?} */ errors = []; var /** @type {?} */ transitionAnimationParams = this.ast.options && this.ast.options.params || EMPTY_OBJECT; var /** @type {?} */ currentAnimationParams = currentOptions && currentOptions.params || EMPTY_OBJECT; var /** @type {?} */ currentStateStyles = this.buildStyles(currentState, currentAnimationParams, errors); var /** @type {?} */ nextAnimationParams = nextOptions && nextOptions.params || EMPTY_OBJECT; var /** @type {?} */ nextStateStyles = this.buildStyles(nextState, nextAnimationParams, errors); var /** @type {?} */ queriedElements = new Set(); var /** @type {?} */ preStyleMap = new Map(); var /** @type {?} */ postStyleMap = new Map(); var /** @type {?} */ isRemoval = nextState === 'void'; var /** @type {?} */ animationOptions = { params: Object.assign({}, transitionAnimationParams, nextAnimationParams) }; var /** @type {?} */ timelines = buildAnimationTimelines(driver, element, this.ast.animation, currentStateStyles, nextStateStyles, animationOptions, subInstructions, errors); if (errors.length) { return createTransitionInstruction(element, this._triggerName, currentState, nextState, isRemoval, currentStateStyles, nextStateStyles, [], [], preStyleMap, postStyleMap, errors); } timelines.forEach(function (tl) { var /** @type {?} */ elm = tl.element; var /** @type {?} */ preProps = getOrSetAsInMap(preStyleMap, elm, {}); tl.preStyleProps.forEach(function (prop) { return preProps[prop] = true; }); var /** @type {?} */ postProps = getOrSetAsInMap(postStyleMap, elm, {}); tl.postStyleProps.forEach(function (prop) { return postProps[prop] = true; }); if (elm !== element) { queriedElements.add(elm); } }); var /** @type {?} */ queriedElementsList = iteratorToArray(queriedElements.values()); return createTransitionInstruction(element, this._triggerName, currentState, nextState, isRemoval, currentStateStyles, nextStateStyles, timelines, queriedElementsList, preStyleMap, postStyleMap); }; return AnimationTransitionFactory; }()); /** * @param {?} matchFns * @param {?} currentState * @param {?} nextState * @return {?} */ function oneOrMoreTransitionsMatch(matchFns, currentState, nextState) { return matchFns.some(function (fn) { return fn(currentState, nextState); }); } var AnimationStateStyles = (function () { /** * @param {?} styles * @param {?} defaultParams */ function AnimationStateStyles(styles, defaultParams) { this.styles = styles; this.defaultParams = defaultParams; } /** * @param {?} params * @param {?} errors * @return {?} */ AnimationStateStyles.prototype.buildStyles = function (params, errors) { var /** @type {?} */ finalStyles = {}; var /** @type {?} */ combinedParams = copyObj(this.defaultParams); Object.keys(params).forEach(function (key) { var /** @type {?} */ value = params[key]; if (value != null) { combinedParams[key] = value; } }); this.styles.styles.forEach(function (value) { if (typeof value !== 'string') { var /** @type {?} */ styleObj_1 = (value); Object.keys(styleObj_1).forEach(function (prop) { var /** @type {?} */ val = styleObj_1[prop]; if (val.length > 1) { val = interpolateParams(val, combinedParams, errors); } finalStyles[prop] = val; }); } }); return finalStyles; }; return AnimationStateStyles; }()); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * \@experimental Animation support is experimental. * @param {?} name * @param {?} ast * @return {?} */ function buildTrigger(name, ast) { return new AnimationTrigger(name, ast); } /** * \@experimental Animation support is experimental. */ var AnimationTrigger = (function () { /** * @param {?} name * @param {?} ast */ function AnimationTrigger(name, ast) { var _this = this; this.name = name; this.ast = ast; this.transitionFactories = []; this.states = {}; ast.states.forEach(function (ast) { var defaultParams = (ast.options && ast.options.params) || {}; _this.states[ast.name] = new AnimationStateStyles(ast.style, defaultParams); }); balanceProperties(this.states, 'true', '1'); balanceProperties(this.states, 'false', '0'); ast.transitions.forEach(function (ast) { _this.transitionFactories.push(new AnimationTransitionFactory(name, ast, _this.states)); }); this.fallbackTransition = createFallbackTransition(name, this.states); } Object.defineProperty(AnimationTrigger.prototype, "containsQueries", { /** * @return {?} */ get: function () { return this.ast.queryCount > 0; }, enumerable: true, configurable: true }); /** * @param {?} currentState * @param {?} nextState * @return {?} */ AnimationTrigger.prototype.matchTransition = function (currentState, nextState) { var /** @type {?} */ entry = this.transitionFactories.find(function (f) { return f.match(currentState, nextState); }); return entry || null; }; /** * @param {?} currentState * @param {?} params * @param {?} errors * @return {?} */ AnimationTrigger.prototype.matchStyles = function (currentState, params, errors) { return this.fallbackTransition.buildStyles(currentState, params, errors); }; return AnimationTrigger; }()); /** * @param {?} triggerName * @param {?} states * @return {?} */ function createFallbackTransition(triggerName, states) { var /** @type {?} */ matchers = [function (fromState, toState) { return true; }]; var /** @type {?} */ animation = new SequenceAst([]); var /** @type {?} */ transition = new TransitionAst(matchers, animation); return new AnimationTransitionFactory(triggerName, transition, states); } /** * @param {?} obj * @param {?} key1 * @param {?} key2 * @return {?} */ function balanceProperties(obj, key1, key2) { if (obj.hasOwnProperty(key1)) { if (!obj.hasOwnProperty(key2)) { obj[key2] = obj[key1]; } } else if (obj.hasOwnProperty(key2)) { obj[key1] = obj[key2]; } } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var EMPTY_INSTRUCTION_MAP = new ElementInstructionMap(); var TimelineAnimationEngine = (function () { /** * @param {?} _driver * @param {?} _normalizer */ function TimelineAnimationEngine(_driver, _normalizer) { this._driver = _driver; this._normalizer = _normalizer; this._animations = {}; this._playersById = {}; this.players = []; } /** * @param {?} id * @param {?} metadata * @return {?} */ TimelineAnimationEngine.prototype.register = function (id, metadata) { var /** @type {?} */ errors = []; var /** @type {?} */ ast = buildAnimationAst(metadata, errors); if (errors.length) { throw new Error("Unable to build the animation due to the following errors: " + errors.join("\n")); } else { this._animations[id] = ast; } }; /** * @param {?} i * @param {?} preStyles * @param {?=} postStyles * @return {?} */ TimelineAnimationEngine.prototype._buildPlayer = function (i, preStyles, postStyles) { var /** @type {?} */ element = i.element; var /** @type {?} */ keyframes = normalizeKeyframes(this._driver, this._normalizer, element, i.keyframes, preStyles, postStyles); return this._driver.animate(element, keyframes, i.duration, i.delay, i.easing, []); }; /** * @param {?} id * @param {?} element * @param {?=} options * @return {?} */ TimelineAnimationEngine.prototype.create = function (id, element, options) { var _this = this; if (options === void 0) { options = {}; } var /** @type {?} */ errors = []; var /** @type {?} */ ast = this._animations[id]; var /** @type {?} */ instructions; var /** @type {?} */ autoStylesMap = new Map(); if (ast) { instructions = buildAnimationTimelines(this._driver, element, ast, {}, {}, options, EMPTY_INSTRUCTION_MAP, errors); instructions.forEach(function (inst) { var /** @type {?} */ styles = getOrSetAsInMap(autoStylesMap, inst.element, {}); inst.postStyleProps.forEach(function (prop) { return styles[prop] = null; }); }); } else { errors.push('The requested animation doesn\'t exist or has already been destroyed'); instructions = []; } if (errors.length) { throw new Error("Unable to create the animation due to the following errors: " + errors.join("\n")); } autoStylesMap.forEach(function (styles, element) { Object.keys(styles).forEach(function (prop) { styles[prop] = _this._driver.computeStyle(element, prop, _angular_animations.AUTO_STYLE); }); }); var /** @type {?} */ players = instructions.map(function (i) { var /** @type {?} */ styles = autoStylesMap.get(i.element); return _this._buildPlayer(i, {}, styles); }); var /** @type {?} */ player = optimizeGroupPlayer(players); this._playersById[id] = player; player.onDestroy(function () { return _this.destroy(id); }); this.players.push(player); return player; }; /** * @param {?} id * @return {?} */ TimelineAnimationEngine.prototype.destroy = function (id) { var /** @type {?} */ player = this._getPlayer(id); player.destroy(); delete this._playersById[id]; var /** @type {?} */ index = this.players.indexOf(player); if (index >= 0) { this.players.splice(index, 1); } }; /** * @param {?} id * @return {?} */ TimelineAnimationEngine.prototype._getPlayer = function (id) { var /** @type {?} */ player = this._playersById[id]; if (!player) { throw new Error("Unable to find the timeline player referenced by " + id); } return player; }; /** * @param {?} id * @param {?} element * @param {?} eventName * @param {?} callback * @return {?} */ TimelineAnimationEngine.prototype.listen = function (id, element, eventName, callback) { // triggerName, fromState, toState are all ignored for timeline animations var /** @type {?} */ baseEvent = makeAnimationEvent(element, '', '', ''); listenOnPlayer(this._getPlayer(id), eventName, baseEvent, callback); return function () { }; }; /** * @param {?} id * @param {?} element * @param {?} command * @param {?} args * @return {?} */ TimelineAnimationEngine.prototype.command = function (id, element, command, args) { if (command == 'register') { this.register(id, /** @type {?} */ (args[0])); return; } if (command == 'create') { var /** @type {?} */ options = ((args[0] || {})); this.create(id, element, options); return; } var /** @type {?} */ player = this._getPlayer(id); switch (command) { case 'play': player.play(); break; case 'pause': player.pause(); break; case 'reset': player.reset(); break; case 'restart': player.restart(); break; case 'finish': player.finish(); break; case 'init': player.init(); break; case 'setPosition': player.setPosition(parseFloat(/** @type {?} */ (args[0]))); break; case 'destroy': this.destroy(id); break; } }; return TimelineAnimationEngine; }()); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var QUEUED_CLASSNAME = 'ng-animate-queued'; var QUEUED_SELECTOR = '.ng-animate-queued'; var DISABLED_CLASSNAME = 'ng-animate-disabled'; var DISABLED_SELECTOR = '.ng-animate-disabled'; var EMPTY_PLAYER_ARRAY = []; var NULL_REMOVAL_STATE = { namespaceId: '', setForRemoval: null, hasAnimation: false, removedBeforeQueried: false }; var NULL_REMOVED_QUERIED_STATE = { namespaceId: '', setForRemoval: null, hasAnimation: false, removedBeforeQueried: true }; var REMOVAL_FLAG = '__ng_removed'; var StateValue = (function () { /** * @param {?} input */ function StateValue(input) { var isObj = input && input.hasOwnProperty('value'); var value = isObj ? input['value'] : input; this.value = normalizeTriggerValue(value); if (isObj) { var options = copyObj(input); delete options['value']; this.options = options; } else { this.options = {}; } if (!this.options.params) { this.options.params = {}; } } Object.defineProperty(StateValue.prototype, "params", { /** * @return {?} */ get: function () { return (this.options.params); }, enumerable: true, configurable: true }); /** * @param {?} options * @return {?} */ StateValue.prototype.absorbOptions = function (options) { var /** @type {?} */ newParams = options.params; if (newParams) { var /** @type {?} */ oldParams_2 = ((this.options.params)); Object.keys(newParams).forEach(function (prop) { if (oldParams_2[prop] == null) { oldParams_2[prop] = newParams[prop]; } }); } }; return StateValue; }()); var VOID_VALUE = 'void'; var DEFAULT_STATE_VALUE = new StateValue(VOID_VALUE); var DELETED_STATE_VALUE = new StateValue('DELETED'); var AnimationTransitionNamespace = (function () { /** * @param {?} id * @param {?} hostElement * @param {?} _engine */ function AnimationTransitionNamespace(id, hostElement, _engine) { this.id = id; this.hostElement = hostElement; this._engine = _engine; this.players = []; this._triggers = {}; this._queue = []; this._elementListeners = new Map(); this._hostClassName = 'ng-tns-' + id; addClass(hostElement, this._hostClassName); } /** * @param {?} element * @param {?} name * @param {?} phase * @param {?} callback * @return {?} */ AnimationTransitionNamespace.prototype.listen = function (element, name, phase, callback) { var _this = this; if (!this._triggers.hasOwnProperty(name)) { throw new Error("Unable to listen on the animation trigger event \"" + phase + "\" because the animation trigger \"" + name + "\" doesn't exist!"); } if (phase == null || phase.length == 0) { throw new Error("Unable to listen on the animation trigger \"" + name + "\" because the provided event is undefined!"); } if (!isTriggerEventValid(phase)) { throw new Error("The provided animation trigger event \"" + phase + "\" for the animation trigger \"" + name + "\" is not supported!"); } var /** @type {?} */ listeners = getOrSetAsInMap(this._elementListeners, element, []); var /** @type {?} */ data = { name: name, phase: phase, callback: callback }; listeners.push(data); var /** @type {?} */ triggersWithStates = getOrSetAsInMap(this._engine.statesByElement, element, {}); if (!triggersWithStates.hasOwnProperty(name)) { addClass(element, NG_TRIGGER_CLASSNAME); addClass(element, NG_TRIGGER_CLASSNAME + '-' + name); triggersWithStates[name] = null; } return function () { // the event listener is removed AFTER the flush has occurred such // that leave animations callbacks can fire (otherwise if the node // is removed in between then the listeners would be deregistered) _this._engine.afterFlush(function () { var /** @type {?} */ index = listeners.indexOf(data); if (index >= 0) { listeners.splice(index, 1); } if (!_this._triggers[name]) { delete triggersWithStates[name]; } }); }; }; /** * @param {?} name * @param {?} ast * @return {?} */ AnimationTransitionNamespace.prototype.register = function (name, ast) { if (this._triggers[name]) { // throw return false; } else { this._triggers[name] = ast; return true; } }; /** * @param {?} name * @return {?} */ AnimationTransitionNamespace.prototype._getTrigger = function (name) { var /** @type {?} */ trigger = this._triggers[name]; if (!trigger) { throw new Error("The provided animation trigger \"" + name + "\" has not been registered!"); } return trigger; }; /** * @param {?} element * @param {?} triggerName * @param {?} value * @param {?=} defaultToFallback * @return {?} */ AnimationTransitionNamespace.prototype.trigger = function (element, triggerName, value, defaultToFallback) { var _this = this; if (defaultToFallback === void 0) { defaultToFallback = true; } var /** @type {?} */ trigger = this._getTrigger(triggerName); var /** @type {?} */ player = new TransitionAnimationPlayer(this.id, triggerName, element); var /** @type {?} */ triggersWithStates = this._engine.statesByElement.get(element); if (!triggersWithStates) { addClass(element, NG_TRIGGER_CLASSNAME); addClass(element, NG_TRIGGER_CLASSNAME + '-' + triggerName); this._engine.statesByElement.set(element, triggersWithStates = {}); } var /** @type {?} */ fromState = triggersWithStates[triggerName]; var /** @type {?} */ toState = new StateValue(value); var /** @type {?} */ isObj = value && value.hasOwnProperty('value'); if (!isObj && fromState) { toState.absorbOptions(fromState.options); } triggersWithStates[triggerName] = toState; if (!fromState) { fromState = DEFAULT_STATE_VALUE; } else if (fromState === DELETED_STATE_VALUE) { return player; } var /** @type {?} */ isRemoval = toState.value === VOID_VALUE; // normally this isn't reached by here, however, if an object expression // is passed in then it may be a new object each time. Comparing the value // is important since that will stay the same despite there being a new object. // The removal arc here is special cased because the same element is triggered // twice in the event that it contains animations on the outer/inner portions // of the host container if (!isRemoval && fromState.value === toState.value) { // this means that despite the value not changing, some inner params // have changed which means that the animation final styles need to be applied if (!objEquals(fromState.params, toState.params)) { var /** @type {?} */ errors = []; var /** @type {?} */ fromStyles_1 = trigger.matchStyles(fromState.value, fromState.params, errors); var /** @type {?} */ toStyles_1 = trigger.matchStyles(toState.value, toState.params, errors); if (errors.length) { this._engine.reportError(errors); } else { this._engine.afterFlush(function () { eraseStyles(element, fromStyles_1); setStyles(element, toStyles_1); }); } } return; } var /** @type {?} */ playersOnElement = getOrSetAsInMap(this._engine.playersByElement, element, []); playersOnElement.forEach(function (player) { // only remove the player if it is queued on the EXACT same trigger/namespace // we only also deal with queued players here because if the animation has // started then we want to keep the player alive until the flush happens // (which is where the previousPlayers are passed into the new palyer) if (player.namespaceId == _this.id && player.triggerName == triggerName && player.queued) { player.destroy(); } }); var /** @type {?} */ transition = trigger.matchTransition(fromState.value, toState.value); var /** @type {?} */ isFallbackTransition = false; if (!transition) { if (!defaultToFallback) return; transition = trigger.fallbackTransition; isFallbackTransition = true; } this._engine.totalQueuedPlayers++; this._queue.push({ element: element, triggerName: triggerName, transition: transition, fromState: fromState, toState: toState, player: player, isFallbackTransition: isFallbackTransition }); if (!isFallbackTransition) { addClass(element, QUEUED_CLASSNAME); player.onStart(function () { removeClass(element, QUEUED_CLASSNAME); }); } player.onDone(function () { var /** @type {?} */ index = _this.players.indexOf(player); if (index >= 0) { _this.players.splice(index, 1); } var /** @type {?} */ players = _this._engine.playersByElement.get(element); if (players) { var /** @type {?} */ index_1 = players.indexOf(player); if (index_1 >= 0) { players.splice(index_1, 1); } } }); this.players.push(player); playersOnElement.push(player); return player; }; /** * @param {?} name * @return {?} */ AnimationTransitionNamespace.prototype.deregister = function (name) { var _this = this; delete this._triggers[name]; this._engine.statesByElement.forEach(function (stateMap, element) { delete stateMap[name]; }); this._elementListeners.forEach(function (listeners, element) { _this._elementListeners.set(element, listeners.filter(function (entry) { return entry.name != name; })); }); }; /** * @param {?} element * @return {?} */ AnimationTransitionNamespace.prototype.clearElementCache = function (element) { this._engine.statesByElement.delete(element); this._elementListeners.delete(element); var /** @type {?} */ elementPlayers = this._engine.playersByElement.get(element); if (elementPlayers) { elementPlayers.forEach(function (player) { return player.destroy(); }); this._engine.playersByElement.delete(element); } }; /** * @param {?} rootElement * @param {?} context * @param {?=} animate * @return {?} */ AnimationTransitionNamespace.prototype._destroyInnerNodes = function (rootElement, context, animate) { var _this = this; if (animate === void 0) { animate = false; } this._engine.driver.query(rootElement, NG_TRIGGER_SELECTOR, true).forEach(function (elm) { if (animate && containsClass(elm, _this._hostClassName)) { var /** @type {?} */ innerNs = _this._engine.namespacesByHostElement.get(elm); // special case for a host element with animations on the same element if (innerNs) { innerNs.removeNode(elm, context, true); } _this.removeNode(elm, context, true); } else { _this.clearElementCache(elm); } }); }; /** * @param {?} element * @param {?} context * @param {?=} doNotRecurse * @return {?} */ AnimationTransitionNamespace.prototype.removeNode = function (element, context, doNotRecurse) { var _this = this; var /** @type {?} */ engine = this._engine; if (!doNotRecurse && element.childElementCount) { this._destroyInnerNodes(element, context, true); } var /** @type {?} */ triggerStates = engine.statesByElement.get(element); if (triggerStates) { var /** @type {?} */ players_1 = []; Object.keys(triggerStates).forEach(function (triggerName) { // this check is here in the event that an element is removed // twice (both on the host level and the component level) if (_this._triggers[triggerName]) { var /** @type {?} */ player = _this.trigger(element, triggerName, VOID_VALUE, false); if (player) { players_1.push(player); } } }); if (players_1.length) { engine.markElementAsRemoved(this.id, element, true, context); optimizeGroupPlayer(players_1).onDone(function () { return engine.processLeaveNode(element); }); return; } } // find the player that is animating and make sure that the // removal is delayed until that player has completed var /** @type {?} */ containsPotentialParentTransition = false; if (engine.totalAnimations) { var /** @type {?} */ currentPlayers = engine.players.length ? engine.playersByQueriedElement.get(element) : []; // when this `if statement` does not continue forward it means that // a previous animation query has selected the current element and // is animating it. In this situation want to continue fowards and // allow the element to be queued up for animation later. if (currentPlayers && currentPlayers.length) { containsPotentialParentTransition = true; } else { var /** @type {?} */ parent = element; while (parent = parent.parentNode) { var /** @type {?} */ triggers = engine.statesByElement.get(parent); if (triggers) { containsPotentialParentTransition = true; break; } } } } // at this stage we know that the element will either get removed // during flush or will be picked up by a parent query. Either way // we need to fire the listeners for this element when it DOES get // removed (once the query parent animation is done or after flush) var /** @type {?} */ listeners = this._elementListeners.get(element); if (listeners) { var /** @type {?} */ visitedTriggers_1 = new Set(); listeners.forEach(function (listener) { var /** @type {?} */ triggerName = listener.name; if (visitedTriggers_1.has(triggerName)) return; visitedTriggers_1.add(triggerName); var /** @type {?} */ trigger = _this._triggers[triggerName]; var /** @type {?} */ transition = trigger.fallbackTransition; var /** @type {?} */ elementStates = ((engine.statesByElement.get(element))); var /** @type {?} */ fromState = elementStates[triggerName] || DEFAULT_STATE_VALUE; var /** @type {?} */ toState = new StateValue(VOID_VALUE); var /** @type {?} */ player = new TransitionAnimationPlayer(_this.id, triggerName, element); _this._engine.totalQueuedPlayers++; _this._queue.push({ element: element, triggerName: triggerName, transition: transition, fromState: fromState, toState: toState, player: player, isFallbackTransition: true }); }); } // whether or not a parent has an animation we need to delay the deferral of the leave // operation until we have more information (which we do after flush() has been called) if (containsPotentialParentTransition) { engine.markElementAsRemoved(this.id, element, false, context); } else { // we do this after the flush has occurred such // that the callbacks can be fired engine.afterFlush(function () { return _this.clearElementCache(element); }); engine.destroyInnerAnimations(element); engine._onRemovalComplete(element, context); } }; /** * @param {?} element * @param {?} parent * @return {?} */ AnimationTransitionNamespace.prototype.insertNode = function (element, parent) { addClass(element, this._hostClassName); }; /** * @param {?} microtaskId * @return {?} */ AnimationTransitionNamespace.prototype.drainQueuedTransitions = function (microtaskId) { var _this = this; var /** @type {?} */ instructions = []; this._queue.forEach(function (entry) { var /** @type {?} */ player = entry.player; if (player.destroyed) return; var /** @type {?} */ element = entry.element; var /** @type {?} */ listeners = _this._elementListeners.get(element); if (listeners) { listeners.forEach(function (listener) { if (listener.name == entry.triggerName) { var /** @type {?} */ baseEvent = makeAnimationEvent(element, entry.triggerName, entry.fromState.value, entry.toState.value); ((baseEvent))['_data'] = microtaskId; listenOnPlayer(entry.player, listener.phase, baseEvent, listener.callback); } }); } if (player.markedForDestroy) { _this._engine.afterFlush(function () { // now we can destroy the element properly since the event listeners have // been bound to the player player.destroy(); }); } else { instructions.push(entry); } }); this._queue = []; return instructions.sort(function (a, b) { // if depCount == 0 them move to front // otherwise if a contains b then move back var /** @type {?} */ d0 = a.transition.ast.depCount; var /** @type {?} */ d1 = b.transition.ast.depCount; if (d0 == 0 || d1 == 0) { return d0 - d1; } return _this._engine.driver.containsElement(a.element, b.element) ? 1 : -1; }); }; /** * @param {?} context * @return {?} */ AnimationTransitionNamespace.prototype.destroy = function (context) { this.players.forEach(function (p) { return p.destroy(); }); this._destroyInnerNodes(this.hostElement, context); }; /** * @param {?} element * @return {?} */ AnimationTransitionNamespace.prototype.elementContainsData = function (element) { var /** @type {?} */ containsData = false; if (this._elementListeners.has(element)) containsData = true; containsData = (this._queue.find(function (entry) { return entry.element === element; }) ? true : false) || containsData; return containsData; }; return AnimationTransitionNamespace; }()); var TransitionAnimationEngine = (function () { /** * @param {?} driver * @param {?} _normalizer */ function TransitionAnimationEngine(driver, _normalizer) { this.driver = driver; this._normalizer = _normalizer; this.players = []; this.newHostElements = new Map(); this.playersByElement = new Map(); this.playersByQueriedElement = new Map(); this.statesByElement = new Map(); this.disabledNodes = new Set(); this.totalAnimations = 0; this.totalQueuedPlayers = 0; this._namespaceLookup = {}; this._namespaceList = []; this._flushFns = []; this._whenQuietFns = []; this.namespacesByHostElement = new Map(); this.collectedEnterElements = []; this.collectedLeaveElements = []; this.onRemovalComplete = function (element, context) { }; } /** * @param {?} element * @param {?} context * @return {?} */ TransitionAnimationEngine.prototype._onRemovalComplete = function (element, context) { this.onRemovalComplete(element, context); }; Object.defineProperty(TransitionAnimationEngine.prototype, "queuedPlayers", { /** * @return {?} */ get: function () { var /** @type {?} */ players = []; this._namespaceList.forEach(function (ns) { ns.players.forEach(function (player) { if (player.queued) { players.push(player); } }); }); return players; }, enumerable: true, configurable: true }); /** * @param {?} namespaceId * @param {?} hostElement * @return {?} */ TransitionAnimationEngine.prototype.createNamespace = function (namespaceId, hostElement) { var /** @type {?} */ ns = new AnimationTransitionNamespace(namespaceId, hostElement, this); if (hostElement.parentNode) { this._balanceNamespaceList(ns, hostElement); } else { // defer this later until flush during when the host element has // been inserted so that we know exactly where to place it in // the namespace list this.newHostElements.set(hostElement, ns); // given that this host element is apart of the animation code, it // may or may not be inserted by a parent node that is an of an // animation renderer type. If this happens then we can still have // access to this item when we query for :enter nodes. If the parent // is a renderer then the set data-structure will normalize the entry this.collectEnterElement(hostElement); } return this._namespaceLookup[namespaceId] = ns; }; /** * @param {?} ns * @param {?} hostElement * @return {?} */ TransitionAnimationEngine.prototype._balanceNamespaceList = function (ns, hostElement) { var /** @type {?} */ limit = this._namespaceList.length - 1; if (limit >= 0) { var /** @type {?} */ found = false; for (var /** @type {?} */ i = limit; i >= 0; i--) { var /** @type {?} */ nextNamespace = this._namespaceList[i]; if (this.driver.containsElement(nextNamespace.hostElement, hostElement)) { this._namespaceList.splice(i + 1, 0, ns); found = true; break; } } if (!found) { this._namespaceList.splice(0, 0, ns); } } else { this._namespaceList.push(ns); } this.namespacesByHostElement.set(hostElement, ns); return ns; }; /** * @param {?} namespaceId * @param {?} hostElement * @return {?} */ TransitionAnimationEngine.prototype.register = function (namespaceId, hostElement) { var /** @type {?} */ ns = this._namespaceLookup[namespaceId]; if (!ns) { ns = this.createNamespace(namespaceId, hostElement); } return ns; }; /** * @param {?} namespaceId * @param {?} name * @param {?} trigger * @return {?} */ TransitionAnimationEngine.prototype.registerTrigger = function (namespaceId, name, trigger) { var /** @type {?} */ ns = this._namespaceLookup[namespaceId]; if (ns && ns.register(name, trigger)) { this.totalAnimations++; } }; /** * @param {?} namespaceId * @param {?} context * @return {?} */ TransitionAnimationEngine.prototype.destroy = function (namespaceId, context) { var _this = this; if (!namespaceId) return; var /** @type {?} */ ns = this._fetchNamespace(namespaceId); this.afterFlush(function () { _this.namespacesByHostElement.delete(ns.hostElement); delete _this._namespaceLookup[namespaceId]; var /** @type {?} */ index = _this._namespaceList.indexOf(ns); if (index >= 0) { _this._namespaceList.splice(index, 1); } }); this.afterFlushAnimationsDone(function () { return ns.destroy(context); }); }; /** * @param {?} id * @return {?} */ TransitionAnimationEngine.prototype._fetchNamespace = function (id) { return this._namespaceLookup[id]; }; /** * @param {?} namespaceId * @param {?} element * @param {?} name * @param {?} value * @return {?} */ TransitionAnimationEngine.prototype.trigger = function (namespaceId, element, name, value) { if (isElementNode(element)) { this._fetchNamespace(namespaceId).trigger(element, name, value); return true; } return false; }; /** * @param {?} namespaceId * @param {?} element * @param {?} parent * @param {?} insertBefore * @return {?} */ TransitionAnimationEngine.prototype.insertNode = function (namespaceId, element, parent, insertBefore) { if (!isElementNode(element)) return; // special case for when an element is removed and reinserted (move operation) // when this occurs we do not want to use the element for deletion later var /** @type {?} */ details = (element[REMOVAL_FLAG]); if (details && details.setForRemoval) { details.setForRemoval = false; } // in the event that the namespaceId is blank then the caller // code does not contain any animation code in it, but it is // just being called so that the node is marked as being inserted if (namespaceId) { this._fetchNamespace(namespaceId).insertNode(element, parent); } // only *directives and host elements are inserted before if (insertBefore) { this.collectEnterElement(element); } }; /** * @param {?} element * @return {?} */ TransitionAnimationEngine.prototype.collectEnterElement = function (element) { this.collectedEnterElements.push(element); }; /** * @param {?} element * @param {?} value * @return {?} */ TransitionAnimationEngine.prototype.markElementAsDisabled = function (element, value) { if (value) { if (!this.disabledNodes.has(element)) { this.disabledNodes.add(element); addClass(element, DISABLED_CLASSNAME); } } else if (this.disabledNodes.has(element)) { this.disabledNodes.delete(element); removeClass(element, DISABLED_CLASSNAME); } }; /** * @param {?} namespaceId * @param {?} element * @param {?} context * @param {?=} doNotRecurse * @return {?} */ TransitionAnimationEngine.prototype.removeNode = function (namespaceId, element, context, doNotRecurse) { if (!isElementNode(element)) { this._onRemovalComplete(element, context); return; } var /** @type {?} */ ns = namespaceId ? this._fetchNamespace(namespaceId) : null; if (ns) { ns.removeNode(element, context, doNotRecurse); } else { this.markElementAsRemoved(namespaceId, element, false, context); } }; /** * @param {?} namespaceId * @param {?} element * @param {?=} hasAnimation * @param {?=} context * @return {?} */ TransitionAnimationEngine.prototype.markElementAsRemoved = function (namespaceId, element, hasAnimation, context) { this.collectedLeaveElements.push(element); element[REMOVAL_FLAG] = { namespaceId: namespaceId, setForRemoval: context, hasAnimation: hasAnimation, removedBeforeQueried: false }; }; /** * @param {?} namespaceId * @param {?} element * @param {?} name * @param {?} phase * @param {?} callback * @return {?} */ TransitionAnimationEngine.prototype.listen = function (namespaceId, element, name, phase, callback) { if (isElementNode(element)) { return this._fetchNamespace(namespaceId).listen(element, name, phase, callback); } return function () { }; }; /** * @param {?} entry * @param {?} subTimelines * @return {?} */ TransitionAnimationEngine.prototype._buildInstruction = function (entry, subTimelines) { return entry.transition.build(this.driver, entry.element, entry.fromState.value, entry.toState.value, entry.fromState.options, entry.toState.options, subTimelines); }; /** * @param {?} containerElement * @return {?} */ TransitionAnimationEngine.prototype.destroyInnerAnimations = function (containerElement) { var _this = this; var /** @type {?} */ elements = this.driver.query(containerElement, NG_TRIGGER_SELECTOR, true); elements.forEach(function (element) { var /** @type {?} */ players = _this.playersByElement.get(element); if (players) { players.forEach(function (player) { // special case for when an element is set for destruction, but hasn't started. // in this situation we want to delay the destruction until the flush occurs // so that any event listeners attached to the player are triggered. if (player.queued) { player.markedForDestroy = true; } else { player.destroy(); } }); } var /** @type {?} */ stateMap = _this.statesByElement.get(element); if (stateMap) { Object.keys(stateMap).forEach(function (triggerName) { return stateMap[triggerName] = DELETED_STATE_VALUE; }); } }); if (this.playersByQueriedElement.size == 0) return; elements = this.driver.query(containerElement, NG_ANIMATING_SELECTOR, true); if (elements.length) { elements.forEach(function (element) { var /** @type {?} */ players = _this.playersByQueriedElement.get(element); if (players) { players.forEach(function (player) { return player.finish(); }); } }); } }; /** * @return {?} */ TransitionAnimationEngine.prototype.whenRenderingDone = function () { var _this = this; return new Promise(function (resolve) { if (_this.players.length) { return optimizeGroupPlayer(_this.players).onDone(function () { return resolve(); }); } else { resolve(); } }); }; /** * @param {?} element * @return {?} */ TransitionAnimationEngine.prototype.processLeaveNode = function (element) { var _this = this; var /** @type {?} */ details = (element[REMOVAL_FLAG]); if (details && details.setForRemoval) { // this will prevent it from removing it twice element[REMOVAL_FLAG] = NULL_REMOVAL_STATE; if (details.namespaceId) { this.destroyInnerAnimations(element); var /** @type {?} */ ns = this._fetchNamespace(details.namespaceId); if (ns) { ns.clearElementCache(element); } } this._onRemovalComplete(element, details.setForRemoval); } if (this.driver.matchesElement(element, DISABLED_SELECTOR)) { this.markElementAsDisabled(element, false); } this.driver.query(element, DISABLED_SELECTOR, true).forEach(function (node) { _this.markElementAsDisabled(element, false); }); }; /** * @param {?=} microtaskId * @return {?} */ TransitionAnimationEngine.prototype.flush = function (microtaskId) { var _this = this; if (microtaskId === void 0) { microtaskId = -1; } var /** @type {?} */ players = []; if (this.newHostElements.size) { this.newHostElements.forEach(function (ns, element) { return _this._balanceNamespaceList(ns, element); }); this.newHostElements.clear(); } if (this._namespaceList.length && (this.totalQueuedPlayers || this.collectedLeaveElements.length)) { var /** @type {?} */ cleanupFns = []; try { players = this._flushAnimations(cleanupFns, microtaskId); } finally { for (var /** @type {?} */ i = 0; i < cleanupFns.length; i++) { cleanupFns[i](); } } } else { for (var /** @type {?} */ i = 0; i < this.collectedLeaveElements.length; i++) { var /** @type {?} */ element = this.collectedLeaveElements[i]; this.processLeaveNode(element); } } this.totalQueuedPlayers = 0; this.collectedEnterElements.length = 0; this.collectedLeaveElements.length = 0; this._flushFns.forEach(function (fn) { return fn(); }); this._flushFns = []; if (this._whenQuietFns.length) { // we move these over to a variable so that // if any new callbacks are registered in another // flush they do not populate the existing set var /** @type {?} */ quietFns_1 = this._whenQuietFns; this._whenQuietFns = []; if (players.length) { optimizeGroupPlayer(players).onDone(function () { quietFns_1.forEach(function (fn) { return fn(); }); }); } else { quietFns_1.forEach(function (fn) { return fn(); }); } } }; /** * @param {?} errors * @return {?} */ TransitionAnimationEngine.prototype.reportError = function (errors) { throw new Error("Unable to process animations due to the following failed trigger transitions\n " + errors.join("\n")); }; /** * @param {?} cleanupFns * @param {?} microtaskId * @return {?} */ TransitionAnimationEngine.prototype._flushAnimations = function (cleanupFns, microtaskId) { var _this = this; var /** @type {?} */ subTimelines = new ElementInstructionMap(); var /** @type {?} */ skippedPlayers = []; var /** @type {?} */ skippedPlayersMap = new Map(); var /** @type {?} */ queuedInstructions = []; var /** @type {?} */ queriedElements = new Map(); var /** @type {?} */ allPreStyleElements = new Map(); var /** @type {?} */ allPostStyleElements = new Map(); var /** @type {?} */ disabledElementsSet = new Set(); this.disabledNodes.forEach(function (node) { disabledElementsSet.add(node); var /** @type {?} */ nodesThatAreDisabled = _this.driver.query(node, QUEUED_SELECTOR, true); for (var /** @type {?} */ i = 0; i < nodesThatAreDisabled.length; i++) { disabledElementsSet.add(nodesThatAreDisabled[i]); } }); var /** @type {?} */ bodyNode = getBodyNode(); var /** @type {?} */ allEnterNodes = this.collectedEnterElements.length ? this.collectedEnterElements.filter(createIsRootFilterFn(this.collectedEnterElements)) : []; // this must occur before the instructions are built below such that // the :enter queries match the elements (since the timeline queries // are fired during instruction building). for (var /** @type {?} */ i = 0; i < allEnterNodes.length; i++) { addClass(allEnterNodes[i], ENTER_CLASSNAME); } var /** @type {?} */ allLeaveNodes = []; var /** @type {?} */ leaveNodesWithoutAnimations = new Set(); for (var /** @type {?} */ i = 0; i < this.collectedLeaveElements.length; i++) { var /** @type {?} */ element = this.collectedLeaveElements[i]; var /** @type {?} */ details = (element[REMOVAL_FLAG]); if (details && details.setForRemoval) { addClass(element, LEAVE_CLASSNAME); allLeaveNodes.push(element); if (!details.hasAnimation) { leaveNodesWithoutAnimations.add(element); } } } cleanupFns.push(function () { allEnterNodes.forEach(function (element) { return removeClass(element, ENTER_CLASSNAME); }); allLeaveNodes.forEach(function (element) { removeClass(element, LEAVE_CLASSNAME); _this.processLeaveNode(element); }); }); var /** @type {?} */ allPlayers = []; var /** @type {?} */ erroneousTransitions = []; for (var /** @type {?} */ i = this._namespaceList.length - 1; i >= 0; i--) { var /** @type {?} */ ns = this._namespaceList[i]; ns.drainQueuedTransitions(microtaskId).forEach(function (entry) { var /** @type {?} */ player = entry.player; allPlayers.push(player); var /** @type {?} */ element = entry.element; if (!bodyNode || !_this.driver.containsElement(bodyNode, element)) { player.destroy(); return; } var /** @type {?} */ instruction = ((_this._buildInstruction(entry, subTimelines))); if (instruction.errors && instruction.errors.length) { erroneousTransitions.push(instruction); return; } // if a unmatched transition is queued to go then it SHOULD NOT render // an animation and cancel the previously running animations. if (entry.isFallbackTransition) { player.onStart(function () { return eraseStyles(element, instruction.fromStyles); }); player.onDestroy(function () { return setStyles(element, instruction.toStyles); }); skippedPlayers.push(player); return; } // this means that if a parent animation uses this animation as a sub trigger // then it will instruct the timeline builder to not add a player delay, but // instead stretch the first keyframe gap up until the animation starts. The // reason this is important is to prevent extra initialization styles from being // required by the user in the animation. instruction.timelines.forEach(function (tl) { return tl.stretchStartingKeyframe = true; }); subTimelines.append(element, instruction.timelines); var /** @type {?} */ tuple = { instruction: instruction, player: player, element: element }; queuedInstructions.push(tuple); instruction.queriedElements.forEach(function (element) { return getOrSetAsInMap(queriedElements, element, []).push(player); }); instruction.preStyleProps.forEach(function (stringMap, element) { var /** @type {?} */ props = Object.keys(stringMap); if (props.length) { var /** @type {?} */ setVal_1 = ((allPreStyleElements.get(element))); if (!setVal_1) { allPreStyleElements.set(element, setVal_1 = new Set()); } props.forEach(function (prop) { return setVal_1.add(prop); }); } }); instruction.postStyleProps.forEach(function (stringMap, element) { var /** @type {?} */ props = Object.keys(stringMap); var /** @type {?} */ setVal = ((allPostStyleElements.get(element))); if (!setVal) { allPostStyleElements.set(element, setVal = new Set()); } props.forEach(function (prop) { return setVal.add(prop); }); }); }); } if (erroneousTransitions.length) { var /** @type {?} */ errors_1 = []; erroneousTransitions.forEach(function (instruction) { errors_1.push("@" + instruction.triggerName + " has failed due to:\n"); /** @type {?} */ ((instruction.errors)).forEach(function (error) { return errors_1.push("- " + error + "\n"); }); }); allPlayers.forEach(function (player) { return player.destroy(); }); this.reportError(errors_1); } // these can only be detected here since we have a map of all the elements // that have animations attached to them... We use a set here in the event // multiple enter captures on the same element were caught in different // renderer namespaces (e.g. when a @trigger was on a host binding that had *ngIf) var /** @type {?} */ enterNodesWithoutAnimations = new Set(); for (var /** @type {?} */ i = 0; i < allEnterNodes.length; i++) { var /** @type {?} */ element = allEnterNodes[i]; if (!subTimelines.has(element)) { enterNodesWithoutAnimations.add(element); } } var /** @type {?} */ allPreviousPlayersMap = new Map(); var /** @type {?} */ sortedParentElements = []; queuedInstructions.forEach(function (entry) { var /** @type {?} */ element = entry.element; if (subTimelines.has(element)) { sortedParentElements.unshift(element); _this._beforeAnimationBuild(entry.player.namespaceId, entry.instruction, allPreviousPlayersMap); } }); skippedPlayers.forEach(function (player) { var /** @type {?} */ element = player.element; var /** @type {?} */ previousPlayers = _this._getPreviousPlayers(element, false, player.namespaceId, player.triggerName, null); previousPlayers.forEach(function (prevPlayer) { getOrSetAsInMap(allPreviousPlayersMap, element, []).push(prevPlayer); prevPlayer.destroy(); }); }); // this is a special case for nodes that will be removed (either by) // having their own leave animations or by being queried in a container // that will be removed once a parent animation is complete. The idea // here is that * styles must be identical to ! styles because of // backwards compatibility (* is also filled in by default in many places). // Otherwise * styles will return an empty value or auto since the element // that is being getComputedStyle'd will not be visible (since * = destination) var /** @type {?} */ replaceNodes = allLeaveNodes.filter(function (node) { return replacePostStylesAsPre(node, allPreStyleElements, allPostStyleElements); }); // POST STAGE: fill the * styles var _a = cloakAndComputeStyles(this.driver, leaveNodesWithoutAnimations, allPostStyleElements, _angular_animations.AUTO_STYLE), postStylesMap = _a[0], allLeaveQueriedNodes = _a[1]; allLeaveQueriedNodes.forEach(function (node) { if (replacePostStylesAsPre(node, allPreStyleElements, allPostStyleElements)) { replaceNodes.push(node); } }); // PRE STAGE: fill the ! styles var preStylesMap = (allPreStyleElements.size ? cloakAndComputeStyles(this.driver, enterNodesWithoutAnimations, allPreStyleElements, _angular_animations.ɵPRE_STYLE) : [new Map()])[0]; replaceNodes.forEach(function (node) { var /** @type {?} */ post = postStylesMap.get(node); var /** @type {?} */ pre = preStylesMap.get(node); postStylesMap.set(node, /** @type {?} */ (Object.assign({}, post, pre))); }); var /** @type {?} */ rootPlayers = []; var /** @type {?} */ subPlayers = []; queuedInstructions.forEach(function (entry) { var element = entry.element, player = entry.player, instruction = entry.instruction; // this means that it was never consumed by a parent animation which // means that it is independent and therefore should be set for animation if (subTimelines.has(element)) { if (disabledElementsSet.has(element)) { skippedPlayers.push(player); return; } var /** @type {?} */ innerPlayer = _this._buildAnimation(player.namespaceId, instruction, allPreviousPlayersMap, skippedPlayersMap, preStylesMap, postStylesMap); player.setRealPlayer(innerPlayer); var /** @type {?} */ parentHasPriority = null; for (var /** @type {?} */ i = 0; i < sortedParentElements.length; i++) { var /** @type {?} */ parent = sortedParentElements[i]; if (parent === element) break; if (_this.driver.containsElement(parent, element)) { parentHasPriority = parent; break; } } if (parentHasPriority) { var /** @type {?} */ parentPlayers = _this.playersByElement.get(parentHasPriority); if (parentPlayers && parentPlayers.length) { player.parentPlayer = optimizeGroupPlayer(parentPlayers); } skippedPlayers.push(player); } else { rootPlayers.push(player); } } else { eraseStyles(element, instruction.fromStyles); player.onDestroy(function () { return setStyles(element, instruction.toStyles); }); // there still might be a ancestor player animating this // element therefore we will still add it as a sub player // even if its animation may be disabled subPlayers.push(player); if (disabledElementsSet.has(element)) { skippedPlayers.push(player); } } }); // find all of the sub players' corresponding inner animation player subPlayers.forEach(function (player) { // even if any players are not found for a sub animation then it // will still complete itself after the next tick since it's Noop var /** @type {?} */ playersForElement = skippedPlayersMap.get(player.element); if (playersForElement && playersForElement.length) { var /** @type {?} */ innerPlayer = optimizeGroupPlayer(playersForElement); player.setRealPlayer(innerPlayer); } }); // the reason why we don't actually play the animation is // because all that a skipped player is designed to do is to // fire the start/done transition callback events skippedPlayers.forEach(function (player) { if (player.parentPlayer) { player.parentPlayer.onDestroy(function () { return player.destroy(); }); } else { player.destroy(); } }); // run through all of the queued removals and see if they // were picked up by a query. If not then perform the removal // operation right away unless a parent animation is ongoing. for (var /** @type {?} */ i = 0; i < allLeaveNodes.length; i++) { var /** @type {?} */ element = allLeaveNodes[i]; var /** @type {?} */ details = (element[REMOVAL_FLAG]); removeClass(element, LEAVE_CLASSNAME); // this means the element has a removal animation that is being // taken care of and therefore the inner elements will hang around // until that animation is over (or the parent queried animation) if (details && details.hasAnimation) continue; var /** @type {?} */ players = []; // if this element is queried or if it contains queried children // then we want for the element not to be removed from the page // until the queried animations have finished if (queriedElements.size) { var /** @type {?} */ queriedPlayerResults = queriedElements.get(element); if (queriedPlayerResults && queriedPlayerResults.length) { players.push.apply(players, queriedPlayerResults); } var /** @type {?} */ queriedInnerElements = this.driver.query(element, NG_ANIMATING_SELECTOR, true); for (var /** @type {?} */ j = 0; j < queriedInnerElements.length; j++) { var /** @type {?} */ queriedPlayers = queriedElements.get(queriedInnerElements[j]); if (queriedPlayers && queriedPlayers.length) { players.push.apply(players, queriedPlayers); } } } var /** @type {?} */ activePlayers = players.filter(function (p) { return !p.destroyed; }); if (activePlayers.length) { removeNodesAfterAnimationDone(this, element, activePlayers); } else { this.processLeaveNode(element); } } // this is required so the cleanup method doesn't remove them allLeaveNodes.length = 0; rootPlayers.forEach(function (player) { _this.players.push(player); player.onDone(function () { player.destroy(); var /** @type {?} */ index = _this.players.indexOf(player); _this.players.splice(index, 1); }); player.play(); }); return rootPlayers; }; /** * @param {?} namespaceId * @param {?} element * @return {?} */ TransitionAnimationEngine.prototype.elementContainsData = function (namespaceId, element) { var /** @type {?} */ containsData = false; var /** @type {?} */ details = (element[REMOVAL_FLAG]); if (details && details.setForRemoval) containsData = true; if (this.playersByElement.has(element)) containsData = true; if (this.playersByQueriedElement.has(element)) containsData = true; if (this.statesByElement.has(element)) containsData = true; return this._fetchNamespace(namespaceId).elementContainsData(element) || containsData; }; /** * @param {?} callback * @return {?} */ TransitionAnimationEngine.prototype.afterFlush = function (callback) { this._flushFns.push(callback); }; /** * @param {?} callback * @return {?} */ TransitionAnimationEngine.prototype.afterFlushAnimationsDone = function (callback) { this._whenQuietFns.push(callback); }; /** * @param {?} element * @param {?} isQueriedElement * @param {?=} namespaceId * @param {?=} triggerName * @param {?=} toStateValue * @return {?} */ TransitionAnimationEngine.prototype._getPreviousPlayers = function (element, isQueriedElement, namespaceId, triggerName, toStateValue) { var /** @type {?} */ players = []; if (isQueriedElement) { var /** @type {?} */ queriedElementPlayers = this.playersByQueriedElement.get(element); if (queriedElementPlayers) { players = queriedElementPlayers; } } else { var /** @type {?} */ elementPlayers = this.playersByElement.get(element); if (elementPlayers) { var /** @type {?} */ isRemovalAnimation_1 = !toStateValue || toStateValue == VOID_VALUE; elementPlayers.forEach(function (player) { if (player.queued) return; if (!isRemovalAnimation_1 && player.triggerName != triggerName) return; players.push(player); }); } } if (namespaceId || triggerName) { players = players.filter(function (player) { if (namespaceId && namespaceId != player.namespaceId) return false; if (triggerName && triggerName != player.triggerName) return false; return true; }); } return players; }; /** * @param {?} namespaceId * @param {?} instruction * @param {?} allPreviousPlayersMap * @return {?} */ TransitionAnimationEngine.prototype._beforeAnimationBuild = function (namespaceId, instruction, allPreviousPlayersMap) { var _this = this; var /** @type {?} */ triggerName = instruction.triggerName; var /** @type {?} */ rootElement = instruction.element; // when a removal animation occurs, ALL previous players are collected // and destroyed (even if they are outside of the current namespace) var /** @type {?} */ targetNameSpaceId = instruction.isRemovalTransition ? undefined : namespaceId; var /** @type {?} */ targetTriggerName = instruction.isRemovalTransition ? undefined : triggerName; instruction.timelines.map(function (timelineInstruction) { var /** @type {?} */ element = timelineInstruction.element; var /** @type {?} */ isQueriedElement = element !== rootElement; var /** @type {?} */ players = getOrSetAsInMap(allPreviousPlayersMap, element, []); var /** @type {?} */ previousPlayers = _this._getPreviousPlayers(element, isQueriedElement, targetNameSpaceId, targetTriggerName, instruction.toState); previousPlayers.forEach(function (player) { var /** @type {?} */ realPlayer = (player.getRealPlayer()); if (realPlayer.beforeDestroy) { realPlayer.beforeDestroy(); } player.destroy(); players.push(player); }); }); // this needs to be done so that the PRE/POST styles can be // computed properly without interfering with the previous animation eraseStyles(rootElement, instruction.fromStyles); }; /** * @param {?} namespaceId * @param {?} instruction * @param {?} allPreviousPlayersMap * @param {?} skippedPlayersMap * @param {?} preStylesMap * @param {?} postStylesMap * @return {?} */ TransitionAnimationEngine.prototype._buildAnimation = function (namespaceId, instruction, allPreviousPlayersMap, skippedPlayersMap, preStylesMap, postStylesMap) { var _this = this; var /** @type {?} */ triggerName = instruction.triggerName; var /** @type {?} */ rootElement = instruction.element; // we first run this so that the previous animation player // data can be passed into the successive animation players var /** @type {?} */ allQueriedPlayers = []; var /** @type {?} */ allConsumedElements = new Set(); var /** @type {?} */ allSubElements = new Set(); var /** @type {?} */ allNewPlayers = instruction.timelines.map(function (timelineInstruction) { var /** @type {?} */ element = timelineInstruction.element; allConsumedElements.add(element); // FIXME (matsko): make sure to-be-removed animations are removed properly var /** @type {?} */ details = element[REMOVAL_FLAG]; if (details && details.removedBeforeQueried) return new _angular_animations.NoopAnimationPlayer(); var /** @type {?} */ isQueriedElement = element !== rootElement; var /** @type {?} */ previousPlayers = flattenGroupPlayers((allPreviousPlayersMap.get(element) || EMPTY_PLAYER_ARRAY) .map(function (p) { return p.getRealPlayer(); })) .filter(function (p) { // the `element` is not apart of the AnimationPlayer definition, but // Mock/WebAnimations // use the element within their implementation. This will be added in Angular5 to // AnimationPlayer var /** @type {?} */ pp = (p); return pp.element ? pp.element === element : false; }); var /** @type {?} */ preStyles = preStylesMap.get(element); var /** @type {?} */ postStyles = postStylesMap.get(element); var /** @type {?} */ keyframes = normalizeKeyframes(_this.driver, _this._normalizer, element, timelineInstruction.keyframes, preStyles, postStyles); var /** @type {?} */ player = _this._buildPlayer(timelineInstruction, keyframes, previousPlayers); // this means that this particular player belongs to a sub trigger. It is // important that we match this player up with the corresponding (@trigger.listener) if (timelineInstruction.subTimeline && skippedPlayersMap) { allSubElements.add(element); } if (isQueriedElement) { var /** @type {?} */ wrappedPlayer = new TransitionAnimationPlayer(namespaceId, triggerName, element); wrappedPlayer.setRealPlayer(player); allQueriedPlayers.push(wrappedPlayer); } return player; }); allQueriedPlayers.forEach(function (player) { getOrSetAsInMap(_this.playersByQueriedElement, player.element, []).push(player); player.onDone(function () { return deleteOrUnsetInMap(_this.playersByQueriedElement, player.element, player); }); }); allConsumedElements.forEach(function (element) { return addClass(element, NG_ANIMATING_CLASSNAME); }); var /** @type {?} */ player = optimizeGroupPlayer(allNewPlayers); player.onDestroy(function () { allConsumedElements.forEach(function (element) { return removeClass(element, NG_ANIMATING_CLASSNAME); }); setStyles(rootElement, instruction.toStyles); }); // this basically makes all of the callbacks for sub element animations // be dependent on the upper players for when they finish allSubElements.forEach(function (element) { getOrSetAsInMap(skippedPlayersMap, element, []).push(player); }); return player; }; /** * @param {?} instruction * @param {?} keyframes * @param {?} previousPlayers * @return {?} */ TransitionAnimationEngine.prototype._buildPlayer = function (instruction, keyframes, previousPlayers) { if (keyframes.length > 0) { return this.driver.animate(instruction.element, keyframes, instruction.duration, instruction.delay, instruction.easing, previousPlayers); } // special case for when an empty transition|definition is provided // ... there is no point in rendering an empty animation return new _angular_animations.NoopAnimationPlayer(); }; return TransitionAnimationEngine; }()); var TransitionAnimationPlayer = (function () { /** * @param {?} namespaceId * @param {?} triggerName * @param {?} element */ function TransitionAnimationPlayer(namespaceId, triggerName, element) { this.namespaceId = namespaceId; this.triggerName = triggerName; this.element = element; this._player = new _angular_animations.NoopAnimationPlayer(); this._containsRealPlayer = false; this._queuedCallbacks = {}; this._destroyed = false; this.markedForDestroy = false; } Object.defineProperty(TransitionAnimationPlayer.prototype, "queued", { /** * @return {?} */ get: function () { return this._containsRealPlayer == false; }, enumerable: true, configurable: true }); Object.defineProperty(TransitionAnimationPlayer.prototype, "destroyed", { /** * @return {?} */ get: function () { return this._destroyed; }, enumerable: true, configurable: true }); /** * @param {?} player * @return {?} */ TransitionAnimationPlayer.prototype.setRealPlayer = function (player) { var _this = this; if (this._containsRealPlayer) return; this._player = player; Object.keys(this._queuedCallbacks).forEach(function (phase) { _this._queuedCallbacks[phase].forEach(function (callback) { return listenOnPlayer(player, phase, undefined, callback); }); }); this._queuedCallbacks = {}; this._containsRealPlayer = true; }; /** * @return {?} */ TransitionAnimationPlayer.prototype.getRealPlayer = function () { return this._player; }; /** * @param {?} name * @param {?} callback * @return {?} */ TransitionAnimationPlayer.prototype._queueEvent = function (name, callback) { getOrSetAsInMap(this._queuedCallbacks, name, []).push(callback); }; /** * @param {?} fn * @return {?} */ TransitionAnimationPlayer.prototype.onDone = function (fn) { if (this.queued) { this._queueEvent('done', fn); } this._player.onDone(fn); }; /** * @param {?} fn * @return {?} */ TransitionAnimationPlayer.prototype.onStart = function (fn) { if (this.queued) { this._queueEvent('start', fn); } this._player.onStart(fn); }; /** * @param {?} fn * @return {?} */ TransitionAnimationPlayer.prototype.onDestroy = function (fn) { if (this.queued) { this._queueEvent('destroy', fn); } this._player.onDestroy(fn); }; /** * @return {?} */ TransitionAnimationPlayer.prototype.init = function () { this._player.init(); }; /** * @return {?} */ TransitionAnimationPlayer.prototype.hasStarted = function () { return this.queued ? false : this._player.hasStarted(); }; /** * @return {?} */ TransitionAnimationPlayer.prototype.play = function () { !this.queued && this._player.play(); }; /** * @return {?} */ TransitionAnimationPlayer.prototype.pause = function () { !this.queued && this._player.pause(); }; /** * @return {?} */ TransitionAnimationPlayer.prototype.restart = function () { !this.queued && this._player.restart(); }; /** * @return {?} */ TransitionAnimationPlayer.prototype.finish = function () { this._player.finish(); }; /** * @return {?} */ TransitionAnimationPlayer.prototype.destroy = function () { this._destroyed = true; this._player.destroy(); }; /** * @return {?} */ TransitionAnimationPlayer.prototype.reset = function () { !this.queued && this._player.reset(); }; /** * @param {?} p * @return {?} */ TransitionAnimationPlayer.prototype.setPosition = function (p) { if (!this.queued) { this._player.setPosition(p); } }; /** * @return {?} */ TransitionAnimationPlayer.prototype.getPosition = function () { return this.queued ? 0 : this._player.getPosition(); }; Object.defineProperty(TransitionAnimationPlayer.prototype, "totalTime", { /** * @return {?} */ get: function () { return this._player.totalTime; }, enumerable: true, configurable: true }); return TransitionAnimationPlayer; }()); /** * @param {?} map * @param {?} key * @param {?} value * @return {?} */ function deleteOrUnsetInMap(map, key, value) { var /** @type {?} */ currentValues; if (map instanceof Map) { currentValues = map.get(key); if (currentValues) { if (currentValues.length) { var /** @type {?} */ index = currentValues.indexOf(value); currentValues.splice(index, 1); } if (currentValues.length == 0) { map.delete(key); } } } else { currentValues = map[key]; if (currentValues) { if (currentValues.length) { var /** @type {?} */ index = currentValues.indexOf(value); currentValues.splice(index, 1); } if (currentValues.length == 0) { delete map[key]; } } } return currentValues; } /** * @param {?} value * @return {?} */ function normalizeTriggerValue(value) { switch (typeof value) { case 'boolean': return value ? '1' : '0'; default: return value != null ? value.toString() : null; } } /** * @param {?} node * @return {?} */ function isElementNode(node) { return node && node['nodeType'] === 1; } /** * @param {?} eventName * @return {?} */ function isTriggerEventValid(eventName) { return eventName == 'start' || eventName == 'done'; } /** * @param {?} element * @param {?=} value * @return {?} */ function cloakElement(element, value) { var /** @type {?} */ oldValue = element.style.display; element.style.display = value != null ? value : 'none'; return oldValue; } /** * @param {?} driver * @param {?} elements * @param {?} elementPropsMap * @param {?} defaultStyle * @return {?} */ function cloakAndComputeStyles(driver, elements, elementPropsMap, defaultStyle) { var /** @type {?} */ cloakVals = []; elements.forEach(function (element) { return cloakVals.push(cloakElement(element)); }); var /** @type {?} */ valuesMap = new Map(); var /** @type {?} */ failedElements = []; elementPropsMap.forEach(function (props, element) { var /** @type {?} */ styles = {}; props.forEach(function (prop) { var /** @type {?} */ value = styles[prop] = driver.computeStyle(element, prop, defaultStyle); // there is no easy way to detect this because a sub element could be removed // by a parent animation element being detached. if (!value || value.length == 0) { element[REMOVAL_FLAG] = NULL_REMOVED_QUERIED_STATE; failedElements.push(element); } }); valuesMap.set(element, styles); }); // we use a index variable here since Set.forEach(a, i) does not return // an index value for the closure (but instead just the value) var /** @type {?} */ i = 0; elements.forEach(function (element) { return cloakElement(element, cloakVals[i++]); }); return [valuesMap, failedElements]; } /** * @param {?} nodes * @return {?} */ function createIsRootFilterFn(nodes) { var /** @type {?} */ nodeSet = new Set(nodes); var /** @type {?} */ knownRootContainer = new Set(); var /** @type {?} */ isRoot; isRoot = function (node) { if (!node) return true; if (nodeSet.has(node.parentNode)) return false; if (knownRootContainer.has(node.parentNode)) return true; if (isRoot(node.parentNode)) { knownRootContainer.add(node); return true; } return false; }; return isRoot; } var CLASSES_CACHE_KEY = '$$classes'; /** * @param {?} element * @param {?} className * @return {?} */ function containsClass(element, className) { if (element.classList) { return element.classList.contains(className); } else { var /** @type {?} */ classes = element[CLASSES_CACHE_KEY]; return classes && classes[className]; } } /** * @param {?} element * @param {?} className * @return {?} */ function addClass(element, className) { if (element.classList) { element.classList.add(className); } else { var /** @type {?} */ classes = element[CLASSES_CACHE_KEY]; if (!classes) { classes = element[CLASSES_CACHE_KEY] = {}; } classes[className] = true; } } /** * @param {?} element * @param {?} className * @return {?} */ function removeClass(element, className) { if (element.classList) { element.classList.remove(className); } else { var /** @type {?} */ classes = element[CLASSES_CACHE_KEY]; if (classes) { delete classes[className]; } } } /** * @return {?} */ function getBodyNode() { if (typeof document != 'undefined') { return document.body; } return null; } /** * @param {?} engine * @param {?} element * @param {?} players * @return {?} */ function removeNodesAfterAnimationDone(engine, element, players) { optimizeGroupPlayer(players).onDone(function () { return engine.processLeaveNode(element); }); } /** * @param {?} players * @return {?} */ function flattenGroupPlayers(players) { var /** @type {?} */ finalPlayers = []; _flattenGroupPlayersRecur(players, finalPlayers); return finalPlayers; } /** * @param {?} players * @param {?} finalPlayers * @return {?} */ function _flattenGroupPlayersRecur(players, finalPlayers) { for (var /** @type {?} */ i = 0; i < players.length; i++) { var /** @type {?} */ player = players[i]; if (player instanceof _angular_animations.ɵAnimationGroupPlayer) { _flattenGroupPlayersRecur(player.players, finalPlayers); } else { finalPlayers.push(/** @type {?} */ (player)); } } } /** * @param {?} a * @param {?} b * @return {?} */ function objEquals(a, b) { var /** @type {?} */ k1 = Object.keys(a); var /** @type {?} */ k2 = Object.keys(b); if (k1.length != k2.length) return false; for (var /** @type {?} */ i = 0; i < k1.length; i++) { var /** @type {?} */ prop = k1[i]; if (!b.hasOwnProperty(prop) || a[prop] !== b[prop]) return false; } return true; } /** * @param {?} element * @param {?} allPreStyleElements * @param {?} allPostStyleElements * @return {?} */ function replacePostStylesAsPre(element, allPreStyleElements, allPostStyleElements) { var /** @type {?} */ postEntry = allPostStyleElements.get(element); if (!postEntry) return false; var /** @type {?} */ preEntry = allPreStyleElements.get(element); if (preEntry) { postEntry.forEach(function (data) { return ((preEntry)).add(data); }); } else { allPreStyleElements.set(element, postEntry); } allPostStyleElements.delete(element); return true; } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var AnimationEngine = (function () { /** * @param {?} driver * @param {?} normalizer */ function AnimationEngine(driver, normalizer) { var _this = this; this._triggerCache = {}; this.onRemovalComplete = function (element, context) { }; this._transitionEngine = new TransitionAnimationEngine(driver, normalizer); this._timelineEngine = new TimelineAnimationEngine(driver, normalizer); this._transitionEngine.onRemovalComplete = function (element, context) { return _this.onRemovalComplete(element, context); }; } /** * @param {?} componentId * @param {?} namespaceId * @param {?} hostElement * @param {?} name * @param {?} metadata * @return {?} */ AnimationEngine.prototype.registerTrigger = function (componentId, namespaceId, hostElement, name, metadata) { var /** @type {?} */ cacheKey = componentId + '-' + name; var /** @type {?} */ trigger = this._triggerCache[cacheKey]; if (!trigger) { var /** @type {?} */ errors = []; var /** @type {?} */ ast = (buildAnimationAst(/** @type {?} */ (metadata), errors)); if (errors.length) { throw new Error("The animation trigger \"" + name + "\" has failed to build due to the following errors:\n - " + errors.join("\n - ")); } trigger = buildTrigger(name, ast); this._triggerCache[cacheKey] = trigger; } this._transitionEngine.registerTrigger(namespaceId, name, trigger); }; /** * @param {?} namespaceId * @param {?} hostElement * @return {?} */ AnimationEngine.prototype.register = function (namespaceId, hostElement) { this._transitionEngine.register(namespaceId, hostElement); }; /** * @param {?} namespaceId * @param {?} context * @return {?} */ AnimationEngine.prototype.destroy = function (namespaceId, context) { this._transitionEngine.destroy(namespaceId, context); }; /** * @param {?} namespaceId * @param {?} element * @param {?} parent * @param {?} insertBefore * @return {?} */ AnimationEngine.prototype.onInsert = function (namespaceId, element, parent, insertBefore) { this._transitionEngine.insertNode(namespaceId, element, parent, insertBefore); }; /** * @param {?} namespaceId * @param {?} element * @param {?} context * @return {?} */ AnimationEngine.prototype.onRemove = function (namespaceId, element, context) { this._transitionEngine.removeNode(namespaceId, element, context); }; /** * @param {?} element * @param {?} disable * @return {?} */ AnimationEngine.prototype.disableAnimations = function (element, disable) { this._transitionEngine.markElementAsDisabled(element, disable); }; /** * @param {?} namespaceId * @param {?} element * @param {?} property * @param {?} value * @return {?} */ AnimationEngine.prototype.process = function (namespaceId, element, property, value) { if (property.charAt(0) == '@') { var _a = parseTimelineCommand(property), id = _a[0], action = _a[1]; var /** @type {?} */ args = (value); this._timelineEngine.command(id, element, action, args); } else { this._transitionEngine.trigger(namespaceId, element, property, value); } }; /** * @param {?} namespaceId * @param {?} element * @param {?} eventName * @param {?} eventPhase * @param {?} callback * @return {?} */ AnimationEngine.prototype.listen = function (namespaceId, element, eventName, eventPhase, callback) { // @@listen if (eventName.charAt(0) == '@') { var _a = parseTimelineCommand(eventName), id = _a[0], action = _a[1]; return this._timelineEngine.listen(id, element, action, callback); } return this._transitionEngine.listen(namespaceId, element, eventName, eventPhase, callback); }; /** * @param {?=} microtaskId * @return {?} */ AnimationEngine.prototype.flush = function (microtaskId) { if (microtaskId === void 0) { microtaskId = -1; } this._transitionEngine.flush(microtaskId); }; Object.defineProperty(AnimationEngine.prototype, "players", { /** * @return {?} */ get: function () { return ((this._transitionEngine.players)) .concat(/** @type {?} */ (this._timelineEngine.players)); }, enumerable: true, configurable: true }); /** * @return {?} */ AnimationEngine.prototype.whenRenderingDone = function () { return this._transitionEngine.whenRenderingDone(); }; return AnimationEngine; }()); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var WebAnimationsPlayer = (function () { /** * @param {?} element * @param {?} keyframes * @param {?} options * @param {?=} previousPlayers */ function WebAnimationsPlayer(element, keyframes, options, previousPlayers) { if (previousPlayers === void 0) { previousPlayers = []; } var _this = this; this.element = element; this.keyframes = keyframes; this.options = options; this.previousPlayers = previousPlayers; this._onDoneFns = []; this._onStartFns = []; this._onDestroyFns = []; this._initialized = false; this._finished = false; this._started = false; this._destroyed = false; this.time = 0; this.parentPlayer = null; this.previousStyles = {}; this.currentSnapshot = {}; this._duration = options['duration']; this._delay = options['delay'] || 0; this.time = this._duration + this._delay; if (allowPreviousPlayerStylesMerge(this._duration, this._delay)) { previousPlayers.forEach(function (player) { var styles = player.currentSnapshot; Object.keys(styles).forEach(function (prop) { return _this.previousStyles[prop] = styles[prop]; }); }); } } /** * @return {?} */ WebAnimationsPlayer.prototype._onFinish = function () { if (!this._finished) { this._finished = true; this._onDoneFns.forEach(function (fn) { return fn(); }); this._onDoneFns = []; } }; /** * @return {?} */ WebAnimationsPlayer.prototype.init = function () { this._buildPlayer(); this._preparePlayerBeforeStart(); }; /** * @return {?} */ WebAnimationsPlayer.prototype._buildPlayer = function () { var _this = this; if (this._initialized) return; this._initialized = true; var /** @type {?} */ keyframes = this.keyframes.map(function (styles) { return copyStyles(styles, false); }); var /** @type {?} */ previousStyleProps = Object.keys(this.previousStyles); if (previousStyleProps.length) { var /** @type {?} */ startingKeyframe_1 = keyframes[0]; var /** @type {?} */ missingStyleProps_1 = []; previousStyleProps.forEach(function (prop) { if (!startingKeyframe_1.hasOwnProperty(prop)) { missingStyleProps_1.push(prop); } startingKeyframe_1[prop] = _this.previousStyles[prop]; }); if (missingStyleProps_1.length) { var /** @type {?} */ self_1 = this; var _loop_1 = function () { var /** @type {?} */ kf = keyframes[i]; missingStyleProps_1.forEach(function (prop) { kf[prop] = _computeStyle(self_1.element, prop); }); }; // tslint:disable-next-line for (var /** @type {?} */ i = 1; i < keyframes.length; i++) { _loop_1(); } } } this._player = this._triggerWebAnimation(this.element, keyframes, this.options); this._finalKeyframe = keyframes.length ? keyframes[keyframes.length - 1] : {}; this._player.addEventListener('finish', function () { return _this._onFinish(); }); }; /** * @return {?} */ WebAnimationsPlayer.prototype._preparePlayerBeforeStart = function () { // this is required so that the player doesn't start to animate right away if (this._delay) { this._resetDomPlayerState(); } else { this._player.pause(); } }; /** * \@internal * @param {?} element * @param {?} keyframes * @param {?} options * @return {?} */ WebAnimationsPlayer.prototype._triggerWebAnimation = function (element, keyframes, options) { // jscompiler doesn't seem to know animate is a native property because it's not fully // supported yet across common browsers (we polyfill it for Edge/Safari) [CL #143630929] return (element['animate'](keyframes, options)); }; Object.defineProperty(WebAnimationsPlayer.prototype, "domPlayer", { /** * @return {?} */ get: function () { return this._player; }, enumerable: true, configurable: true }); /** * @param {?} fn * @return {?} */ WebAnimationsPlayer.prototype.onStart = function (fn) { this._onStartFns.push(fn); }; /** * @param {?} fn * @return {?} */ WebAnimationsPlayer.prototype.onDone = function (fn) { this._onDoneFns.push(fn); }; /** * @param {?} fn * @return {?} */ WebAnimationsPlayer.prototype.onDestroy = function (fn) { this._onDestroyFns.push(fn); }; /** * @return {?} */ WebAnimationsPlayer.prototype.play = function () { this._buildPlayer(); if (!this.hasStarted()) { this._onStartFns.forEach(function (fn) { return fn(); }); this._onStartFns = []; this._started = true; } this._player.play(); }; /** * @return {?} */ WebAnimationsPlayer.prototype.pause = function () { this.init(); this._player.pause(); }; /** * @return {?} */ WebAnimationsPlayer.prototype.finish = function () { this.init(); this._onFinish(); this._player.finish(); }; /** * @return {?} */ WebAnimationsPlayer.prototype.reset = function () { this._resetDomPlayerState(); this._destroyed = false; this._finished = false; this._started = false; }; /** * @return {?} */ WebAnimationsPlayer.prototype._resetDomPlayerState = function () { if (this._player) { this._player.cancel(); } }; /** * @return {?} */ WebAnimationsPlayer.prototype.restart = function () { this.reset(); this.play(); }; /** * @return {?} */ WebAnimationsPlayer.prototype.hasStarted = function () { return this._started; }; /** * @return {?} */ WebAnimationsPlayer.prototype.destroy = function () { if (!this._destroyed) { this._destroyed = true; this._resetDomPlayerState(); this._onFinish(); this._onDestroyFns.forEach(function (fn) { return fn(); }); this._onDestroyFns = []; } }; /** * @param {?} p * @return {?} */ WebAnimationsPlayer.prototype.setPosition = function (p) { this._player.currentTime = p * this.time; }; /** * @return {?} */ WebAnimationsPlayer.prototype.getPosition = function () { return this._player.currentTime / this.time; }; Object.defineProperty(WebAnimationsPlayer.prototype, "totalTime", { /** * @return {?} */ get: function () { return this._delay + this._duration; }, enumerable: true, configurable: true }); /** * @return {?} */ WebAnimationsPlayer.prototype.beforeDestroy = function () { var _this = this; var /** @type {?} */ styles = {}; if (this.hasStarted()) { Object.keys(this._finalKeyframe).forEach(function (prop) { if (prop != 'offset') { styles[prop] = _this._finished ? _this._finalKeyframe[prop] : _computeStyle(_this.element, prop); } }); } this.currentSnapshot = styles; }; return WebAnimationsPlayer; }()); /** * @param {?} element * @param {?} prop * @return {?} */ function _computeStyle(element, prop) { return ((window.getComputedStyle(element)))[prop]; } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var WebAnimationsDriver = (function () { function WebAnimationsDriver() { } /** * @param {?} element * @param {?} selector * @return {?} */ WebAnimationsDriver.prototype.matchesElement = function (element, selector) { return matchesElement(element, selector); }; /** * @param {?} elm1 * @param {?} elm2 * @return {?} */ WebAnimationsDriver.prototype.containsElement = function (elm1, elm2) { return containsElement(elm1, elm2); }; /** * @param {?} element * @param {?} selector * @param {?} multi * @return {?} */ WebAnimationsDriver.prototype.query = function (element, selector, multi) { return invokeQuery(element, selector, multi); }; /** * @param {?} element * @param {?} prop * @param {?=} defaultValue * @return {?} */ WebAnimationsDriver.prototype.computeStyle = function (element, prop, defaultValue) { return (((window.getComputedStyle(element)))[prop]); }; /** * @param {?} element * @param {?} keyframes * @param {?} duration * @param {?} delay * @param {?} easing * @param {?=} previousPlayers * @return {?} */ WebAnimationsDriver.prototype.animate = function (element, keyframes, duration, delay, easing, previousPlayers) { if (previousPlayers === void 0) { previousPlayers = []; } var /** @type {?} */ fill = delay == 0 ? 'both' : 'forwards'; var /** @type {?} */ playerOptions = { duration: duration, delay: delay, fill: fill }; // we check for this to avoid having a null|undefined value be present // for the easing (which results in an error for certain browsers #9752) if (easing) { playerOptions['easing'] = easing; } var /** @type {?} */ previousWebAnimationPlayers = (previousPlayers.filter(function (player) { return player instanceof WebAnimationsPlayer; })); return new WebAnimationsPlayer(element, keyframes, playerOptions, previousWebAnimationPlayers); }; return WebAnimationsDriver; }()); /** * @return {?} */ function supportsWebAnimations() { return typeof Element !== 'undefined' && typeof ((Element)).prototype['animate'] === 'function'; } exports.AnimationDriver = AnimationDriver; exports.ɵAnimation = Animation; exports.ɵAnimationStyleNormalizer = AnimationStyleNormalizer; exports.ɵNoopAnimationStyleNormalizer = NoopAnimationStyleNormalizer; exports.ɵWebAnimationsStyleNormalizer = WebAnimationsStyleNormalizer; exports.ɵNoopAnimationDriver = NoopAnimationDriver; exports.ɵAnimationEngine = AnimationEngine; exports.ɵWebAnimationsDriver = WebAnimationsDriver; exports.ɵsupportsWebAnimations = supportsWebAnimations; exports.ɵWebAnimationsPlayer = WebAnimationsPlayer; Object.defineProperty(exports, '__esModule', { value: true }); }))); //# sourceMappingURL=animations-browser.umd.js.map
steal("funcunit/qunit", function(){ module("naxx"); test("naxx testing works", function(){ ok(true,"an assert is run"); }); })
describe('taSanitize', function(){ 'use strict'; beforeEach(module('textAngular')); beforeEach(module('ngSanitize')); describe('should change all align attributes to text-align styles for HTML5 compatability', function(){ it('should correct left align', inject(function(taSanitize){ var safe = angular.element(taSanitize('<div align="left"></div>')); expect(safe.attr('align')).not.toBeDefined(); expect(safe.css('text-align')).toBe('left'); })); it('should correct right align', inject(function(taSanitize){ var safe = angular.element(taSanitize('<div align="right"></div>')); expect(safe.attr('align')).not.toBeDefined(); expect(safe.css('text-align')).toBe('right'); })); it('should correct center align', inject(function(taSanitize){ var safe = angular.element(taSanitize('<div align=\'center\'></div>')); expect(safe.attr('align')).not.toBeDefined(); expect(safe.css('text-align')).toBe('center'); })); it('should correct justify align', inject(function(taSanitize){ var safe = angular.element(taSanitize('<div align=\'justify\'></div>')); expect(safe.attr('align')).not.toBeDefined(); expect(safe.css('text-align')).toBe('justify'); })); }); describe('if invalid HTML', function(){ it('should return the oldsafe passed in', inject(function(taSanitize){ var result = taSanitize('<broken><test', 'safe'); expect(result).toBe('safe'); })); it('should return an empty string if no oldsafe', inject(function(taSanitize){ var result = taSanitize('<broken><test'); expect(result).toBe(''); })); }); describe('only certain style attributes are allowed', function(){ describe('validated color attribute', function(){ it('name', inject(function(taSanitize){ var result = angular.element(taSanitize('<div style="color: blue;"></div>')); expect(result.attr('style')).toBe('color: blue;'); })); it('hex value', inject(function(taSanitize){ var result = angular.element(taSanitize('<div style="color: #000000;"></div>')); expect(result.attr('style')).toBe('color: #000000;'); })); it('rgba', inject(function(taSanitize){ var result = angular.element(taSanitize('<div style="color: rgba(20, 20, 20, 0.5);"></div>')); expect(result.attr('style')).toBe('color: rgba(20, 20, 20, 0.5);'); })); it('rgb', inject(function(taSanitize){ var result = angular.element(taSanitize('<div style="color: rgb(20, 20, 20);"></div>')); expect(result.attr('style')).toBe('color: rgb(20, 20, 20);'); })); it('hsl', inject(function(taSanitize){ var result = angular.element(taSanitize('<div style="color: hsl(20, 20%, 20%);"></div>')); expect(result.attr('style')).toBe('color: hsl(20, 20%, 20%);'); })); it('hlsa', inject(function(taSanitize){ var result = angular.element(taSanitize('<div style="color: hsla(20, 20%, 20%, 0.5);"></div>')); expect(result.attr('style')).toBe('color: hsla(20, 20%, 20%, 0.5);'); })); it('bad value not accepted', inject(function(taSanitize){ var result = taSanitize('<div style="color: execute(alert(\'test\'));"></div>'); expect(result).toBe('<div></div>'); })); }); describe('validated background-color attribute', function(){ it('name', inject(function(taSanitize){ var result = angular.element(taSanitize('<div style="background-color: blue;"></div>')); expect(result.attr('style')).toBe('background-color: blue;'); })); it('hex value', inject(function(taSanitize){ var result = angular.element(taSanitize('<div style="background-color: #000000;"></div>')); expect(result.attr('style')).toBe('background-color: #000000;'); })); it('rgba', inject(function(taSanitize){ var result = angular.element(taSanitize('<div style="background-color: rgba(20, 20, 20, 0.5);"></div>')); expect(result.attr('style')).toBe('background-color: rgba(20, 20, 20, 0.5);'); })); it('rgb', inject(function(taSanitize){ var result = angular.element(taSanitize('<div style="background-color: rgb(20, 20, 20);"></div>')); expect(result.attr('style')).toBe('background-color: rgb(20, 20, 20);'); })); it('hsl', inject(function(taSanitize){ var result = angular.element(taSanitize('<div style="background-color: hsl(20, 20%, 20%);"></div>')); expect(result.attr('style')).toBe('background-color: hsl(20, 20%, 20%);'); })); it('hlsa', inject(function(taSanitize){ var result = angular.element(taSanitize('<div style="background-color: hsla(20, 20%, 20%, 0.5);"></div>')); expect(result.attr('style')).toBe('background-color: hsla(20, 20%, 20%, 0.5);'); })); it('bad value not accepted', inject(function(taSanitize){ var result = taSanitize('<div style="background-color: execute(alert(\'test\'));"></div>'); expect(result).toBe('<div></div>'); })); }); describe('validated text-align attribute', function(){ it('left', inject(function(taSanitize){ var result = angular.element(taSanitize('<div style="text-align: left;"></div>')); expect(result.attr('style')).toBe('text-align: left;'); })); it('right', inject(function(taSanitize){ var result = angular.element(taSanitize('<div style="text-align: right;"></div>')); expect(result.attr('style')).toBe('text-align: right;'); })); it('center', inject(function(taSanitize){ var result = angular.element(taSanitize('<div style="text-align: center;"></div>')); expect(result.attr('style')).toBe('text-align: center;'); })); it('justify', inject(function(taSanitize){ var result = angular.element(taSanitize('<div style="text-align: justify;"></div>')); expect(result.attr('style')).toBe('text-align: justify;'); })); it('bad value not accepted', inject(function(taSanitize){ var result = taSanitize('<div style="text-align: execute(alert(\'test\'));"></div>'); expect(result).toBe('<div></div>'); })); }); describe('validated float attribute', function(){ it('left', inject(function(taSanitize){ var result = angular.element(taSanitize('<div style="float: left;"></div>')); expect(result.attr('style')).toBe('float: left;'); })); it('right', inject(function(taSanitize){ var result = angular.element(taSanitize('<div style="float: right;"></div>')); expect(result.attr('style')).toBe('float: right;'); })); it('bad value not accepted', inject(function(taSanitize){ var result = taSanitize('<div style="float: execute(alert(\'test\'));"></div>'); expect(result).toBe('<div></div>'); })); }); describe('validated height attribute', function(){ it('px', inject(function(taSanitize){ var result = angular.element(taSanitize('<div style="height: 100px;"></div>')); expect(result.attr('style')).toBe('height: 100px;'); })); it('px', inject(function(taSanitize){ var result = angular.element(taSanitize('<div style="height: 100%;"></div>')); expect(result.attr('style')).toBe('height: 100%;'); })); it('em', inject(function(taSanitize){ var result = angular.element(taSanitize('<div style="height: 100em;"></div>')); expect(result.attr('style')).toBe('height: 100em;'); })); it('rem', inject(function(taSanitize){ var result = angular.element(taSanitize('<div style="height: 100rem;"></div>')); expect(result.attr('style')).toBe('height: 100rem;'); })); it('bad value not accepted', inject(function(taSanitize){ var result = taSanitize('<div style="height: execute(alert(\'test\'));"></div>'); expect(result).toBe('<div></div>'); })); }); describe('validated width attribute', function(){ it('px', inject(function(taSanitize){ var result = angular.element(taSanitize('<div style="width: 100px;"></div>')); expect(result.attr('style')).toBe('width: 100px;'); })); it('px', inject(function(taSanitize){ var result = angular.element(taSanitize('<div style="width: 100%;"></div>')); expect(result.attr('style')).toBe('width: 100%;'); })); it('em', inject(function(taSanitize){ var result = angular.element(taSanitize('<div style="width: 100em;"></div>')); expect(result.attr('style')).toBe('width: 100em;'); })); it('rem', inject(function(taSanitize){ var result = angular.element(taSanitize('<div style="width: 100rem;"></div>')); expect(result.attr('style')).toBe('width: 100rem;'); })); it('bad value not accepted', inject(function(taSanitize){ var result = taSanitize('<div style="width: execute(alert(\'test\'));"></div>'); expect(result).toBe('<div></div>'); })); }); describe('un-validated are removed', function(){ it('removes non whitelisted values', inject(function(taSanitize){ var result = taSanitize('<div style="max-height: 12px;"></div>'); expect(result).toBe('<div></div>'); })); it('removes non whitelisted values leaving valid values', inject(function(taSanitize){ var result = angular.element(taSanitize('<div style="text-align: left; max-height: 12px;"></div>')); expect(result.attr('style')).toBe('text-align: left;'); })); }); }); describe('allow disabling of sanitizer', function(){ it('should return the oldsafe passed in if bad html', inject(function(taSanitize, $sce){ var result = taSanitize('<broken><test', 'safe', true); expect(result).toBe('safe'); })); it('should allow html not allowed by sanitizer', inject(function(taSanitize, $sce){ var result = taSanitize('<bad-tag></bad-tag>', '', true); expect(result).toBe('<bad-tag></bad-tag>'); })); }); describe('check if style is satinized correctly', function(){ it('should translate style to tag', inject(function(taSanitize, $sce){ var result = taSanitize('Q<b>W</b><i style="font-weight: bold;">E</i><u style="font-weight: bold; font-style: italic;">R</u>T'); expect(result).toBe('Q<b>W</b><i><b>E</b></i><u><i><b>R</b></i></u>T'); })); }); });
var gulp = require('gulp'); var sass = require('gulp-sass'); var sourcemaps = require('gulp-sourcemaps'); var concat = require('gulp-concat'); var plumber = require('gulp-plumber'); var strip = require('gulp-strip-comments'); var uglify = require('gulp-uglify'); var browserify = require('gulp-browserify'); var sourceBower = 'bower/'; var sourceNodeModules = 'node_modules/'; var sourceDir = 'app/gulp/web/'; var sourceJsDir = sourceDir + 'js/'; gulp.task('css-external', function(){ return gulp.src([ sourceNodeModules+ 'foundation-sites/dist/foundation.min.css', sourceBower + 'fontawesome/css/font-awesome.min.css', sourceBower + 'sweetalert/dist/sweetalert.css' ]) .pipe(plumber()) .pipe(concat('external.css')) .pipe(gulp.dest('web/css')) ; }); gulp.task('css', function(){ return gulp.src([ sourceDir + 'scss/style.scss' ]) .pipe(plumber()) .pipe(sass()) .pipe(concat('bundle.css')) .pipe(sourcemaps.write('.')) .pipe(gulp.dest('web/css')) ; }); gulp.task('copy-fonts', function(){ gulp.src([ sourceBower + 'fontawesome/fonts/*.*' ], [{ base: 'bower/' }]) .pipe(gulp.dest('web/fonts')) ; }); gulp.task('copy-files', ['copy-fonts'], function(){ //return gulp.src(sourceScssDir + 'responsive/**/*.css') // .pipe(gulp.dest('web/css/responsive')); }); gulp.task('js', function(){ return gulp.src([ sourceJsDir + 'app.js' ]) .pipe(strip()) .pipe(browserify({ insertGlobals: true, debug: false })) //.pipe(uglify()) .pipe(concat('bundle.js')) .pipe(gulp.dest('web/js/')) ; }); gulp.task('watch', function(){ gulp.watch([ sourceDir + 'layout/css/*.*/*.css', sourceDir + 'scss/**/*.scss' ], ['css']) }); gulp.task('default', ['css-external', 'css', 'copy-files', 'js']);
/* Copyright (c) 2008-2015 Pivotal Labs Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ jasmineRequire.html = function(j$) { j$.ResultsNode = jasmineRequire.ResultsNode(); j$.HtmlReporter = jasmineRequire.HtmlReporter(j$); j$.QueryString = jasmineRequire.QueryString(); j$.HtmlSpecFilter = jasmineRequire.HtmlSpecFilter(); }; jasmineRequire.HtmlReporter = function(j$) { var noopTimer = { start: function() {}, elapsed: function() { return 0; } }; function HtmlReporter(options) { var env = options.env || {}, getContainer = options.getContainer, createElement = options.createElement, createTextNode = options.createTextNode, onRaiseExceptionsClick = options.onRaiseExceptionsClick || function() {}, onThrowExpectationsClick = options.onThrowExpectationsClick || function() {}, onRandomClick = options.onRandomClick || function() {}, addToExistingQueryString = options.addToExistingQueryString || defaultQueryString, timer = options.timer || noopTimer, results = [], specsExecuted = 0, failureCount = 0, pendingSpecCount = 0, htmlReporterMain, symbols, failedSuites = []; this.initialize = function() { clearPrior(); htmlReporterMain = createDom('div', {className: 'jasmine_html-reporter'}, createDom('div', {className: 'jasmine-banner'}, createDom('a', {className: 'jasmine-title', href: 'http://jasmine.github.io/', target: '_blank'}), createDom('span', {className: 'jasmine-version'}, j$.version) ), createDom('ul', {className: 'jasmine-symbol-summary'}), createDom('div', {className: 'jasmine-alert'}), createDom('div', {className: 'jasmine-results'}, createDom('div', {className: 'jasmine-failures'}) ) ); getContainer().appendChild(htmlReporterMain); }; var totalSpecsDefined; this.jasmineStarted = function(options) { totalSpecsDefined = options.totalSpecsDefined || 0; timer.start(); }; var summary = createDom('div', {className: 'jasmine-summary'}); var topResults = new j$.ResultsNode({}, '', null), currentParent = topResults; this.suiteStarted = function(result) { currentParent.addChild(result, 'suite'); currentParent = currentParent.last(); }; this.suiteDone = function(result) { if (result.status == 'failed') { failedSuites.push(result); } if (currentParent == topResults) { return; } currentParent = currentParent.parent; }; this.specStarted = function(result) { currentParent.addChild(result, 'spec'); }; var failures = []; this.specDone = function(result) { if(noExpectations(result) && typeof console !== 'undefined' && typeof console.error !== 'undefined') { console.error('Spec \'' + result.fullName + '\' has no expectations.'); } if (result.status != 'disabled') { specsExecuted++; } if (!symbols){ symbols = find('.jasmine-symbol-summary'); } symbols.appendChild(createDom('li', { className: noExpectations(result) ? 'jasmine-empty' : 'jasmine-' + result.status, id: 'spec_' + result.id, title: result.fullName } )); if (result.status == 'failed') { failureCount++; var failure = createDom('div', {className: 'jasmine-spec-detail jasmine-failed'}, createDom('div', {className: 'jasmine-description'}, createDom('a', {title: result.fullName, href: specHref(result)}, result.fullName) ), createDom('div', {className: 'jasmine-messages'}) ); var messages = failure.childNodes[1]; for (var i = 0; i < result.failedExpectations.length; i++) { var expectation = result.failedExpectations[i]; messages.appendChild(createDom('div', {className: 'jasmine-result-message'}, expectation.message)); messages.appendChild(createDom('div', {className: 'jasmine-stack-trace'}, expectation.stack)); } failures.push(failure); } if (result.status == 'pending') { pendingSpecCount++; } }; this.jasmineDone = function(doneResult) { var banner = find('.jasmine-banner'); var alert = find('.jasmine-alert'); var order = doneResult && doneResult.order; alert.appendChild(createDom('span', {className: 'jasmine-duration'}, 'finished in ' + timer.elapsed() / 1000 + 's')); banner.appendChild( createDom('div', { className: 'jasmine-run-options' }, createDom('span', { className: 'jasmine-trigger' }, 'Options'), createDom('div', { className: 'jasmine-payload' }, createDom('div', { className: 'jasmine-exceptions' }, createDom('input', { className: 'jasmine-raise', id: 'jasmine-raise-exceptions', type: 'checkbox' }), createDom('label', { className: 'jasmine-label', 'for': 'jasmine-raise-exceptions' }, 'raise exceptions')), createDom('div', { className: 'jasmine-throw-failures' }, createDom('input', { className: 'jasmine-throw', id: 'jasmine-throw-failures', type: 'checkbox' }), createDom('label', { className: 'jasmine-label', 'for': 'jasmine-throw-failures' }, 'stop spec on expectation failure')), createDom('div', { className: 'jasmine-random-order' }, createDom('input', { className: 'jasmine-random', id: 'jasmine-random-order', type: 'checkbox' }), createDom('label', { className: 'jasmine-label', 'for': 'jasmine-random-order' }, 'run tests in random order')) ) )); var raiseCheckbox = find('#jasmine-raise-exceptions'); raiseCheckbox.checked = !env.catchingExceptions(); raiseCheckbox.onclick = onRaiseExceptionsClick; var throwCheckbox = find('#jasmine-throw-failures'); throwCheckbox.checked = env.throwingExpectationFailures(); throwCheckbox.onclick = onThrowExpectationsClick; var randomCheckbox = find('#jasmine-random-order'); randomCheckbox.checked = env.randomTests(); randomCheckbox.onclick = onRandomClick; var optionsMenu = find('.jasmine-run-options'), optionsTrigger = optionsMenu.querySelector('.jasmine-trigger'), optionsPayload = optionsMenu.querySelector('.jasmine-payload'), isOpen = /\bjasmine-open\b/; optionsTrigger.onclick = function() { if (isOpen.test(optionsPayload.className)) { optionsPayload.className = optionsPayload.className.replace(isOpen, ''); } else { optionsPayload.className += ' jasmine-open'; } }; if (specsExecuted < totalSpecsDefined) { var skippedMessage = 'Ran ' + specsExecuted + ' of ' + totalSpecsDefined + ' specs - run all'; alert.appendChild( createDom('span', {className: 'jasmine-bar jasmine-skipped'}, createDom('a', {href: '?', title: 'Run all specs'}, skippedMessage) ) ); } var statusBarMessage = ''; var statusBarClassName = 'jasmine-bar '; if (totalSpecsDefined > 0) { statusBarMessage += pluralize('spec', specsExecuted) + ', ' + pluralize('failure', failureCount); if (pendingSpecCount) { statusBarMessage += ', ' + pluralize('pending spec', pendingSpecCount); } statusBarClassName += (failureCount > 0) ? 'jasmine-failed' : 'jasmine-passed'; } else { statusBarClassName += 'jasmine-skipped'; statusBarMessage += 'No specs found'; } var seedBar; if (order && order.random) { seedBar = createDom('span', {className: 'jasmine-seed-bar'}, ', randomized with seed ', createDom('a', {title: 'randomized with seed ' + order.seed, href: seedHref(order.seed)}, order.seed) ); } alert.appendChild(createDom('span', {className: statusBarClassName}, statusBarMessage, seedBar)); for(i = 0; i < failedSuites.length; i++) { var failedSuite = failedSuites[i]; for(var j = 0; j < failedSuite.failedExpectations.length; j++) { var errorBarMessage = 'AfterAll ' + failedSuite.failedExpectations[j].message; var errorBarClassName = 'jasmine-bar jasmine-errored'; alert.appendChild(createDom('span', {className: errorBarClassName}, errorBarMessage)); } } var results = find('.jasmine-results'); results.appendChild(summary); summaryList(topResults, summary); function summaryList(resultsTree, domParent) { var specListNode; for (var i = 0; i < resultsTree.children.length; i++) { var resultNode = resultsTree.children[i]; if (resultNode.type == 'suite') { var suiteListNode = createDom('ul', {className: 'jasmine-suite', id: 'suite-' + resultNode.result.id}, createDom('li', {className: 'jasmine-suite-detail'}, createDom('a', {href: specHref(resultNode.result)}, resultNode.result.description) ) ); summaryList(resultNode, suiteListNode); domParent.appendChild(suiteListNode); } if (resultNode.type == 'spec') { if (domParent.getAttribute('class') != 'jasmine-specs') { specListNode = createDom('ul', {className: 'jasmine-specs'}); domParent.appendChild(specListNode); } var specDescription = resultNode.result.description; if(noExpectations(resultNode.result)) { specDescription = 'SPEC HAS NO EXPECTATIONS ' + specDescription; } if(resultNode.result.status === 'pending' && resultNode.result.pendingReason !== '') { specDescription = specDescription + ' PENDING WITH MESSAGE: ' + resultNode.result.pendingReason; } specListNode.appendChild( createDom('li', { className: 'jasmine-' + resultNode.result.status, id: 'spec-' + resultNode.result.id }, createDom('a', {href: specHref(resultNode.result)}, specDescription) ) ); } } } if (failures.length) { alert.appendChild( createDom('span', {className: 'jasmine-menu jasmine-bar jasmine-spec-list'}, createDom('span', {}, 'Spec List | '), createDom('a', {className: 'jasmine-failures-menu', href: '#'}, 'Failures'))); alert.appendChild( createDom('span', {className: 'jasmine-menu jasmine-bar jasmine-failure-list'}, createDom('a', {className: 'jasmine-spec-list-menu', href: '#'}, 'Spec List'), createDom('span', {}, ' | Failures '))); find('.jasmine-failures-menu').onclick = function() { setMenuModeTo('jasmine-failure-list'); }; find('.jasmine-spec-list-menu').onclick = function() { setMenuModeTo('jasmine-spec-list'); }; setMenuModeTo('jasmine-failure-list'); var failureNode = find('.jasmine-failures'); for (var i = 0; i < failures.length; i++) { failureNode.appendChild(failures[i]); } } }; return this; function find(selector) { return getContainer().querySelector('.jasmine_html-reporter ' + selector); } function clearPrior() { // return the reporter var oldReporter = find(''); if(oldReporter) { getContainer().removeChild(oldReporter); } } function createDom(type, attrs, childrenVarArgs) { var el = createElement(type); for (var i = 2; i < arguments.length; i++) { var child = arguments[i]; if (typeof child === 'string') { el.appendChild(createTextNode(child)); } else { if (child) { el.appendChild(child); } } } for (var attr in attrs) { if (attr == 'className') { el[attr] = attrs[attr]; } else { el.setAttribute(attr, attrs[attr]); } } return el; } function pluralize(singular, count) { var word = (count == 1 ? singular : singular + 's'); return '' + count + ' ' + word; } function specHref(result) { return addToExistingQueryString('spec', result.fullName); } function seedHref(seed) { return addToExistingQueryString('seed', seed); } function defaultQueryString(key, value) { return '?' + key + '=' + value; } function setMenuModeTo(mode) { htmlReporterMain.setAttribute('class', 'jasmine_html-reporter ' + mode); } function noExpectations(result) { return (result.failedExpectations.length + result.passedExpectations.length) === 0 && result.status === 'passed'; } } return HtmlReporter; }; jasmineRequire.HtmlSpecFilter = function() { function HtmlSpecFilter(options) { var filterString = options && options.filterString() && options.filterString().replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); var filterPattern = new RegExp(filterString); this.matches = function(specName) { return filterPattern.test(specName); }; } return HtmlSpecFilter; }; jasmineRequire.ResultsNode = function() { function ResultsNode(result, type, parent) { this.result = result; this.type = type; this.parent = parent; this.children = []; this.addChild = function(result, type) { this.children.push(new ResultsNode(result, type, this)); }; this.last = function() { return this.children[this.children.length - 1]; }; } return ResultsNode; }; jasmineRequire.QueryString = function() { function QueryString(options) { this.navigateWithNewParam = function(key, value) { options.getWindowLocation().search = this.fullStringWithNewParam(key, value); }; this.fullStringWithNewParam = function(key, value) { var paramMap = queryStringToParamMap(); paramMap[key] = value; return toQueryString(paramMap); }; this.getParam = function(key) { return queryStringToParamMap()[key]; }; return this; function toQueryString(paramMap) { var qStrPairs = []; for (var prop in paramMap) { qStrPairs.push(encodeURIComponent(prop) + '=' + encodeURIComponent(paramMap[prop])); } return '?' + qStrPairs.join('&'); } function queryStringToParamMap() { var paramStr = options.getWindowLocation().search.substring(1), params = [], paramMap = {}; if (paramStr.length > 0) { params = paramStr.split('&'); for (var i = 0; i < params.length; i++) { var p = params[i].split('='); var value = decodeURIComponent(p[1]); if (value === 'true' || value === 'false') { value = JSON.parse(value); } paramMap[decodeURIComponent(p[0])] = value; } } return paramMap; } } return QueryString; };
var Dungeon = { LEVEL: 1, attackVariance: 5, weaponTypes: [ { weaponName: "Wooden Stick", damage: 4, xp: 0 }, { weaponName: "Brass Knuckles", damage: 7, xp: 5 }, { weaponName: "Serrated Dagger", damage: 12, xp: 5 }, { weaponName: "Katana", damage: 16, xp: 5 }, { weaponName: "Reaper's scythe", damage: 22, xp: 5 }, { weaponName: "Large Trout", damage: 30, xp: 5 } ], Helper: { random: function(min, max) { //random value between [min,max] return Math.round(Math.random() * (max-min) + min); }, min: function(a, b) { return a < b ? a : b; }, max: function(a, b) { return a > b ? a : b; } }, Point: function(x, y) { this.x = x; this.y = y; }, Node: function(value) { this.value = value; this.lchild = undefined; this.rchild = undefined; }, Container: function(x, y, width, height) { this.x = x; this.y = y; this.width = width; this.height = height; this.center = new Dungeon.Point( ((width % 2 !== 0 ? Math.floor(width/2) : (width/2) - 1) + x), ((height % 2 !== 0 ? Math.floor(height/2) : (height/2) - 1) + y) ); }, Map: function(rows, cols, lists, entityIds) { this.height = rows; this.width = cols; this.floor = entityIds.floor; this.wall = entityIds.wall; this.enemy = entityIds.enemy; this.health = entityIds.health; this.weapon = entityIds.weapon; this.nextlvl = entityIds.nextlvl; this.player = entityIds.player; this.boss = entityIds.boss; this.roomlist = lists.roomlist; this.corridorlist = lists.corridorlist; this.entitylist = lists.entitylist; this.terrain = (function(wall) { var map = []; for(var y = 0; y < rows; y++) { var row = []; for(var x = 0; x < cols; x++) { row.push(wall); } map.push(row); } return map; }(this.wall)); }, Room: function(c) { if(Dungeon.Helper.min(c.width, c.height) / Dungeon.Helper.max(c.width, c.height) < 0.45) { if(Dungeon.Helper.max(c.width, c.height) === c.width) { this.height = Dungeon.Helper.random(c.height * 0.5, c.height); this.y = c.y + Dungeon.Helper.random(0, c.height - this.height); this.width = Math.ceil(this.height / 0.45); this.x = c.x + Math.floor((c.width / 2) - (this.width / 2)); } else { //c.height is bigger this.width = Dungeon.Helper.random(c.width * 0.5, c.width); this.x = c.x + Dungeon.Helper.random(0, c.width - this.width); this.height = Math.ceil(this.width / 0.45); this.y = c.y + Math.floor((c.height / 2) - (this.height / 2)); } } else { this.width = Dungeon.Helper.random(c.width * 0.5, c.width - 2); this.height = Dungeon.Helper.random(c.height * 0.5, c.height - 2); this.x = c.x + Dungeon.Helper.random(1, (c.width - 2) - this.width); this.y = c.y + Dungeon.Helper.random(1, (c.height - 2) - this.height); } }, Entity: function(room, type) { this.x = Dungeon.Helper.random(room.x, room.x + room.width - 1); this.y = Dungeon.Helper.random(room.y, room.y + room.height - 1); switch(type) { case "enemy": this.type = type; this.stats = { health: 5 + (Dungeon.LEVEL * 20), attack: 12 + (Dungeon.LEVEL * 5), xp: 10 + (Dungeon.LEVEL * 5) }; break; case "health": this.type = type; this.stats = { heal: Dungeon.Helper.random(30,60) + (Dungeon.LEVEL * 5), xp: 2 + (Dungeon.LEVEL * 2) - 1 }; break; case "weapon": this.type = type; this.stats = Dungeon.weaponTypes[Dungeon.LEVEL]; break; case "nextlvl": this.type = type; this.stats = null; break; case "player": this.type = type; this.stats = { health: 100, weapon: Dungeon.weaponTypes[0], xp: 0, level: 0, toNextLevel: 60 }; break; default: console.error("new Entity() Invalid type name: ", type); break; } }, Boss: function(room) { this.x = Dungeon.Helper.random(room.x, room.x + room.width - 2); this.y = Dungeon.Helper.random(room.y, room.y + room.height -2); this.width = 2; this.height = 2; this.type = "boss"; this.stats = { health: 300, attack: 45, xp: 200 }; }, growTree: function(container, iter) { var root = new Dungeon.Node(container); var subc = container.split(); if(iter != 0) { root.lchild = Dungeon.growTree(subc[0], iter - 1); root.rchild = Dungeon.growTree(subc[1], iter - 1); } return root; }, itemPositionIsUnique: function(base, next) { for(var i = 0; i < base.length; i++) { if(base[i].x === next.x && base[i].y === next.y) { return false; } } return true; }, bossPositionIsUnique: function(base, boss) { for(var i = 0; i < base.length; i++) { if(boss.x === base[i].x && boss.y === base[i].y) { return false; } if((boss.x + boss.width - 1) === base[i].x && boss.y === base[i].y) { return false; } if(boss.x === base[i].x && (boss.y + boss.height - 1) === base[i].y) { return false; } if((boss.x + boss.width - 1) === base[i].x && (boss.y + boss.height - 1) === base[i].y) { return false; } } return true; }, createEntities: function(list, room, type) { var e_max = Dungeon.Helper.random(0,1); for(var i = 0; i < e_max; i++) { do { var item = new Dungeon.Entity(room, type); } while(!Dungeon.itemPositionIsUnique(list, item)); list.push(item); } return list; }, createBoss : function(list, room) { do { var boss = new Dungeon.Boss(room); } while(!Dungeon.bossPositionIsUnique(list, boss)); list.push(boss); return list; }, createDungeon: function(args) { if(args.entities.wall === undefined || args.entities.floor === undefined) { throw new Error("Dungeon.createDungeon() entities object must at least hold 'wall' and 'floor' properties"); } var root_container = new Dungeon.Container(1,1, args.width - 2, args.height - 2); var containers = Dungeon.growTree(root_container, args.iterations).toArray(); var room_template = containers.slice(containers.length / 2); var corridors = []; var rooms = []; var entities = []; for(var cor = 1; cor < containers.length; cor += 2) { corridors.push({ start: containers[cor].center, end: containers[cor+1].center }); } for(var ri = 0; ri < room_template.length; ri++) { var room = new Dungeon.Room(room_template[ri]); rooms.push(room); } if(args.entities.player !== undefined) { var player = new Dungeon.Entity(rooms[Dungeon.Helper.random(0, rooms.length-1)], "player"); entities.push(player); } if(args.entities.nextlvl !== undefined) { var exit = new Dungeon.Entity(rooms[0], "nextlvl"); entities.push(exit); } if(args.entities.weapon !== undefined) { var weapon = new Dungeon.Entity(rooms[rooms.length - 1], "weapon"); entities.push(weapon); } if(args.entities.enemy !== undefined) { for(var ei = 0; ei < rooms.length; ei++) { Dungeon.createEntities(entities, rooms[ei], "enemy"); } } if(args.entities.health !== undefined) { for(var hi = 0; hi < rooms.length; hi++) { Dungeon.createEntities(entities, rooms[hi], "health") } } if(args.entities.boss !== undefined) { Dungeon.createBoss(entities, rooms[Dungeon.Helper.random(0, rooms.length - 1)]); } var map_template = new Dungeon.Map( args.height, args.width, { roomlist: rooms, corridorlist: corridors, entitylist: entities }, { wall: args.entities.wall, floor: args.entities.floor, enemy: args.entities.enemy !== undefined ? args.entities.enemy : null, health: args.entities.health !== undefined ? args.entities.health : null, weapon: args.entities.weapon !== undefined ? args.entities.weapon : null, nextlvl: args.entities.nextlvl !== undefined ? args.entities.nextlvl : null, player: args.entities.player !== undefined ? args.entities.player : null, boss: args.entities.boss !== undefined ? args.entities.boss : null } ); for(var c_nr = 0; c_nr < corridors.length; c_nr++) { map_template.drawCorridor(corridors[c_nr].start, corridors[c_nr].end); } for(var room_nr = 0; room_nr < rooms.length; room_nr++) { map_template.drawRoom(rooms[room_nr]); } for(var ent_nr = 0; ent_nr < entities.length; ent_nr++) { map_template.drawEntity(entities[ent_nr]); } return map_template; }, render: function(dungeonMap, target) { var map_table = document.createElement('table'); var map_body = document.createElement('tbody'); for(var i = 0; i < dungeonMap.terrain.length; i++) { var row = document.createElement('tr'); for(var j = 0; j < dungeonMap.terrain[i].length; j++) { var cell = document.createElement('td'); if(dungeonMap.terrain[i][j] === dungeonMap.wall) { cell.classList.add('wall'); } if(dungeonMap.terrain[i][j] === dungeonMap.floor) { cell.classList.add('floor'); } if(dungeonMap.terrain[i][j] === dungeonMap.enemy) { cell.classList.add('enemy'); } if(dungeonMap.terrain[i][j] === dungeonMap.health) { cell.classList.add('health'); } if(dungeonMap.terrain[i][j] === dungeonMap.weapon) { cell.classList.add('weapon'); } if(dungeonMap.terrain[i][j] === dungeonMap.nextlvl) { cell.classList.add('nextlvl'); } if(dungeonMap.terrain[i][j] === dungeonMap.player) { cell.classList.add('player'); } if(dungeonMap.terrain[i][j] === dungeonMap.boss) { cell.classList.add('boss'); } row.appendChild(cell); } map_body.appendChild(row); } map_table.appendChild(map_body); target.appendChild(map_table); } }; Dungeon.Node.prototype.toArray = function(target, i) { i = i === undefined ? 0 : i; target = target === undefined ? [] : target; if(this.lchild !== undefined) { this.lchild.toArray(target, 2*i+1); } target[i] = this.value; if(this.rchild !== undefined) { this.rchild.toArray(target, 2*i+2); } return target; }; Dungeon.Container.prototype.split = function(maxR) { maxR = maxR || 0.45; var c1, c2; if(Dungeon.Helper.random(0,1) === 0) { //split at x axis c1 = new Dungeon.Container( this.x, this.y, Dungeon.Helper.random(this.width * maxR, this.width * (1 - maxR)), this.height ); c2 = new Dungeon.Container( this.x + c1.width, this.y, this.width - c1.width, this.height ); return [c1, c2]; } else { //split at y axis c1 = new Dungeon.Container( this.x, this.y, this.width, Dungeon.Helper.random(this.height * maxR, this.height * (1 - maxR)) ); c2 = new Dungeon.Container( this.x, this.y + c1.height, this.width, this.height - c1.height ); return [c1, c2]; } }; Dungeon.Point.prototype.equals = function(refp) { if(!(refp instanceof Dungeon.Point)) { throw new TypeError("Point.equals() argument must be a Point"); } else { return this.x === refp.x && this.y === refp.y; } }; Dungeon.Point.prototype.isVerticalTo = function(refp) { if(!(refp instanceof Dungeon.Point)) { throw new TypeError("Point.equals() argument must be a Point"); } else { return this.x === refp.x && this.y !== refp.y; } }; Dungeon.Point.prototype.isHorizontalTo = function(refp) { if(!(refp instanceof Dungeon.Point)) { throw new TypeError("Point.equals() argument must be a Point"); } else { return this.y === refp.y && this.x !== refp.x; } }; Dungeon.Map.prototype.drawEntity = function(entity) { if(entity instanceof Dungeon.Boss) { for(var y = entity.y; y < (entity.y + entity.height); y++) { for(var x = entity.x; x < (entity.x + entity.width); x++) { this.terrain[y][x] = this[entity.type]; } } } else if(!(entity instanceof Dungeon.Entity)) { throw new TypeError("Map.drawEntity() argument must be Entity"); } else { this.terrain[entity.y][entity.x] = this[entity.type]; } }; Dungeon.Map.prototype.drawCorridor = function(p1, p2) { if(!(p1 instanceof Dungeon.Point) || !(p2 instanceof Dungeon.Point)) { throw new TypeError("Map.drawCorridor() arguments must be from Point"); } else { if(p1.isHorizontalTo(p2)) { //line is horizonal var bigger = p1.x > p2.x ? p1.x : p2.x; var smaller = p1.x < p2.x ? p1.x : p2.x; for(var x = smaller; x <= bigger; x++) { this.terrain[p1.y][x] = this.floor; } } else if(p1.isVerticalTo(p2)) { //line is vertical var bigger = p1.y > p2.y ? p1.y : p2.y; var smaller = p1.y < p2.y ? p1.y : p2.y; for(var y = smaller; y <= bigger; y++) { this.terrain[y][p1.x] = this.floor; } } else if(p1.equals(p2)) { //just draw a point this.terrain[p1.y][p1.x] = this.floor; } } }; Dungeon.Map.prototype.drawRoom = function(room) { if(!(room instanceof Dungeon.Room)) { throw new TypeError("Map.drawRoom() argument must be Room"); } else { for(var y = room.y; y < (room.y + room.height); y++) { for(var x = room.x; x < (room.x + room.width); x++) { //console.log(this.terrain[y][x]); this.terrain[y][x] = this.floor; } } } };
version https://git-lfs.github.com/spec/v1 oid sha256:5eae0a783d81b87e71f9f6626dc1cb356f896c8df874e7a7d72b7181075c3128 size 339
describe('app', function () { 'use strict'; var module, dependencies; beforeEach(function () { module = angular.module('app'); dependencies = module.requires; }); it('should be defined', function () { expect(module).not.toBeUndefined(); }); describe('check defined dependencies:', function () { var hasModule = function (module) { return dependencies.indexOf(module) >= 0; }; it('check services module is dependency of app', function () { expect(hasModule('ngRoute')).toBeTruthy(); expect(hasModule('services')).toBeTruthy(); expect(hasModule('controllers')).toBeTruthy(); }); }); });
// @flow function _validate(rules: Object, state: Object): Object { return Object.keys(rules).reduce((validation: Object, key: string) => { if (typeof rules[key] === "function") { validation[key] = rules[key](state); return validation; } if (typeof rules[key] === "object" && typeof state[key] === "object") { validation[key] = _validate(rules[key], state[key]); return validation; } return validation; }, {}); } function _isValid(validation): boolean { return Object.keys(validation).reduce((isValid, key) => { if (typeof validation[key] === "boolean") { return isValid && validation[key]; } return isValid && (typeof validation[key] === "undefined" || _isValid(validation[key])); }, true); } function stateValidation(stateMachine: SequentialStateMachine): SequentialStateMachine { let rules = {}; let validatedStateMachine = { addValidationRule: function (rule): void { rules = Object.assign({}, rules, rule); }, validate: function (): object { let state = stateMachine.currentState(); return _validate(rules, state); }, isValid: function (): boolean { return _isValid(this.validate()); } }; return Object.assign({}, stateMachine, validatedStateMachine); } const puzzleContainer = document.getElementById("puzzle"); const resetStateButton = document.getElementById("resetStateButton"); const forwardStateButton = document.getElementById("forwardStateButton"); const backStateButton = document.getElementById("backStateButton"); const stateIndexDisplay = document.getElementById("stateIndexDisplay"); const shuffleButton = document.getElementById("shuffleButton"); const puzzleCompletedMessagePanel = document.getElementById("puzzleCompletedMessage"); const puzzleSizeControl = document.getElementById("puzzleSize"); let puzzle; /** * Checks a move to see if it's valid * @param {number} puzzleWidth - the number tiles in a row * @param {object} move - which tile moves where * @returns {boolean} */ function _isValidMove(puzzleWidth: number, move: object): boolean { let keys = Object.keys(move); let distance = Math.abs(keys[0] - keys[1]); function isInSameRow(pos1: number, pos2: number, puzzleWidth: number): boolean { return Math.floor((pos1 - 1) / puzzleWidth) === Math.floor((pos2 - 1) / puzzleWidth); } return distance === puzzleWidth || (distance === 1 && isInSameRow(keys[0], keys[1], puzzleWidth)); } /** * * @param element * @param isComplete * @private */ function _markCompletion(element: Object, isComplete: boolean): void { if (isComplete) { element.classList.add("is-complete"); } else { element.classList.remove("is-complete"); } } function computeMove(state, puzzlePiece): Object { function findTilePosition(state: Object, puzzlePiece = null): Object { return Object.keys(state).find(key => { return state[key] === puzzlePiece; }); } let emptyPosition = findTilePosition(state); let tilePosition = findTilePosition(state, puzzlePiece); let move = {}; move[emptyPosition] = state[tilePosition]; move[tilePosition] = null; return move; } /** * * @param isValidMove * @param markCompletion * @param stateMachine * @param puzzleWidth * @param puzzlePiece * @returns {Function} * @private */ function _moveTile(render: Function, isValidMove: Function, markCompletion: Function, stateMachine: Object, puzzleWidth: Number, puzzlePiece: Object): void { return function () { let currentState = stateMachine.currentState(); let move = computeMove(currentState, puzzlePiece); if (isValidMove(move)) { stateMachine.addSequence(move); markCompletion(stateMachine.isValid()); return render(stateMachine.returnState(), stateMachine.currentIndex()); } }; } function _generatePuzzle(moveTile: Function, tileCount: number, puzzleHash = []): Element[] { let _puzzleHash = Object.assign({}, puzzleHash); let key = Object.keys(puzzleHash).length + 1; if (tileCount <= 1) { _puzzleHash[key] = null; return _puzzleHash; } let tile = document.createElement("div"); tile.classList.add("puzzle-piece"); tile.classList.add(`position-${key}`); tile.id = `puzzlePiece${key}`; Rx.Observable.fromEvent(tile, "click").subscribe(moveTile(tile)); _puzzleHash[key] = tile; return _generatePuzzle(moveTile, tileCount - 1, _puzzleHash) } function _moveToState(render: Function, markCompletion: Function, stateMachine: object, velocity: number): Object { return function () { markCompletion(stateMachine.isValid()); return render(stateMachine.moveToState(velocity), stateMachine.currentIndex()); } } function _reset(render: Function, stateMachine: Object): void { return function () { render(stateMachine.reset()); }; } function _render(state: Object, index = 0): void { Object.keys(state).forEach(key => { if (state[key] !== null) { state[key].className = `puzzle-piece position-${key}`; } }); stateIndexDisplay.innerHTML = index; } function _randomizeState(initialState: Object): Object { function randomize(countdown: number, state: Object) { if (countdown <= 0) { return state; } let tileCount = Object.keys(state).length; let pos1 = Math.round(Math.random() * (tileCount - 1) + 1); let pos2 = Math.round(Math.random() * (tileCount - 1) + 1); let transition1 = {}; let transition2 = {}; transition1[pos1] = state[pos2]; transition2[pos2] = state[pos1]; return randomize(countdown - 1, Object.assign({}, state, transition1, transition2)); } let totalCycles = Object.keys(initialState).length * 3; return randomize(totalCycles, initialState); } function _shuffle(randomizeState: Function, markCompletion: Function, render: Function, stateMachine: Object, completedPuzzleState: Object): void { return function () { if (stateMachine.setInitialState(randomizeState(completedPuzzleState))) { markCompletion(stateMachine.isValid()); return render(stateMachine.currentState()); } return _shuffle(randomizeState, markCompletion, render, stateMachine, completedPuzzleState)(); }; } // Very imperative here :-( function addPuzzle(completedPuzzleState: Object, puzzleContainer: Element): void { let tiles = Object.keys(completedPuzzleState) .filter(key => completedPuzzleState[key] !== null) .map(key => completedPuzzleState[key]); while (puzzleContainer.hasChildNodes()) { puzzleContainer.removeChild(puzzleContainer.lastChild); } tiles.forEach(tile => { puzzleContainer.append(tile); }); puzzleContainer.className = Array.from(puzzleContainer.classList) .filter(className => !(/puzzle-\d/).test(className)) .concat(`puzzle-${Math.sqrt(tiles.length + 1)}`) .join(" "); } function _validateTileInversions(initialState: object, puzzleWidth: number, state: object): boolean { let pieceOrder = Object.keys(initialState).filter(key => initialState[key] !== null).reduce((wmap, key) => { wmap.set(initialState[key], Number(key)); return wmap; }, (new WeakMap())); let tilePositions = Object.keys(state).filter(key => state[key] !== null).map(key => pieceOrder.get(state[key])); function countInversions(numArr: number[], _puzzleWidth: number): number { if (numArr.length <= 1) { return 0; } return numArr.filter(num => Number(numArr[0]) > Number(num)).length + countInversions(numArr.slice(1), _puzzleWidth); } // If the grid width is odd, then the number of inversions in a solvable situation is even. // If the grid width is even, and the blank is on an even row counting from the bottom (second-last, fourth-last etc), then the number of inversions in a solvable situation is odd. // If the grid width is even, and the blank is on an odd row counting from the bottom (last, third-last, fifth-last etc) then the number of inversions in a solvable situation is even. // That gives us this formula for determining invariance: // // ( (grid width odd) && (#inversions even) ) || ( (grid width even) && ((blank on odd row from bottom) == (#inversions even)) ) let inversionsCount = countInversions(tilePositions, puzzleWidth); let gridWidthIsEven = puzzleWidth / 2 === Math.floor(puzzleWidth / 2); let inversionsIsEven = inversionsCount / 2 === Math.floor(inversionsCount / 2); let rowCount = Math.ceil(Object.keys(initialState).length / puzzleWidth); let blankPosition = Object.keys(initialState).map((key, index) => (initialState[key] === null ? index + 1 : NaN)).find(num => !isNaN(num)); let blankRowFromBottom = rowCount - Math.ceil(blankPosition / puzzleWidth) + 1; let blankOnOddRowFromBttom = blankRowFromBottom / 2 !== Math.floor(blankRowFromBottom/2); return ( !gridWidthIsEven && inversionsIsEven ) || ( gridWidthIsEven && (blankOnOddRowFromBttom === inversionsIsEven)); } function _isCompleted(completedState, currentState) { return R.equals(completedState, currentState) } function initializePuzzle(size: number = 3): void { puzzle = new Puzzle(size, puzzleContainer, puzzleCompletedMessagePanel, forwardStateButton, backStateButton, resetStateButton, shuffleButton); } class Puzzle { constructor(size, puzzleContainer, puzzleCompletedMessagePanel, forwardStateButton, backStateButton, resetStateButton, shuffleButton) { const markCompletion = R.curry(_markCompletion)(puzzleCompletedMessagePanel); const render = _render; const isValidMove = R.curry(_isValidMove)(size); let stateMachine = invariantCheck(stateValidation(IndexedStateMachine.create())); const moveTile = R.curry(_moveTile)(render)(isValidMove)(markCompletion)(stateMachine)(size); const completedPuzzleState = _generatePuzzle(moveTile, Math.pow(size, 2)); stateMachine.addInvariantRule(R.curry(_validateTileInversions)(completedPuzzleState)(size)); stateMachine.addValidationRule({one: R.curry(_isCompleted)(completedPuzzleState)}); const moveToState = R.curry(_moveToState)(render)(markCompletion)(stateMachine); const reset = _reset(render, stateMachine); const randomizeState = _randomizeState(completedPuzzleState); const shuffle = _shuffle(_randomizeState, markCompletion, render, stateMachine, completedPuzzleState); stateMachine.setInitialState(completedPuzzleState); addPuzzle(completedPuzzleState, puzzleContainer); render(stateMachine.returnState(), stateMachine.currentIndex()); Rx.Observable.fromEvent(forwardStateButton, "click").subscribe(moveToState(1)); Rx.Observable.fromEvent(backStateButton, "click").subscribe(moveToState(-1)); Rx.Observable.fromEvent(resetStateButton, "click").subscribe(reset); Rx.Observable.fromEvent(shuffleButton, "click").subscribe(shuffle); puzzleCompletedMessagePanel.classList.remove("is-complete"); } } Rx.Observable.fromEvent(puzzleSizeControl, "change").subscribe((event) => { const puzzleSize = Math.floor(Number(event.target.value)); if (puzzleSize <= 6 && puzzleSize >= 3) { return initializePuzzle(puzzleSize); } }); initializePuzzle(3);
const axios = require('axios') const express = require('express') const _ = require('lodash') const { url } = require('../../config') const { onError, getData } = require('../lib') const router = express.Router() const nearby = ({ lat, lng }, r = 0.5) => `lat_gte=${lat - r}&lat_lte=${lat + r}&lng_gte=${lng - r}&lng_lte=${lng + r}&_expand=product` const getHotDeals = ({ lat, lng }) => axios.get(url + `/purchases?${nearby({ lat, lng })}&_expand=product`) .then(getData) module.exports = io => { io.on('connection', (client) => { console.log('client connected', client.id) io.emit('review', { much: 'wow!' }) client.on('getNotifications', ({ lat = 47, lng = 8.5, userId = 1 }) => { getHotDeals({ lat, lng }).then(deals => { console.warn('deals', deals) io.emit('newHotDeals', deals) }) }) }) const getNotifications = (req, res, next) => { let { lat = 47, lng = 8.5, userId = 1 } = req.query // ehh.. lat = Number(lat) lng = Number(lng) userId = _.parseInt(userId) // return res.json({ lat, lng, userId }) // find hot nearby hot purchases // curl 'localhost:3000/purchases?lat_gte=45&lat_lte=47.9&lng_gte=8&lng_lte=8.5&_expand=product' return getHotDeals({ lat, lng }) .then(data => res.json(data)) .catch(onError(next)) } router.get('/', getNotifications) return router }
'use strict'; const extend = require('extend'); const mongoose = require('mongoose'); const debug = require('debug')('hds:init'); const mongo = require('./mongo'); var defaultOptions = { database: { host: '127.0.0.1', port: 27017, name: 'hds', user: null, pass: null } }; var customs = {}; exports.init = function initHds(options) { options = extend(true, {}, defaultOptions, options); return new Promise(function (resolve, reject) { if (typeof options.database === 'string') { mongoose.connect(options.database); } else { var mongoOptions = {}; var dbOptions = options.database; if (dbOptions.user && dbOptions.pass) { mongoOptions.user = dbOptions.user; mongoOptions.pass = dbOptions.pass; } mongoose.connect(dbOptions.host, dbOptions.name, dbOptions.port, mongoOptions); } var conn = mongoose.connection; conn.on('error', reject); conn.once('open', function () { debug('mongoDB connection established'); mongo._setMongo(conn.db); resolve(); }); }); }; exports.close = function closeHds() { return new Promise(function (resolve) { mongoose.disconnect(function () { resolve(); }); }); }; exports.customCollection = function customCollection(name, schema) { if (customs[name]) { return customs[name]; } if (schema) { if (!schema instanceof mongoose.Schema) { schema = new mongoose.Schema(schema); } return customs[name] = mongoose.model('custom_' + name, schema, 'custom_' + name); } else { throw new Error('Custom collection ' + name + ' is not defined yet'); } }; exports.dropDatabase = function dropDatabase() { return new Promise(function (resolve, reject) { mongoose.connection.db.dropDatabase(function (err) { if (err) { return reject(err); } resolve(); }) }); }; exports.mongo = mongoose.mongo; exports.Schema = mongoose.Schema; exports.Kind = require('./kind'); exports.Entry = require('./entry'); exports.Query = require('./query'); exports.Group = require('./group');
/** * Created by Alex on 24/05/2015. */ /* TODO This view will contain the different templates such as movie-metadata, options menu (actors/awards/etc). The options menu will need to publish a event in order to know which detail view template has to be loaded. */ //# sourceMappingURL=metadata-view.js.map
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2015 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides enumeration for changes in model sap.ui.define(function() { "use strict"; /** * @class * Change Reason for ListBinding/TreeBinding. * * @static * @public * @alias sap.ui.model.ChangeReason */ var ChangeReason = { /** * The list was sorted * @public */ Sort: "sort", /** * The List was filtered * @public */ Filter: "filter", /** * The list has changed * @public */ Change: "change", /** * The list context has changed * @public */ Context: "context", /** * The list was refreshed * @public */ Refresh: "refresh", /** * The tree node was expanded * @public */ Expand: "expand", /** * The tree node was collapsed * @public */ Collapse: "collapse" }; return ChangeReason; }, /* bExport= */ true);
var inotify = require('inotify'), Inotify = inotify.Inotify, path = require('path'), util = require('util'), walker = require('walk'), log = require('winston'), fs = require('fs'), events = require('events'); /** * Creates a new watcher. * * @constructor * @extends events.EventEmitter * @param {string} root The directory to watch */ var Watcher = function(root) { Watcher.super_.call(this); this._root = path.normalize(root); this._inotify = new Inotify(); this._watches = {}; this._files = {}; this.on('newListener', this._replay.bind(this)); this._watch(this._root); }; util.inherits(Watcher, events.EventEmitter); /** * Recursively watches the given directory and notifies an update for every * nested file. * * @private * @param {string} directory The directory to recursively watch */ Watcher.prototype._watch = function(directory) { var self = this; // watch directory this._addWatch(directory); // recursively watch subdirectories and notify existing files walker.walk(directory).on('directory', function(root, stat, next) { self._addWatch(path.join(root, stat.name)); next(); }).on('file', function(root, stat, next) { var file = path.join(root, stat.name); self._update(file, stat); next(); }); }; /** * Watches the given directory. * * @private * @param {string} directory The directory to watch */ Watcher.prototype._addWatch = function(directory) { log.info('watching directory', directory); var wd = this._inotify.addWatch({ path: directory, watch_for: Inotify.IN_CLOSE_WRITE | Inotify.IN_CREATE | Inotify.IN_DELETE | Inotify.IN_MOVED_FROM | Inotify.IN_MOVED_TO, callback: this._onEvent.bind(this) }); this._watches[wd] = { directory: directory, watch: wd }; }; /** * Recursively unwatches the given directory and notifies a delete for every * nested file. * * @private * @param {string} directory The directory to recursively unwatch */ Watcher.prototype._unwatch = function(directory) { var prefix = directory + '/'; // unwatch directory and subdirectories for (var wd in this._watches) { if (this._watches[wd].directory === directory || this._watches[wd].directory.indexOf(prefix) === 0) { this._removeWatch(this._watches[wd].watch, false); } } // notify deletions for (var file in this._files) { if (file.indexOf(prefix) === 0) { this._delete(file); } } }; /** * Unwatches the given directory. * * @private * @param {number} wd The watch descriptor to unwatch * @param {boolean} auto When set to true, it means that the watch has been * automatically removed by inotify and we only have to clean our stuff */ Watcher.prototype._removeWatch = function(wd, auto) { var descriptor = this._watches[wd]; if (descriptor === undefined) { return; } log.info('unwatching directory', descriptor.directory); if (!auto) { this._inotify.removeWatch(wd); } delete this._watches[wd]; }; /** * Fires a file creation event. * * @private * @param {string} file The created file */ Watcher.prototype._create = function(file) { log.debug('firing create', file); this.emit('create', file); // when hardlinking, consider this as an instantaneous create/write var stat = fs.statSync(file); if (stat.nlink > 1) { this._update(file, stat); } }; /** * Fires a file update event. * * @private * @param {string} file The updated file * @param {fs.Stats} stat The file stat (when undefined, this method will * synchronously retrieve it) */ Watcher.prototype._update = function(file, stat) { if (stat === undefined) { stat = fs.statSync(file); } this._files[file] = stat; log.debug('firing update', file); this.emit('update', file, stat); }; /** * Fires a file deletion event. * * @private * @param {string} file The deleted file */ Watcher.prototype._delete = function(file) { var stat = this._files[file]; if (stat !== undefined) { delete this._files[file]; log.debug('firing delete', file); this.emit('delete', file); } }; /** * Replays creation and update events for new listeners. * * @private * @param {string} event The event to replay * @param {Function} listener The new listener */ Watcher.prototype._replay = function(event, listener) { for (var file in this._files) { if (typeof this._files[file] === 'boolean' && event === 'create') { listener(file); } else if (event === 'update') { listener(file, this._files[file]); } } }; /** * Converts an event to the path of the file that triggered this event. * * @private * @param {Object} event The inotify event * @return {string} the path of the file that triggered this event */ Watcher.prototype._toPath = function(event) { var descriptor = this._watches[event.watch]; if (descriptor !== undefined) { return path.join(descriptor.directory, event.name); } else { log.warn('can\'t convert event to path, unknown wd', event); return undefined; } }; /** * The inotify event listener. * * @private * @param {Object} event The inotify event */ Watcher.prototype._onEvent = function(event) { if (event.mask & Inotify.IN_CLOSE_WRITE) { log.debug('IN_CLOSE_WRITE', event); // fire update this._update(this._toPath(event), undefined); } else if (event.mask & Inotify.IN_CREATE) { log.debug('IN_CREATE', event); // watch new directory if (event.mask & Inotify.IN_ISDIR) { this._addWatch(this._toPath(event)); } // fire create else { this._create(this._toPath(event)); } } else if (event.mask & Inotify.IN_DELETE) { log.debug('IN_DELETE', event); // fire delete if ((event.mask & Inotify.IN_ISDIR) === 0) { this._delete(this._toPath(event)); } } else if (event.mask & Inotify.IN_MOVED_FROM) { log.debug('IN_MOVED_FROM', event); // unwatch moved away directory if (event.mask & Inotify.IN_ISDIR) { this._unwatch(this._toPath(event)); } // fire delete else { this._delete(this._toPath(event)); } } else if (event.mask & Inotify.IN_MOVED_TO) { log.debug('IN_MOVED_TO', event); // watch moved in directory if (event.mask & Inotify.IN_ISDIR) { this._watch(this._toPath(event)); } // fire create else { this._create(this._toPath(event)); } } else if (event.mask & Inotify.IN_IGNORED) { log.debug('IN_IGNORED', event); // cleanup this._removeWatch(event.watch, true); } else { log.warn('unexpected event', event); } }; /** * Closes the watcher object. */ Watcher.prototype.close = function() { this._inotify.close(); }; /** * Exports the Watcher class. */ module.exports.Watcher = Watcher; /** * Watches a location for file creation, deletion or modifications. The method * returns an event emitter which sends 3 different events: * - 'create': when a new file is created (argument: the file) * - 'delete': when a file is deleted (argument: the file) * - 'update': when a file is updated (argument: the file and its stats) * * Note that upon registration, the watcher sends an 'update' event for every * existing file. * * When done, the watcher can be closed using its close() method and safely * discarded. * * @param {string} location The location to watch * @return {Watcher} the watcher */ module.exports.watch = function(location) { return new Watcher(location); };
'use strict'; /** * @ngdoc directive * @name konga.directive:tableCell * @description * # tableCell */ angular.module('konga') .directive('tableCell', ['util', '$filter', 'configurationManager', 'mapper', function (util, $filter, configurationManager, mapper) { return { templateUrl: '/konga/views/table-cell.html', restrict: 'E', replace: true, scope: { entity: '=', field: '=' }, link: function postLink(scope, element) { scope.content = ''; scope.type = 'text'; scope.styles = []; scope.preffix = ''; scope.suffix = ''; scope.custom = null; scope.title = ""; var useList = true; //var fieldWatcher; var entityWatcher; function setupValue() { var fieldEntity = scope.entity; // Lookup for complex fields var mapped = null; if(scope.field.derived) { if(scope.field.derivedSource) { fieldEntity = $filter('mapField')(scope.entity, scope.field.derivedSource); if(scope.field.isSelf) { mapped = fieldEntity; } } } if(!mapped) { mapped = $filter('mapField')(fieldEntity, scope.field); } // Render depending on the data type switch(scope.field.fieldType.results) { case util.constants.FIELD_DATE: scope.content = mapped !== 0 ? $filter('date')(mapped, 'dd/MM/yyyy') : ''; break; case util.constants.FIELD_DATETIME: scope.content = mapped !== 0 ? $filter('date')(mapped, 'dd/MM/yyyy HH:mm:ss') : ''; break; case util.constants.FIELD_BOOLEAN: var content = $filter('activeInactive')(mapped, scope.field); scope.content = $filter('translate')(content); // scope.contentUrl = views.translated; break; case util.constants.FIELD_IMAGE: scope.type = 'image'; scope.content = mapped; scope.image = { width: 30, height: 30, }; // Read configuration var conf = scope.field.fieldType.configuration[0]; var width = $filter('filter')(conf, { key: 'IMAGE_WIDTH' }, true)[0]; var height = $filter('filter')(conf, { key: 'IMAGE_HEIGHT' }, true)[0]; if(width) { scope.image.width = width.value; } if(height) { scope.image.height = height.value; } break; case util.constants.FIELD_PRICE: var configuration = scope.field.fieldType.configuration[0]; var currency = $filter('filter')(configuration, { key: 'CURRENCY' }, true)[0]; scope.suffix = currency.value; scope.styles.push('text-right'); scope.content = $filter('number')(mapped, 2); break; case util.constants.FIELD_NUMBER: // Read decimals from config scope.styles.push('text-right'); scope.content = mapped; break; case util.constants.FIELD_CSS: scope.type = 'styling'; scope.styles.push('text-center'); scope.content = mapped; useList = false; // Get title // TODO Allow custom var list = scope.field.type.list; var listMatch = $filter('filter')(list, { key: (scope.content+"") }, true); if(listMatch.length) { var item = listMatch[0]; var content = item.value; scope.title = $filter('translate')(content); } break; case util.constants.FIELD_PLAIN_FILTERED: scope.type = 'plain-filtered'; scope.content = mapped; // Get the filter // TODO Or die :) var configuration = scope.field.fieldType.configuration[0]; var filter = $filter('filter')(configuration, { key: util.constants.TABLE_CELL_FILTER }, true)[0]; scope.filter = filter.value; break; case util.constants.FIELD_CUSTOM: scope.type = 'custom'; scope.content = mapped; var customConf = configurationManager.get(util.constants.CUSTOM_FIELD_TYPE, scope.field, util.constants.SCOPE_RESULTS); if(!customConf) { // TODO Throw exception } // Try to get mapped view scope.custom = mapper[customConf]; if(!scope.custom) { scope.custom = customConf; } break; case util.constants.FIELD_PLAIN: default: if(scope.field.type.type === util.constants.FIELD_COMPLEX) { scope.content = $filter('tableRendererComplex')(mapped, scope.field); } else { try { scope.content = $filter('translate')(mapped); } catch(e) { scope.content = mapped; } } } if(scope.field.type.list && useList) { var list = scope.field.type.list; var listMatch = $filter('filter')(list, { key: (scope.content+"") }, true); if(listMatch.length) { var item = listMatch[0]; var content = item.value; scope.content = $filter('translate')(content); } } if(scope.content === null || scope.content === undefined) { scope.content = ''; } } entityWatcher = scope.$watch('entity', function() { setupValue(); scope.updateContent(); entityWatcher(); // fieldWatcher(); }, true); var watchers = null; scope.$on('suspend', function() { watchers = scope.$$watchers; scope.$$watchers = []; }); scope.$on('resume', function() { scope.$$watchers = watchers; }); var elt = angular.element(element); scope.updateContent = function() { element.children('.table-cell-content').text(scope.preffix + ' ' + scope.content + ' ' + scope.suffix); }; } }; }]);
/* */ 'use strict'; var _extends = require('babel-runtime/helpers/extends')['default']; var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default']; exports.__esModule = true; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _classnames = require('classnames'); var _classnames2 = _interopRequireDefault(_classnames); var _utilsValidComponentChildren = require('./utils/ValidComponentChildren'); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); var _Glyphicon = require('./Glyphicon'); var _Glyphicon2 = _interopRequireDefault(_Glyphicon); var _utilsBootstrapUtils = require('./utils/bootstrapUtils'); var _utilsBootstrapUtils2 = _interopRequireDefault(_utilsBootstrapUtils); var Carousel = _react2['default'].createClass({ displayName: 'Carousel', propTypes: { slide: _react2['default'].PropTypes.bool, indicators: _react2['default'].PropTypes.bool, interval: _react2['default'].PropTypes.number, controls: _react2['default'].PropTypes.bool, pauseOnHover: _react2['default'].PropTypes.bool, wrap: _react2['default'].PropTypes.bool, onSelect: _react2['default'].PropTypes.func, onSlideEnd: _react2['default'].PropTypes.func, activeIndex: _react2['default'].PropTypes.number, defaultActiveIndex: _react2['default'].PropTypes.number, direction: _react2['default'].PropTypes.oneOf(['prev', 'next']), prevIcon: _react2['default'].PropTypes.node, nextIcon: _react2['default'].PropTypes.node }, getDefaultProps: function getDefaultProps() { return { bsClass: 'carousel', slide: true, interval: 5000, pauseOnHover: true, wrap: true, indicators: true, controls: true, prevIcon: _react2['default'].createElement(_Glyphicon2['default'], {glyph: 'chevron-left'}), nextIcon: _react2['default'].createElement(_Glyphicon2['default'], {glyph: 'chevron-right'}) }; }, getInitialState: function getInitialState() { return { activeIndex: this.props.defaultActiveIndex == null ? 0 : this.props.defaultActiveIndex, previousActiveIndex: null, direction: null }; }, getDirection: function getDirection(prevIndex, index) { if (prevIndex === index) { return null; } return prevIndex > index ? 'prev' : 'next'; }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { var activeIndex = this.getActiveIndex(); if (nextProps.activeIndex != null && nextProps.activeIndex !== activeIndex) { clearTimeout(this.timeout); this.setState({ previousActiveIndex: activeIndex, direction: nextProps.direction != null ? nextProps.direction : this.getDirection(activeIndex, nextProps.activeIndex) }); } }, componentDidMount: function componentDidMount() { this.waitForNext(); }, componentWillUnmount: function componentWillUnmount() { clearTimeout(this.timeout); }, next: function next(e) { if (e) { e.preventDefault(); } var index = this.getActiveIndex() + 1; var count = _utilsValidComponentChildren2['default'].numberOf(this.props.children); if (index > count - 1) { if (!this.props.wrap) { return; } index = 0; } this.handleSelect(index, 'next'); }, prev: function prev(e) { if (e) { e.preventDefault(); } var index = this.getActiveIndex() - 1; if (index < 0) { if (!this.props.wrap) { return; } index = _utilsValidComponentChildren2['default'].numberOf(this.props.children) - 1; } this.handleSelect(index, 'prev'); }, pause: function pause() { this.isPaused = true; clearTimeout(this.timeout); }, play: function play() { this.isPaused = false; this.waitForNext(); }, waitForNext: function waitForNext() { if (!this.isPaused && this.props.slide && this.props.interval && this.props.activeIndex == null) { this.timeout = setTimeout(this.next, this.props.interval); } }, handleMouseOver: function handleMouseOver() { if (this.props.pauseOnHover) { this.pause(); } }, handleMouseOut: function handleMouseOut() { if (this.isPaused) { this.play(); } }, render: function render() { var _classes; var classes = (_classes = {}, _classes[_utilsBootstrapUtils2['default'].prefix(this.props)] = true, _classes.slide = this.props.slide, _classes); return _react2['default'].createElement('div', _extends({}, this.props, { className: _classnames2['default'](this.props.className, classes), onMouseOver: this.handleMouseOver, onMouseOut: this.handleMouseOut }), this.props.indicators ? this.renderIndicators() : null, _react2['default'].createElement('div', { ref: 'inner', className: _utilsBootstrapUtils2['default'].prefix(this.props, 'inner') }, _utilsValidComponentChildren2['default'].map(this.props.children, this.renderItem)), this.props.controls ? this.renderControls() : null); }, renderPrev: function renderPrev() { var classes = 'left ' + _utilsBootstrapUtils2['default'].prefix(this.props, 'control'); return _react2['default'].createElement('a', { className: classes, href: '#prev', key: 0, onClick: this.prev }, this.props.prevIcon); }, renderNext: function renderNext() { var classes = 'right ' + _utilsBootstrapUtils2['default'].prefix(this.props, 'control'); return _react2['default'].createElement('a', { className: classes, href: '#next', key: 1, onClick: this.next }, this.props.nextIcon); }, renderControls: function renderControls() { if (!this.props.wrap) { var activeIndex = this.getActiveIndex(); var count = _utilsValidComponentChildren2['default'].numberOf(this.props.children); return [activeIndex !== 0 ? this.renderPrev() : null, activeIndex !== count - 1 ? this.renderNext() : null]; } return [this.renderPrev(), this.renderNext()]; }, renderIndicator: function renderIndicator(child, index) { var className = index === this.getActiveIndex() ? 'active' : null; return _react2['default'].createElement('li', { key: index, className: className, onClick: this.handleSelect.bind(this, index, null) }); }, renderIndicators: function renderIndicators() { var _this = this; var indicators = []; _utilsValidComponentChildren2['default'].forEach(this.props.children, function(child, index) { indicators.push(_this.renderIndicator(child, index), ' '); }, this); return _react2['default'].createElement('ol', {className: _utilsBootstrapUtils2['default'].prefix(this.props, 'indicators')}, indicators); }, getActiveIndex: function getActiveIndex() { return this.props.activeIndex != null ? this.props.activeIndex : this.state.activeIndex; }, handleItemAnimateOutEnd: function handleItemAnimateOutEnd() { var _this2 = this; this.setState({ previousActiveIndex: null, direction: null }, function() { _this2.waitForNext(); if (_this2.props.onSlideEnd) { _this2.props.onSlideEnd(); } }); }, renderItem: function renderItem(child, index) { var activeIndex = this.getActiveIndex(); var isActive = index === activeIndex; var isPreviousActive = this.state.previousActiveIndex != null && this.state.previousActiveIndex === index && this.props.slide; return _react.cloneElement(child, { active: isActive, ref: child.ref, key: child.key ? child.key : index, index: index, animateOut: isPreviousActive, animateIn: isActive && this.state.previousActiveIndex != null && this.props.slide, direction: this.state.direction, onAnimateOutEnd: isPreviousActive ? this.handleItemAnimateOutEnd : null }); }, handleSelect: function handleSelect(index, direction) { clearTimeout(this.timeout); if (this.isMounted()) { var previousActiveIndex = this.getActiveIndex(); direction = direction || this.getDirection(previousActiveIndex, index); if (this.props.onSelect) { this.props.onSelect(index, direction); } if (this.props.activeIndex == null && index !== previousActiveIndex) { if (this.state.previousActiveIndex != null) { return; } this.setState({ activeIndex: index, previousActiveIndex: previousActiveIndex, direction: direction }); } } } }); exports['default'] = Carousel; module.exports = exports['default'];
'use strict'; const inherits = require('util').inherits; const EventEmitter = require('eventemitter2').EventEmitter2 class StepValueCollection { constructor(collection) { this.collection = collection; } valid() { return this.collection.every((item) => { return item.valid(); }); } ambiguousSteps() { return this.collection.filter((item) => { return item.ambiguous(); }); } notFoundSteps() { return this.collection.filter((item) => { return item.notFound(); }); } map(iterator) { return this.collection.map(iterator); } listen(listener) { this.collection.forEach((item) => { item.onAny((event, item, err) => { this.emit(event, item, err); listener(event, item, err); }); }); } } inherits(StepValueCollection, EventEmitter); module.exports = StepValueCollection;
/* eslint-env node, mocha */ /* global expect */ /* eslint no-console: 0 */ 'use strict'; // Uncomment the following lines to use the react test utilities // import TestUtils from 'react-addons-test-utils'; import createComponent from 'helpers/shallowRenderHelper'; import WishthumbnailComponent from 'components/wishshow/WishthumbnailComponent.js'; describe('WishthumbnailComponent', () => { let component; beforeEach(() => { component = createComponent(WishthumbnailComponent); }); it('should have its component name as default className', () => { expect(component.props.className).to.equal('wishthumbnail-component'); }); });
'use strict' const xhr = require('xhr') const controlPanelLinks = document.querySelectorAll('.control-panel a') const messagesEl = document.getElementById('messages') const initFlamegraph = require('./viz/flamegraph') const initSunburst = require('./viz/sunburst') const initTree = require('./viz/tree') const initTreemap = require('./viz/treemap') const flamegraphEl = document.getElementById('flamegraph') const sunburstEl = document.getElementById('sunburst') const treeEl = document.getElementById('tree') const treemapEl = document.getElementById('treemap') function log(msg) { const html = '<span class="message">' + msg + '</span>' messagesEl.innerHTML = html } function logResponse(res) { var html = '<span><em>' + res.status + '</em></span>&nbsp;' if (res.error) { html += '<span class="error">' + res.error + '</span>' } else { html += '<span class="message">' + res.msg + '</span>' } messagesEl.innerHTML = html } function onresponse(err, res) { if (err) { console.error(err) return logResponse({ error: err, status: 500 }) } log('Got response, parsing ...') const data = JSON.parse(res.body) data.status = res.statusCode if (data.type === 'message') logResponse(data) if (data.data) refresh(data.data) } function processRequest(href) { xhr({ uri: href }, onresponse) } function refresh(graph) { sunburstEl.innerHTML = '' flamegraphEl.innerHTML = '' treeEl.innerHTML = '' treemapEl.innerHTML = '' log('Updating visualizations ...') setTimeout(x => { initFlamegraph({ graph, clazz: '.flamegraph' }) initSunburst({ graph, clazz: '.sunburst' }) initTree({ graph, clazz: '.tree' }) initTreemap({ graph, clazz: '.treemap' }) log('Visualizations updated.') }, 200) } function hookLink(a) { console.log('hooking', a) function onclick(e) { e.preventDefault() processRequest(a.getAttribute('href')) return false } a.onclick = onclick } for (var i = 0; i < controlPanelLinks.length; i++) { hookLink(controlPanelLinks[i]) }
function Selection(selection, table, args) { args = args || {}; this.selection = selection || []; this.length = this.selection.length; this.table = table; if (args.type === undefined) { this.type = "SELECTION<STREAM>"; } else { this.type = args.type; } this.operations = []; if ((args.operation !== undefined) && (args.index !== undefined)) { this.operations.push({ operation: args.operation, index: args.index, args: args.args, options: args.options }); } } module.exports = Selection; var util = require(__dirname+"/utils.js"); var Sequence = require(__dirname+"/sequence.js"); var Error = require(__dirname+"/error.js"); var Promise = require("bluebird"); // operation = {type: 'between', index: 'foo'} Selection.prototype.addOperation = function(operation) { this.operations.push(operation); }; // Import methods from Sequence var keys = Object.keys(Sequence.prototype); for(var i=0; i<keys.length; i++) { (function(key) { Selection.prototype[key] = function() { var docs = []; for(var i=0; i<this.selection.length; i++) { docs.push(this.selection[i].doc); } var sequence = new Sequence(docs, this); return sequence[key].apply(sequence, arguments); }; })(keys[i]); } Selection.prototype.get = function(index) { return this.selection[index]; }; Selection.prototype.setType = function(type) { this.type = type; }; Selection.prototype.typeOf = function() { return this.type; }; Selection.prototype.toSequence = function() { var result = new Sequence(); for(var i=0; i<this.selection.length; i++) { result.push(this.selection[i].doc); } return result; }; Selection.prototype.toSelection = function() { var result = new Selection(); for(var i=0; i<this.selection.length; i++) { result.push(this.selection[i]); } return result; }; Selection.prototype.toSelection = function() { var result = new Selection(); for(var i=0; i<this.selection.length; i++) { result.push(this.selection[i]); } return result; }; Selection.prototype.push = function(doc) { this.selection.push(doc); this.length++; }; Selection.prototype.pop = function() { this.length--; return this.selection.pop(); }; Selection.prototype.filter = function(filter, options, query, internalOptions) { var self = this; var selection = new Selection([], self.table, {}); if (options.default === undefined) { options.default = false; } if (util.isFunction(filter)) { var varId = util.getVarId(filter); query.frames.push(1); return Promise.reduce(self.selection, function(result, context) { query.context[varId] = context; return query.evaluate(filter, query, internalOptions).bind({}).then(function(filterResult) { delete query.context[varId]; if (util.isTrue(filterResult)) { result.push(context); } return result; }).catch(function(err) { delete query.context[varId]; if (err.message.match(/^No attribute/)) { if (util.isTrue(options.default)) { result.push(context); } } else { throw err; } return result; }); }, selection).then(function(result) { return result; }); } else { query.frames.push(1); return query.evaluate(filter, query, internalOptions).then(function(filterValue) { if (typeof filterValue === 'function') { for(var i=0; i<self.selection.length; i++) { try { var filterResult = filterValue(util.toDatum(self.selection[i])); } catch(error) { throw new Error.ReqlRuntimeError(error.toString(), query.frames); } util.assertJavaScriptResult(filterResult, query); filterResult = util.revertDatum(filterResult); if (util.isTrue(filterResult)) { selection.push(self.selection[i]); } } } else if (util.isPlainObject(filterValue)) { for(var i=0; i<self.selection.length; i++) { if (util.filter(util.toDatum(self.selection[i]), util.toDatum(filterValue))) { selection.push(self.selection[i]); } } } else { for(var i=0; i<self.selection.length; i++) { if ((filterValue !== null) && (filterValue !== false)) { selection.push(self.selection[i]); } } } query.frames.pop(); return selection; }); } }; Selection.prototype.update = function(rawUpdate, options, query, internalOptions) { return Promise.map(this.selection, function(doc) { return doc.update(rawUpdate, options, query, internalOptions); }, {concurrency: 1}).then(function(mergedResults) { var result = util.writeResult(); for(var i=0; i<mergedResults.length; i++) { util.mergeWriteResult(result, mergedResults[i]); } return result; }); }; Selection.prototype.replace = function(rawReplace, options, query, internalOptions) { return Promise.map(this.selection, function(doc) { return doc.replace(rawReplace, options, query, internalOptions); }, {concurrency: 1}).then(function(mergedResults) { var result = util.writeResult(); for(var i=0; i<mergedResults.length; i++) { util.mergeWriteResult(result, mergedResults[i]); } return result; }); }; Selection.prototype.delete = function(options, query) { return Promise.map(this.selection, function(doc) { return doc.delete(options, query); }, {concurrency: 1}).then(function(mergedResults) { var result = util.writeResult(); for(var i=0; i<mergedResults.length; i++) { util.mergeWriteResult(result, mergedResults[i]); } return result; }); }; Selection.prototype.skip = function(skip) { var result = new Selection([], this.table, {}); for(var i=skip; i<this.selection.length; i++) { result.push(this.selection[i]); } return result; }; Selection.prototype.limit = function(limit) { var result; if ((this.type === 'TABLE_SLICE') && (this.operations.length > 0) && (this.operations[this.operations.length-1].operation === 'orderBy')) { result = new Selection([], this.table, { type: 'TABLE_SLICE' }); for(var i=0; i<this.operations.length; i++) { result.operations.push(this.operations[i]); } if (util.isPlainObject(result.operations[result.operations.length-1].args)) { result.operations[result.operations.length-1].args = {}; } result.operations[result.operations.length-1].args.limit = limit; } else { result = new Selection([], this.table, {}); } for(var i=0; i<Math.min(limit,this.length); i++) { result.push(this.selection[i]); } return result; }; Selection.prototype.orderBy = function(fields, options, query, internalOptions) { var self = this; var hasIndex = false; var index; var order; if (options.index !== undefined) { hasIndex = true; index = options.index; order = 'ASC'; if (util.isAsc(index)) { order = 'ASC'; index = options.index.value; } else if (util.isDesc(index)) { order = 'DESC'; index = options.index.value; } if (this.type !== 'TABLE_SLICE') { return Promise.reject(new Error.ReqlRuntimeError("Cannot use an index on a selection", query.frames)); } else { // We have a table slice, so this.operations.length > 0 if (this.operations[this.operations.length-1].index !== index) { query.frames.push(0); query.frames.push(0); return Promise.reject(new Error.ReqlRuntimeError('Cannot order by index `'+index+'` after calling '+this.operations[this.operations.length-1].operation.toUpperCase()+' on index `'+this.operations[this.operations.length-1].index+'`', query.frames)); } } query.frames.push('index'); util.assertType(index, 'STRING', query); query.frames.pop(); if (this.table.indexes[index] === undefined) { return Promise.reject(new Error.ReqlRuntimeError('Index `'+index+'` was not found on table `'+this.db+'.'+this.name+'`', query.frames)); } if (order === 'DESC') { fields.unshift([74, [this.table.indexes[index].fn], {}]); } else { fields.unshift(this.table.indexes[index].fn); } } var selection = new Selection([], this.table, { type: this.type }); //TODO Move in the constructor selection.operations = this.operations.slice(0); var mainPromise; var restrictedSelection = new Selection([], this.table, {}); if (hasIndex === true) { var varId = util.getVarId(self.table.indexes[index].fn); mainPromise = Promise.map(self.selection, function(doc) { query.context[varId] = doc; return query.evaluate(self.table.indexes[index].fn, query, internalOptions).then(function(indexValue) { delete query.context[varId]; if ((indexValue !== null) || (util.isPlainObject(indexValue) && (indexValue.$reql_type$ === undefined))) { restrictedSelection.push(doc); } }).catch(function(err) { if (err.message.match(/^No attribute/)) { // We also drop documents where a non existent error was thrown } else { throw err; } }); }, {concurrency: 1}).then(function() { return restrictedSelection; }); } else { mainPromise = Promise.resolve(this); } var sequenceToSort = new Sequence(); return mainPromise.then(function(restrictedSelection) { return Promise.map(restrictedSelection.selection, function(ref) { var element = { original: ref, fields: new Sequence() }; return util.computeFields(element, 0, fields, query, internalOptions); }, {concurrency: 1}).then(function(resolved) { for(var i=0; i<resolved.length; i++) { sequenceToSort.push(resolved[i]); } sequenceToSort._orderBy(); for(var i=0; i<sequenceToSort.length; i++) { selection.push(sequenceToSort.get(i).original); } return selection; }); }); }; Selection.prototype._orderBy = function() { this.selection.sort(function(left, right) { for(var i=0; i<left.fields.length; i++) { if (util.gt(left.fields.get(i).value, right.fields.get(i).value)) { if (left.fields.get(i).order === "ASC") { return 1; } else { return -1; } } if (util.lt(left.fields.get(i).value, right.fields.get(i).value)) { if (left.fields.get(i).order === "ASC") { return -1; } else { return 1; } } } return 0; }); return this; }; Selection.prototype.distinct = function(options, query, internalOptions) { var self = this; if (options.index !== undefined) { if (this.type !== 'TABLE_SLICE') { throw new Error.ReqlRuntimeError("Cannot use an index on a selection", query.frames); } if (this.operations[this.operations.length-1].index !== options.index) { throw new Error.ReqlRuntimeError('Cannot use between index `'+this.operations[this.operations.length-1].index+'` after calling '+this.operations[this.operations.length-1].operation.toUpperCase()+' on index `'+this.index+'`', query.frames); } var fn = this.table.indexes[options.index].fn; var varId = util.getVarId(fn); var mapped = new Sequence(); return Promise.map(this.selection, function(doc) { query.context[varId] = doc; return query.evaluate(fn, query, internalOptions).then(function(next) { delete query.context[varId]; if (self.table.indexes[options.index].multi === true) { for(var j=0; j<next.sequence.length; j++) { mapped.push(next.sequence[j]); } } else { mapped.push(next); } return mapped; }).catch(function(err) { if (err.message.match(/^No attribute `/) === null) { throw err; } return mapped; // else we just skip the non existence error }); }, {concurrency: 1}).then(function() { // We can't use results here since we could have a multi index return mapped.distinct({}, query, internalOptions); }); } else { return this.toSequence().distinct({}, query, internalOptions); } }; Selection.prototype.between = function(left, right, options, query, internalOptions) { var self = this; if (this.type !== 'TABLE_SLICE') { throw new Error.ReqlRuntimeError("Cannot use an index on a selection", query.frames); } if ((util.isPlainObject(options) === false) || (typeof options.index !== 'string')) { options.index = this.operations[this.operations.length-1].index; } for(var i=0; i<this.operations.length; i++) { if (this.operations[i].operation === 'between') { // This is weird, did we miss a frame before? query.frames.push(0); query.frames.push(0); throw new Error.ReqlRuntimeError('Cannot perform multiple BETWEENs on the same table', query.frames); } } // We now have a TABLE_SLICE and therefore this.operations.length > 0 if (this.operations[this.operations.length-1].index !== options.index) { throw new Error.ReqlRuntimeError('Cannot use between index `'+this.operations[this.operations.length-1].index+'` after calling '+this.operations[this.operations.length-1].operation.toUpperCase()+' on index `'+this.index+'`', query.frames); } var selection = new Selection([], this.table, { type: this.type }); selection.operations = this.operations.slice(0); var varId = util.getVarId(self.table.indexes[options.index].fn); return Promise.reduce(self.selection, function(result, doc) { query.context[varId] = doc; return query.evaluate(self.table.indexes[options.index].fn, internalOptions).then(function(valueIndex) { delete query.context[varId]; if (self.table.indexes[options.index].multi === true) { for(var k=0; k<valueIndex.length; k++) { util.between(result, doc, valueIndex.get(k), left, right, options); } } else { util.between(result, doc, valueIndex, left, right, options); } return result; }).catch(function(err) { //TODO Test this code path if (err.message.match(/^No attribute `/) === null) { throw err; } }); }, selection); }; Selection.prototype.toDatum = function() { var result = []; for(var i=0; i<this.selection.length; i++) { result.push(util.toDatum(this.selection[i])); } return result; };
var searchData= [ ['borradoelemento',['BorradoElemento',['../classZero_1_1Observador.html#a3ba845503dd02bde5117f7c6b515439ba7589b232ac05b1a6ecb93dff3e80b815',1,'Zero::Observador']]] ];
version https://git-lfs.github.com/spec/v1 oid sha256:b230c966acc49261f99af797170ba8d46f3c012441b7833b6ee448ea0e355a47 size 2630
const escapeRegex = require('escape-string-regexp') const highlightTranscript = (transcript, selector, highlight) => { highlight = highlight && escapeRegex(highlight) const nodes = transcript.find(selector) $(nodes).each(function(){ const text = $(this).attr('data-node') const html = $(this).html() if(!highlight){ $(this).html(text) return } const replaced = text.replace( new RegExp(`(${highlight})`, 'ig'), '<span class="transcript-highlight">$1</span>' ) // prevent unnecessary DOM mutations if(replaced === text){ $(this).html(text) return } if(replaced === html){ return } $(this).html(replaced) }) } module.exports = highlightTranscript
// Vehicle (reducer) ==================== On se préoccupe d’une seule action… import {ADD_VEHICLE, REMOVE_VEHICLE, UPDATE_VEHICLE} from '../action-creators' // Par défaut, `history` vaut `[]` (pas d’historique) export default function vehicles (state = [], action) { switch (action.type) { case ADD_VEHICLE: { const {immat, brand, model} = action.payload return [ ...state, { immat, brand, model } ] } case REMOVE_VEHICLE: return state.filter(({ immat }) => immat !== action.payload.immat) case UPDATE_VEHICLE: const { immat, brand, model } = action.payload const newVehicle = { immat, brand, model } // Si l’objectif existait bien dans le tableau, on crée le nouveau // tableau en partant de l’existant pour ne remplacer que l’entrée idoine. if (state.find((vehicle) => vehicle.immat === immat)) { return state.map((vehicle) => vehicle.immat === immat ? newVehicle : vehicle) } // Si ça se trouve, on ne l’avait pas en fait, cet objectif… Ça ne // devrait pas arriver, mais autant se blinder. On l’ajoute à la fin, // dans un tel as, comme un ajout mais en préservant l'ID. return [...state, newVehicle] default: // Rappel : un *reducer* doit **toujours** renvoyer l’état sans modification si // l’action n’est pas applicable. return state } }
var dir_b05834cb21707fe439124e4910782a60 = [ [ "asm-primitives.cpp", "asm-primitives_8cpp.html", "asm-primitives_8cpp" ], [ "blockcopy8.h", "blockcopy8_8h.html", "blockcopy8_8h" ], [ "dct8.h", "dct8_8h.html", "dct8_8h" ], [ "intrapred.h", "intrapred_8h.html", "intrapred_8h" ], [ "ipfilter8.h", "ipfilter8_8h.html", "ipfilter8_8h" ], [ "loopfilter.h", "loopfilter_8h.html", "loopfilter_8h" ], [ "mc.h", "mc_8h.html", "mc_8h" ], [ "pixel-util.h", "pixel-util_8h.html", "pixel-util_8h" ], [ "pixel.h", "pixel_8h.html", "pixel_8h" ] ];
import React from 'react' import { Table, TableHeader, TableBody, TableRow, TableRowColumn, TableHeaderColumn } from 'material-ui' export function DocsTable({ columns, children }) { return ( <Table style={{ tableLayout: 'auto' }} selectable={false} fixedHeader={false}> { columns && ( <TableHeader displaySelectAll={false} adjustForCheckbox={false}> <TableRow> { columns.map((col) => <TableHeaderColumn key={col}>{col}</TableHeaderColumn>) } </TableRow> </TableHeader> ) } <TableBody displayRowCheckbox={false}> {children} </TableBody> </Table> ) } export function DocsSection({ span, children }) { return <TableHeaderColumn colSpan={span}>{children}</TableHeaderColumn> } export const DocsRow = TableRow export function DocsCell({ multiline, children }) { return <TableRowColumn style={multiline && { whiteSpace: 'wrap' }}>{children}</TableRowColumn> }
import expect from 'expect'; import successRateReducer$, { successRateActions } from '../../containers/successRate.redux$'; describe('successRate.redux$', () => { it('handles succeed, fail and reset actions', () => { successRateReducer$.take(5).toArray().subscribe((fns) => { expect(fns.reduce((acc, fn) => fn(acc), {})).toEqual({ successCount: 1, failCount: 1 }); }); successRateActions.succeed$.next(); successRateActions.reset$.next(); successRateActions.succeed$.next(); successRateActions.fail$.next(); }); });
import express from "express"; import validate from "validate.js"; import moment from "moment"; import APIResponse from "../../lib/apiresponse.js"; import * as Utils from "../../lib/apiutils.js"; var router = express.Router(); // Adds a new assignment to the database // Required fields: subjectId, typeId, dueDate, title, description (body) router.post("/", Utils.isAuthenticated, (req, res) => { let response = new APIResponse(); validate.async(req.body, { subjectId: { presence: true }, typeId: { presence: true }, dueDate: { presence: true, numericality: { onlyInteger: true } }, title: { presence: true, length: { maximum: 100 } }, description: { presence: true } }, { format: "flat" }).then(success, error); function error(errors) { response.setFailureMessages(errors); response.setSuccess(false); return response.setStatus(422).send(res); // Unprocessable Entity } function success(values) { values = Utils.trimObject(values); values.dueDate = moment(parseInt(values.dueDate)).format("YYYY-MM-DD"); // Check if the date is valid if (values.dueDate === "Invalid date") { response.addFailureMessage("Invalid date"); response.setSuccess(false); return response.setStatus(422).send(res); // Unprocessable Entity } // Check if the subject exists SchoolBuddy.database.get("SELECT * FROM subjects WHERE id=? AND userId=? LIMIT 1;", [values.subjectId, req.token.id], (err, row) => { // TODO Do something with this error if (err) throw err; if (!row) { response.addFailureMessage("Subject id doesn't exist in the database"); response.setSuccess(false); return response.setStatus(422).send(res); // Unprocessable Entity } checkType(values); }); } function checkType(values) { // Check if the assignment type exists SchoolBuddy.database.get("SELECT * FROM assignment_types WHERE id=? AND userId=? LIMIT 1;", [values.typeId, req.token.id], (err, row) => { // TODO Do something with this error if (err) throw err; if (!row) { response.addFailureMessage("Type id doesn't exist in the database"); response.setSuccess(false); return response.setStatus(422).send(res); // Unprocessable Entity } saveToDB(values); }); } function saveToDB(values) { // Save the assignment to the database SchoolBuddy.database.run("INSERT INTO assignments (userId, subjectId, typeId, dueDate, title, description, done, addedAt) VALUES (?, ?, ?, ?, ?, ?, 0, CURRENT_TIMESTAMP);", [req.token.id, values.subjectId, values.typeId, values.dueDate, values.title, values.description], function() { // Get the assignment info SchoolBuddy.database.get("SELECT * FROM assignments_view WHERE id=? AND userId=? LIMIT 1;", [this.lastID, req.token.id], (err, row) => { // TODO Do something with this error if (err) throw err; // Delete the user id from the row delete row.userId; response.addSuccessMessage("Assignment added to the database"); response.setData(row); response.setSuccess(true); return response.setStatus(200).send(res); // OK }); }); } }); // Gets all of the (user) assignments from the database router.get("/", Utils.isAuthenticated, (req, res) => { let response = new APIResponse(); let assignments = []; // Get the assignments info SchoolBuddy.database.each("SELECT * FROM assignments_view WHERE userId=?;", [req.token.id], (err, row) => { // TODO Do something with this error if (err) throw err; // Delete the user id from the row delete row.userId; assignments.push(row); }, done); function done() { if (assignments.length > 0) { response.setData(assignments); response.setSuccess(true); return response.setStatus(200).send(res); // OK } else { response.addFailureMessage("There are no assignments in the database"); response.setSuccess(false); return response.setStatus(404).send(res); // Not Found } } }); // Gets a specific assignment from the database // Required fields: id (url) router.get("/:id", Utils.isAuthenticated, (req, res) => { let response = new APIResponse(); let id = req.params.id; // Get the assignment info SchoolBuddy.database.get("SELECT * FROM assignments_view WHERE id=? AND userId=? LIMIT 1;", [id, req.token.id], (err, row) => { // TODO Do something with this error if (err) throw err; if (row) { // Delete the user id from the row delete row.userId; response.setData(row); response.setSuccess(true); return response.setStatus(200).send(res); // OK } else { response.addFailureMessage("The assignment doesn't exist"); response.setSuccess(false); return response.setStatus(404).send(res); // Not Found } }); }); // Edits a specific assignment from the database // Required fields: id (url), subjectId, typeId, dueDate, title, description, done (body) router.put("/:id", Utils.isAuthenticated, (req, res) => { let response = new APIResponse(); let id = req.params.id; validate.async(req.body, { subjectId: { presence: true }, typeId: { presence: true }, dueDate: { presence: true, numericality: { onlyInteger: true } }, title: { presence: true, length: { maximum: 100 } }, description: { presence: true }, done: { presence: true, inclusion: { within: {0: false, 1: true} } } }, { format: "flat" }).then(success, error); function error(errors) { response.setFailureMessages(errors); response.setSuccess(false); return response.setStatus(422).send(res); // Unprocessable Entity } function success(values) { values = Utils.trimObject(values); values.dueDate = moment(parseInt(values.dueDate)).format("YYYY-MM-DD"); // Check if the date is valid if (values.dueDate === "Invalid date") { response.addFailureMessage("Invalid date"); response.setSuccess(false); return response.setStatus(422).send(res); // Unprocessable Entity } // Check if the assignment exists SchoolBuddy.database.get("SELECT * FROM assignments WHERE id=? AND userId=? LIMIT 1;", [id, req.token.id], (err, row) => { // TODO Do something with this error if (err) throw err; if (!row) { response.addFailureMessage("The assignment doesn't exist"); response.setSuccess(false); return response.setStatus(422).send(res); // Unprocessable Entity } checkSubject(values); }); } function checkSubject(values) { // Check if the subject exists SchoolBuddy.database.get("SELECT * FROM subjects WHERE id=? AND userId=? LIMIT 1;", [values.subjectId, req.token.id], (err, row) => { // TODO Do something with this error if (err) throw err; if (!row) { response.addFailureMessage("Subject id doesn't exist in the database"); response.setSuccess(false); return response.setStatus(422).send(res); // Unprocessable Entity } checkType(values); }); } function checkType(values) { // Check if the assignment type exists SchoolBuddy.database.get("SELECT * FROM assignment_types WHERE id=? AND userId=? LIMIT 1;", [values.typeId, req.token.id], (err, row) => { // TODO Do something with this error if (err) throw err; if (!row) { response.addFailureMessage("Type id doesn't exist in the database"); response.setSuccess(false); return response.setStatus(422).send(res); // Unprocessable Entity } saveToDB(values); }); } function saveToDB(values) { // Save the assignment to the database SchoolBuddy.database.run("UPDATE assignments SET subjectId=?, typeId=?, dueDate=?, title=?, description=?, done=?, modifiedAt=CURRENT_TIMESTAMP WHERE id=? AND userId=?;", [values.subjectId, values.typeId, values.dueDate, values.title, values.description, values.done, id, req.token.id]); // Get the assignment info SchoolBuddy.database.get("SELECT * FROM assignments_view WHERE id=? AND userId=? LIMIT 1;", [id, req.token.id], (err, row) => { // TODO Do something with this error if (err) throw err; // Delete the user id from the row delete row.userId; response.addSuccessMessage("Assignment edited"); response.setData(row); response.setSuccess(true); return response.setStatus(200).send(res); // OK }); } }); // Deletes a specific assignment from the database // Required fields: id (url) router.delete("/:id", Utils.isAuthenticated, (req, res) => { let response = new APIResponse(); let id = req.params.id; // Get the assignment info SchoolBuddy.database.get("SELECT * FROM assignments WHERE id=? AND userId=? LIMIT 1;", [id, req.token.id], (err, row) => { // TODO Do something with this error if (err) throw err; if (row) { // Delete the assignment SchoolBuddy.database.run("DELETE FROM assignments WHERE id=? AND userId=?;", [id, req.token.id]); response.addSuccessMessage("Assignment removed"); response.setSuccess(true); return response.setStatus(200).send(res); // OK } else { response.addFailureMessage("The assignment doesn't exist"); response.setSuccess(false); return response.setStatus(404).send(res); // Not Found } }); }); export default router;
const fs = require('fs'); var read = fs.readFileSync('input.json', 'utf8'); var index = require('./input.json'); var D; var x1; var x2; var print={}; if (index.a==0 && index.b==0) { print="#" console.log(print); } if (index.a==0 && index.b!=0) { x1=(-c)/b print = {"x1":x1}; console.log(print); } D=(index.b*index.b)+(-4*index.a*index.c); if (D<0 && index.a!=0) { print ="NOT MENTIONED" console.log(print); } if (D>0 && index.a!=0) { discr=Math.sqrt(D) x1=(-index.b+discr)/(2*index.a) x2=(-index.b+(-discr))/(2*index.a) print = {"x2":x2, "x1":x1, "D":D}; print=JSON.stringify(print,"\n",1); console.log(print); } if (D==0 && index.a!=0) { x1=(-b)/(2*a) print = {"x1":x1}; console.log(print); }
var map = require('../../array/map'); describe('array/map', function () { it('returns an empty array when passed an empty array', function () { function yes () { return true; } expect(map([], yes)).to.deep.equal([]); }); it('returns a mapped array', function () { function square (n) { return n * n; } expect(map([1, 2, 3], square)).to.deep.equal([1, 4, 9]); }); it('calls the function with the proper arguments', function () { var fn = this.sandbox.spy(function () { return true; }); var arr = ['a', 'b', 'c']; map(arr, fn); expect(fn.callCount).to.equal(3); expect(fn.getCall(0).args).to.deep.equal(['a', 0, arr]); expect(fn.getCall(1).args).to.deep.equal(['b', 1, arr]); expect(fn.getCall(2).args).to.deep.equal(['c', 2, arr]); }); });
$(document).ready(function() { var publishCommand = function(notificationName) { return function(tokens) { $.publish(notificationName); }; } window.TerminalCommands = { next : publishCommand('presentation:slide:next'), previous : publishCommand('presentation:slide:previous'), goto : function(tokens) { var gotoSlideNumber = undefined; if ( parseInt(tokens[0]) > 0 && parseInt(tokens[0]) < presentation.slideTotal()) { gotoSlideNumber = parseInt(tokens[0]) - 1; } else if (tokens[0] == 'start') { gotoSlideNumber = 0; } else if (tokens[0] == 'end') { gotoSlideNumber = presentation.slideTotal() - 1; } else { gotoSlideNumber = presentation.slides.findClosestToQuery(presentation.currentSlide.sequence,tokens[0]) - 1; } $.publish('presentation:slide:location:change',gotoSlideNumber); } }; });
module.exports = { options: { title: "a typical app", description: "Generates something very important.", forms: [ "$ cat input.json | my-app [<options>]", "$ my-app <files>" ], footer: "Project home: [underline]{https://github.com/me/my-app}" }, data: [ { name: "help", alias: "h", type: Boolean, description: "Display this usage guide." }, { name: "src", type: String, multiple: true, defaultOption: true, description: "The input files to process", typeLabel: "<files>" }, { name: "timeout", alias: "t", type: Number, description: "Timeout value in ms", typeLabel: "<ms>" } ] };
(function (window, $) { 'use strict'; // Cache document for fast access. var document = window.document; /* function mainSlider() { $('.bxslider').bxSlider({ pagerCustom: '#bx-pager', mode: 'fade', nextText: '', prevText: '' }); } mainSlider(); */ var $links = $(".bx-wrapper .bx-controls-direction a, #bx-pager a"); $links.click(function(){ $(".slider-caption").removeClass('animated fadeInLeft'); $(".slider-caption").addClass('animated fadeInLeft'); }); $(".bx-controls").addClass('container'); $(".bx-next").addClass('fa fa-angle-right'); $(".bx-prev").addClass('fa fa-angle-left'); $('a.toggle-menu').click(function(){ $('.responsive .main-menu').toggle(); return false; }); $('.responsive .main-menu a').click(function(){ $('.responsive .main-menu').hide(); }); /* $('.main-menu').singlePageNav(); */ })(window, jQuery); var map = ''; function initialize() { var myLatLng = {lat: 33.729998, lng: 73.037313}; var mapOptions = { zoom: 14, center: myLatLng }; map = new google.maps.Map(document.getElementById('map'), mapOptions); var marker = new google.maps.Marker({ position: myLatLng, map: map, title: 'Shah Faisal Masjid Islamabad' }); } // load google map /* var script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&' + 'callback=initialize'; document.body.appendChild(script); */
import ApiKey from 'appkit/models/api_key'; var AuthManager = Ember.Object.extend({ // Load the current user if the cookies exist and is valid init: function() { this._super(); var accessToken = $.cookie('access_token'); var authUserId = $.cookie('auth_user'); if (!Ember.isEmpty(accessToken) && !Ember.isEmpty(authUserId)) { this.authenticate(accessToken, authUserId); } }, // Determine if the user is currently authenticated. isAuthenticated: function() { return !Ember.isEmpty(this.get('apiKey.accessToken')) && !Ember.isEmpty(this.get('apiKey.user')); }, // Authenticate the user. Once they are authenticated, set the access token to be submitted with all // future AJAX requests to the server. authenticate: function(accessToken, user) { $.ajaxSetup({ headers: { 'Authorization': 'Bearer ' + accessToken } }); this.set('apiKey', ApiKey.create({ accessToken: accessToken, user: user })); }, // Log out the user reset: function() { Ember.run.sync(); Ember.run.next(this, function(){ this.set('apiKey', null); $.ajaxSetup({ headers: { 'Authorization': 'Bearer none' } }); }); }, // Ensure that when the apiKey changes, we store the data in cookies in order for us to load // the user when the browser is refreshed. apiKeyObserver: function() { if (Ember.isEmpty(this.get('apiKey'))) { $.removeCookie('access_token'); $.removeCookie('auth_user'); } else { $.cookie('access_token', this.get('apiKey.accessToken')); $.cookie('auth_user', this.get('apiKey.user.id')); } }.observes('apiKey', 'apiKey.user.id') }); // Reset the authentication if any ember data request returns a 401 unauthorized error DS.rejectionHandler = function(reason) { if (reason.status === 401) { window.App.AuthManager.reset(); } throw reason; }; export default AuthManager;
/** * ShopReactNative * * @author Tony Wong * @date 2016-09-23 * @email 908601756@qq.com * @copyright Copyright © 2016 EleTeam * @license The MIT License (MIT) */ import React, {Component} from 'react'; import {connect} from 'react-redux'; import PreorderPage from '../pages/PreorderPage'; class PreorderContainer extends Component { render() { return ( <PreorderPage {...this.props} /> ) } } export default connect((state) => { return { preorderReducer, orderReducer, userReducer, commonReducer} = state; })(PreorderContainer);
const {expect} = require('chai'); const valueExpand = require('.'); describe('Set-1: Value Expand', () => { let inputObject; beforeEach(() => { inputObject = { 1: { values: { 36: 0.7 }, uuids: { finance_rate_id: { 36: '43378e65-a835-47e0-8577-e24d80d3e2d4' }, trim_id: 'fa6205dd-43e2-4935-ba6f-fdeb7e2f207d' } }, 2: { values: { 24: 0.4, 36: 0.8 }, uuids: { finance_rate_id: { 24: '2cdd24a2-a5e7-46b1-80d0-776f3dbbbc79', 36: '1c5e4ab5-8cf4-4eef-8162-e1642056a57b' }, trim_id: '09f16ef2-1aa5-44bf-8c7a-64cd0ef0b65b' } }, 10: { values: { 36: 0.9, 48: 1.2, 64: 1.6 }, uuids: { finance_rate_id: { 36: '29268e5d-70d0-4403-acf0-89b2d3d7d942', 48: 'fe4b9501-60da-4a8d-81a2-019709b634d8', 64: 'f468f00e-9962-422a-9096-6e872fd54f5c' }, trim_id: '09f16ef2-1aa5-44bf-8c7a-64cd0ef0b65b' } } }; }); it('Base Test : Function returns expected keys', () => { let result = valueExpand(inputObject); expect(Object.keys(result)).to.eql([1, 2, 10]); }); // Write your correctness tests here });
'use strict'; angular.module('videostoreApp').controller('MovieDialogController', ['$scope', '$stateParams', '$modalInstance', 'entity', 'Movie', 'Director', function($scope, $stateParams, $modalInstance, entity, Movie, Director) { $scope.movie = entity; $scope.directors = Director.query(); $scope.load = function(id) { Movie.get({id : id}, function(result) { $scope.movie = result; }); }; var onSaveFinished = function (result) { $scope.$emit('videostoreApp:movieUpdate', result); $modalInstance.close(result); }; $scope.save = function () { if ($scope.movie.id != null) { Movie.update($scope.movie, onSaveFinished); } else { Movie.save($scope.movie, onSaveFinished); } }; $scope.clear = function() { $modalInstance.dismiss('cancel'); }; }]);
function WrappedShape(type, x, y, board) { Shape.call(this, type, x, y, board); this.state = WrappedShape.NORMAL; this.special = WrappedShape.SPECIAL; this.bombSize = 1; } WrappedShape.NORMAL = 0; WrappedShape.EXPLODED = 1; WrappedShape.WAIT_EXPLODE_AGAIN = 2; WrappedShape.CAN_CLEAR = 3; WrappedShape.SPECIAL = 3; WrappedShape.SPECIAL_WAIT_EXPLODE = 4; WrappedShape.prototype = new Shape(); WrappedShape.prototype.constructor = WrappedShape; WrappedShape.prototype.update = function () { Shape.prototype.update.call(this); if (this.state === WrappedShape.EXPLODED) { this.state = WrappedShape.WAIT_EXPLODE_AGAIN; this.special = WrappedShape.SPECIAL_WAIT_EXPLODE; this.tick = 60 * 5 - this.board.passedTime%60; } this.tick--; if (this.tick <= 0 && this.state === WrappedShape.WAIT_EXPLODE_AGAIN) { this.state = WrappedShape.CAN_CLEAR; this.board.clearShape(this.x, this.y, 0, {special: true}); // sometimes the shape might fail to explode if (!this.cleared) { this.state = WrappedShape.WAIT_EXPLODE_AGAIN; } } }; WrappedShape.prototype.canMatch = function () { if (this.state === WrappedShape.NORMAL) { // call base class return Shape.prototype.canMatch.call(this); } return false; }; WrappedShape.prototype.canBeCleared = function () { if (Shape.prototype.canBeCleared.call(this)) { return this.state === WrappedShape.CAN_CLEAR; } return false; }; WrappedShape.prototype.canCrush = function () { if (Shape.prototype.canCrush.call(this)) { return this.state === WrappedShape.NORMAL || this.state === WrappedShape.CAN_CLEAR; } return false; }; WrappedShape.prototype.crush = function (board) { if (this.state === WrappedShape.NORMAL) { this.state = WrappedShape.EXPLODED; var ex = new WrappedEffect(board, this.x, this.y, this.type, this.bombSize); board.addItemToClear(ex); } return Shape.prototype.crush.call(this, board); }; WrappedShape.prototype.deleteUpdate = function () { if (this.tickClear === this.tickClearTotal) { var ex = new WrappedEffect(this.board, this.x, this.y, this.type, this.bombSize); this.board.addItemToClear(ex); } return Shape.prototype.deleteUpdate.call(this); }; function WrappedEffect(board, x, y, color, bombSize) { this.board = board; this.x = x; this.y = y; this.totalTicks = 10; this.tick = this.totalTicks; this.type = color; this.size = bombSize || 1; this.explode(); } WrappedEffect.prototype.explode = function () { var i, j; var size = this.size; var score = size > 1 ? 0 : 540; var x = this.x, y = this.y; for (i = Math.max(x - size, 0); i <= x + size && i < this.board.width; i++) { for (j = Math.min(y + size, this.board.height - 1); j >= y - size && j >= 0 ; j--) { if (i !== this.x || j !== this.y) { if (size > 1) score += 60; var s = this.board.clearShape(i, j); score += s.addition + s.jelly + s.blocker; } } } this.board.gainScores.push({ x: this.x, y: this.y, type: this.type, score: score }); this.board.score += score; this.board.goodCount += 1; }; WrappedEffect.prototype.update = function () { 'use strict'; this.tick--; return this.tick > 0; }; // returns array of [x, y, width, height, frameName]'s WrappedEffect.prototype.getSpritePositions = function () { var t = (1 - this.tick / this.totalTicks) * this.size; var sw = 0.6, sh = 0.6, frm = Shape.typeNames[this.type-1]; return [ [this.x-t, this.y-t, sw, sh, frm], [this.x-t, this.y+t, sw, sh, frm], [this.x+t, this.y-t, sw, sh, frm], [this.x+t, this.y+t, sw, sh, frm], [this.x-t, this.y, sw, sh, frm], [this.x+t, this.y, sw, sh, frm], [this.x, this.y-t, sw, sh, frm], [this.x, this.y+t, sw, sh, frm] ]; };
function setup() { // You are also allowed to assign variables a value, while declaring them // Valid var myVar = 5; // OR you can declare and assign on seperate lines; var var2; var2 = 5; } function draw() { }
/** * Created by zhangdihong on 2014/12/15. */ var dbUrl=require('../config').db; var mongoose=require('mongoose'); exports.connect= function (callback) { mongoose.connect(dbUrl); } exports.mongoObj= function () { return mongoose; }
/*globals describe, it */ var should = require('should'), JGLModel = require('../../').Model, Parser = JGLModel.Pattern.Parser; describe('OPE.Pattern.Parser', function () { describe('.isInteger()', function () { it('should return true for a integer', function () { Parser.isInteger(2).should.be.true; }); }); describe('.isIntegers()', function () { it('should return true for an array of integers', function () { Parser.isIntegers([0, 1, 2]).should.be.true; }); }); describe('.isRange()', function () { it('should return true for ranges', function () { Parser.isRange({ to: 9 }).should.be.true; Parser.isRange({ from: 0, to: 9 }).should.be.true; }); }); describe('.isIntegersOrRange()', function () { it('should return true for a range or an array of integers', function () { Parser.isIntegersOrRange([0, 1, 2]).should.be.true; Parser.isIntegersOrRange({ to: 9 }).should.be.true; Parser.isIntegersOrRange({ from: 0, to: 9 }).should.be.true; }); }); describe('#match()', function () { it('should match a path and return the matches as nested arrays', function () { var p = new Parser('foo', 'bar', Parser.INTEGERS); p.match(['foo', 'bar', [1, 2, 3]]). should. eql([['foo'], ['bar'], [1, 2, 3]]); p.match(['foo', 'bar', { from: 1, to: 3}]). should. eql([['foo'], ['bar'], [1, 2, 3]]); }); it( 'should return false if the query length and the parser segment lengths do not match', function () { var p = new Parser('foo', 'bar'); p.match(['foo']).should.be.false; } ); }); });
var t; function timedCount() { var temptextmin = document.getElementById('txt'); var now = new Date();//定义一个现在的时间 var SetStart = new Date();//设置开始考试时间 // SetStart.setHours(21, 30, 00);//时,分,秒 var SetEnd = new Date();//设置结束考试时间 SetEnd.setHours(22, 30, 00);//时,分,秒 var leftTime=SetEnd.getTime()-now.getTime(); var leftsecond = parseInt(leftTime/1000); var hour=Math.floor(leftsecond/3600); var minute=Math.floor((leftsecond-hour*3600)/60); var second=Math.floor(leftsecond-hour*3600-minute*60); if((hour==0)&(minute ==0)&(second == 0)) {//判断时间和考试开始时间是否一致 alert("考试结束,接下来将自动帮你提交试卷"); document.getElementById("myform").submit(); // btn.submit(); //提交 } temptextmin.value = hour + "时" + minute + "分" + second + "秒"; t=setTimeout("timedCount()",1000); } function changeColor(num){ var button = document.getElementById(num); button.style.background="#429AB7"; button.style.color="white"; } function clickMove(index){ document.getElementsByTagName("p")[index].scrollIntoView(true); } window.onload=function() { timedCount(); var Botton = document.getElementById('btn'); Botton.onclick = function () { if (confirm("确认提交?")) { window.open("loading.html", "_self"); document.getElementById("myform").submit(); } else { } } } //
import lt from './lt' describe('lt', () => { it('compares the values', () => { expect(lt(1)(2)).toBe(false) expect(lt(2)(1)).toBe(true) expect(lt(2)(2)).toBe(false) }) })
exports.action = { name: 'printerCreate', description: 'Creates a Printer', version: 1, inputs: { required: [ 'name', 'organizationId', 'ipAddress' ], optional: [ 'location', 'manufacturer', 'model', 'serial' ] }, outputExample: { name: 'My Color Printer', id: '123', location: 'Room 201', manufacturer: 'Ricoh', model: 'ABC123', ipAddress: '192.168.100.20', serial: '12345ABCDE' }, run: function (api, connection, next) { var id = api.mongoose.Types.ObjectId(connection.params.organizationId); var Printer = api.mongoose.model('Printer'); var ipArray = connection.params.ipAddress.split('.'); for(var i=0; i<ipArray.length; i++) { var pad = '000'; ipArray[i] = pad.substring(0, pad.length - ipArray[i].length) + ipArray[i]; } var paddedIP = ipArray.join('.'); var newPrinter = new Printer({ name: connection.params.name, location: connection.params.location, manufacturer: connection.params.manufacturer, model: connection.params.model, ipAddress: paddedIP, serial: connection.params.serial }).save(function (err, printer) { if(err) { connection.error = "A Printer with IP Address '" + connection.params.ipAddress + "' already exists."; connection.response.details = err; next(connection, true); } else if(printer) { connection.response.name = printer.name; connection.response.location = printer.location; connection.response.manufacturer = printer.manufacturer; connection.response.model = printer.model; connection.response.ipAddress = printer.ipAddress; connection.response.serial = printer.serial; connection.response.id = printer._id; api.mongoose.model('Organization').findByIdAndUpdate(id, { $push: { printers: printer._id } }, function (err) { next(connection, true); }); } }); } };
// viewmodel class define(['jquery', 'knockout'], function($, ko) { return function() { var self = this; self.authors = ko.observable(); $.get('/shufa/').then(function(list) { $('#beitie-authors-container').removeClass('hide'); return $.map(list, function(author, index) { return { href: ['#/shufa/', author].join(''), text: (index + 1) + '.' + author } }); }).done(this.authors); }; });
/* global module:false */ module.exports = function(grunt) { var port = grunt.option('port') || 8000; // Project configuration grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), meta: { banner: '/*!\n' + ' * reveal.js <%= pkg.version %> (<%= grunt.template.today("yyyy-mm-dd, HH:MM") %>)\n' + ' * http://lab.hakim.se/reveal-js\n' + ' * MIT licensed\n' + ' *\n' + ' * Copyright (C) 2014 Hakim El Hattab, http://hakim.se\n' + ' */' }, qunit: { files: [ 'test/*.html' ] }, uglify: { options: { banner: '<%= meta.banner %>\n' }, build: { src: 'js/reveal.js', dest: 'js/reveal.min.js' } }, cssmin: { compress: { files: { 'css/reveal.min.css': [ 'css/reveal.css' ] } } }, sass: { main: { files: { 'css/theme/firebase.css': 'css/theme/source/firebase.scss' } } }, jshint: { options: { curly: false, eqeqeq: true, immed: true, latedef: true, newcap: true, noarg: true, sub: true, undef: true, eqnull: true, browser: true, expr: true, globals: { head: false, module: false, console: false, unescape: false } }, files: [ 'Gruntfile.js', 'config.js', 'reveal-config.js', 'firebase-intro.js', ] }, connect: { server: { options: { port: port, base: '.' } } }, zip: { 'reveal-js-presentation.zip': [ 'index.html', 'css/**', 'demo/**', 'js/**', 'lib/**', 'images/**', 'plugin/**' ] }, watch: { main: { files: [ 'Gruntfile.js', 'js/reveal.js', 'demo/firebase-demo.js', 'css/reveal.css' ], tasks: 'default' }, theme: { files: [ 'css/theme/source/*.scss', 'css/theme/template/*.scss' ], tasks: 'themes' } } }); // Dependencies grunt.loadNpmTasks( 'grunt-contrib-qunit' ); grunt.loadNpmTasks( 'grunt-contrib-jshint' ); grunt.loadNpmTasks( 'grunt-contrib-cssmin' ); grunt.loadNpmTasks( 'grunt-contrib-uglify' ); grunt.loadNpmTasks( 'grunt-contrib-watch' ); grunt.loadNpmTasks( 'grunt-contrib-sass' ); grunt.loadNpmTasks( 'grunt-contrib-connect' ); grunt.loadNpmTasks( 'grunt-zip' ); // Default task grunt.registerTask( 'default', [ 'jshint', 'cssmin', 'uglify', 'qunit' ] ); // Theme task grunt.registerTask( 'themes', [ 'sass' ] ); // Package presentation to archive grunt.registerTask( 'package', [ 'default', 'zip' ] ); // Serve presentation locally grunt.registerTask( 'serve', [ 'connect', 'watch' ] ); // Run tests grunt.registerTask( 'test', [ 'jshint', 'qunit' ] ); };
/* ======================================================== * bootstrap-tab.js v2.2.1 * http://twitter.github.com/bootstrap/javascript.html#tabs * ======================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================== */ !function ($) { "use strict"; // jshint ;_; /* TAB CLASS DEFINITION * ==================== */ var Tab = function (element) { this.element = $(element) } Tab.prototype = { constructor: Tab , show: function () { var $this = this.element , $ul = $this.closest('ul:not(.dropdown-menu)') , selector = $this.attr('data-target') , previous , $target , e if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } if ( $this.parent('li').hasClass('active') ) return previous = $ul.find('.active:last a')[0] e = $.Event('show', { relatedTarget: previous }) $this.trigger(e) if (e.isDefaultPrevented()) return $target = $(selector) this.activate($this.parent('li'), $ul) this.activate($target, $target.parent(), function () { $this.trigger({ type: 'shown' , relatedTarget: previous }) }) } , activate: function ( element, container, callback) { var $active = container.find('> .active') , transition = callback && $.support.transition && $active.hasClass('fade') function next() { $active .removeClass('active') .find('> .dropdown-menu > .active') .removeClass('active') element.addClass('active') if (transition) { element[0].offsetWidth // reflow for transition element.addClass('in') } else { element.removeClass('fade') } if ( element.parent('.dropdown-menu') ) { element.closest('li.dropdown').addClass('active') } callback && callback() } transition ? $active.one($.support.transition.end, next) : next() $active.removeClass('in') } } /* TAB PLUGIN DEFINITION * ===================== */ $.fn.tab = function ( option ) { return this.each(function () { var $this = $(this) , data = $this.data('tab') if (!data) $this.data('tab', (data = new Tab(this))) if (typeof option == 'string') data[option]() }) } $.fn.tab.Constructor = Tab /* TAB DATA-API * ============ */ $(document).on('click.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) { e.preventDefault() $(this).tab('show') }) }(window.jQuery);
import React, { Component } from 'react'; import { connect } from 'react-redux'; import * as APIService from '../../api/APIService'; import DocumentTitle from 'react-document-title'; import ReactPaginate from 'react-paginate'; import Loader from '../helpers/loader'; import IssueHandler from '../helpers/IssueHandler'; import MusicList from '../views/lists/MusicList'; class ListensList extends Component { getContent(id, offset, limit) { APIService.getUserListensList(id, offset, limit); window.scrollTo(0,0); } componentDidMount() { this.getContent(this.props.match.params.id, this.props.paginationConfig.offset, this.props.paginationConfig.limit); } handlePageClick = (data) => { let selected = data.selected * 20; this.getContent(this.props.match.params.id, selected, this.props.paginationConfig.limit); }; render() { return ( <div className="center-align"> <div className="container"> <DocumentTitle title={(this.props.match.params.id || "User")+ "'s Listens - SoundMix"}/> <div className="col s12 pushDown"></div> <div className={!this.props.isLoading ? 'hidden' : ''}> <Loader /> </div> <div className={this.props.isLoading ? 'hidden' : ''}> {(() => { if (this.props.errorStatus) { return <IssueHandler requestItem={this.props.match.params.id} /> } else { return <div> <MusicList isLoading = {this.props.isLoading} goBack={APIService.goBack} data={this.props.listensList.data} /> {(() => { if (this.props.listensList.data.length >= this.props.paginationConfig.limit) { return <ReactPaginate previousLabel={"Previous"} nextLabel={"Next"} breakLabel={<a href="">...</a>} breakClassName={"break-me"} pageCount={this.props.paginationConfig.pageCount} marginPagesDisplayed={0} pageRangeDisplayed={7} onPageChange={this.handlePageClick} containerClassName={"pagination"} subContainerClassName={"pages pagination"} activeClassName={"active"} /> } if (this.props.listensList.data.length === 0) { return <p>No Listens Just Yet...</p> } })()} </div> } })()} </div> </div> </div> ); } } const mapStateToProps = function(store) { //console.log("Store", store.api); return { listensList: store.api.listensList, isLoading: store.api.isLoading, paginationConfig: store.api.paginationConfig, errorStatus: store.api.errorStatus }; }; export default connect(mapStateToProps)(ListensList);
class AboutController { constructor() { this.name = 'about'; } } export default AboutController;
var cooking = require('cooking'); var config = require('./config'); var md = require('markdown-it')(); var striptags = require('./strip-tags'); var slugify = require('transliteration').slugify; var isProd = process.env.NODE_ENV === 'production'; function convert(str) { str = str.replace(/(&#x)(\w{4});/gi, function($0) { return String.fromCharCode(parseInt(encodeURIComponent($0).replace(/(%26%23x)(\w{4})(%3B)/g, '$2'), 16)); }); return str; } cooking.set({ entry: isProd ? { docs: './examples/entry.js', 'element-ui': './src/index.js' } : './examples/entry.js', dist: './examples/element-ui/', template: [ { template: './examples/index.tpl', filename: './index.html', favicon: './examples/favicon.ico' } ], publicPath: process.env.CI_ENV || '/', hash: true, devServer: { port: 8085, log: false, publicPath: '/' }, minimize: true, chunk: isProd ? { 'common': { name: ['element-ui', 'manifest'] } } : false, extractCSS: true, alias: config.alias, extends: ['vue2', 'lint'], postcss: config.postcss }); cooking.add('loader.md', { test: /\.md$/, loader: 'vue-markdown-loader' }); cooking.add('vueMarkdown', { use: [ [require('markdown-it-anchor'), { level: 2, slugify: slugify, permalink: true, permalinkBefore: true }], [require('markdown-it-container'), 'demo', { validate: function(params) { return params.trim().match(/^demo\s*(.*)$/); }, render: function(tokens, idx) { var m = tokens[idx].info.trim().match(/^demo\s*(.*)$/); if (tokens[idx].nesting === 1) { var description = (m && m.length > 1) ? m[1] : ''; var content = tokens[idx + 1].content; var html = convert(striptags.strip(content, ['script', 'style'])); var script = striptags.fetch(content, 'script'); var style = striptags.fetch(content, 'style'); var jsfiddle = { html: html, script: script, style: style }; var descriptionHTML = description ? md.render(description) : ''; jsfiddle = md.utils.escapeHtml(JSON.stringify(jsfiddle)); return `<demo-block class="demo-box" :jsfiddle="${jsfiddle}"> <div class="source" slot="source">${html}</div> ${descriptionHTML} <div class="highlight" slot="highlight">`; } return '</div></demo-block>\n'; } }] ], preprocess: function(MarkdownIt, source) { MarkdownIt.renderer.rules.table_open = function() { return '<table class="table">'; }; MarkdownIt.renderer.rules.fence = wrap(MarkdownIt.renderer.rules.fence); return source; } }); var wrap = function(render) { return function() { return render.apply(this, arguments) .replace('<code class="', '<code class="hljs ') .replace('<code>', '<code class="hljs">'); }; }; if (isProd) { cooking.add('externals.vue', 'Vue'); cooking.add('externals.vue-router', 'VueRouter'); } cooking.add('vue.preserveWhitespace', false); module.exports = cooking.resolve();
define([ 'onion/type', 'onion/event_emitter', 'onion/json_api', 'jquery' ], function ( Type, eventEmitter, JsonApi, $ ) { return Type.sub("Server") .after("init", function () { this.api = new JsonApi() }) .proto(eventEmitter) .proto({ camelize: function (string) { return string.replace(/_(\w)/g, function (entire, c) { return c.toUpperCase() }) }, camelizeAttrs: function (attributes) { var camelAttributes = {} for ( var key in attributes ) { camelAttributes[this.camelize(key)] = attributes[key] } return camelAttributes }, fromDataArray: function (data, Class) { return data.map(function (attrs) { return Class.newFromAttributes(this.camelizeAttrs(attrs)) }, this) } }) })
angular.module('tf-client') .directive('tfJob', function() { return { restrict: 'E', // ng-repeat has a priority of 1000, we need the compiler to process first the directive, // so we use more priority here. priority: 1001, scope: { job: '=' }, templateUrl: 'directives/job/tf-job.html' }; });
var request = require('request'); var userUrl = 'https://www.codewars.com/api/v1/users/johnwquarles?access_key=' + process.env['CODEWARS_KEY']; var outOfUrl = 'https://www.codewars.com/api/v1/code-challenges/50654ddff44f800200000004?access_key=' + process.env['CODEWARS_KEY']; var exp_obj = {}; exp_obj.getMyData = function(cb) { request(userUrl, function (error, response, body) { if (!error && response.statusCode == 200) { // pulls in JSON object (which is 'stringified'; that's what JSON is. Stringified = JSON, parsed = JS object) cb(null, body); } else { cb(error); } }) } exp_obj.getOutOf = function(cb) { request(outOfUrl, function (error, response, body) { if (!error && response.statusCode == 200) { cb(null, body); } else { cb(error); } }) } module.exports = exp_obj;
/** * 显示模块 * @param node|nodeArray 略过节点 支持节点或者节点数组 */ CJS.Import( 'css.isShow' ); CJS.register( 'css.show', function ( $ ) { var $f = $.FUNCS, $l = $.logic; return function ( nodes, skipNode ) { var show = function ( n ) { // 对当前节点做浅度显示检测,避免重复设置 if( !$l.css.isShow( n ) ) { n.style.display = 'block'; // n.style.visibility = 'visible'; } }; if ( $f.isNode( nodes ) ) { show(nodes); } else if ( $f.isArray( nodes ) ) { for ( var i = 0, nL = nodes.length; i < nL; i++ ) { if ( skipNode && skipNode == nodes[i] ) continue; show( nodes[i] ); } } return nodes; }; });
import $ from 'jquery'; /* Dependencies for checking if changes happened since load on a form import toastr from '../utils/toastr'; import { translations } from 'grav-config'; import { Instance as FormState } from './state'; */ export default class Form { constructor(form) { this.form = $(form); if (!this.form.length || this.form.prop('tagName').toLowerCase() !== 'form') { return; } /* Option for not saving while nothing in a form has changed this.form.on('submit', (event) => { if (FormState.equals()) { event.preventDefault(); toastr.info(translations.PLUGIN_ADMIN.NOTHING_TO_SAVE); } }); */ this._attachShortcuts(); this._attachToggleables(); this._attachDisabledFields(); this._submitUncheckedFields(); this.observer = new MutationObserver(this.addedNodes); this.form.each((index, form) => this.observer.observe(form, { subtree: true, childList: true })); } _attachShortcuts() { // CTRL + S / CMD + S - shortcut for [Save] when available let saveTask = $('#titlebar [name="task"][value="save"]'); if (saveTask.length) { $(global).on('keydown', function(event) { var key = String.fromCharCode(event.which).toLowerCase(); if (((event.ctrlKey && !event.altKey) || event.metaKey) && key === 's') { event.preventDefault(); saveTask.click(); } }); } } _attachToggleables() { let query = '[data-grav-field="toggleable"] input[type="checkbox"]'; this.form.on('change', query, (event) => { let toggle = $(event.target); let enabled = toggle.is(':checked'); let parent = toggle.closest('.form-field'); let label = parent.find('label.toggleable'); let fields = parent.find('.form-data'); let inputs = fields.find('input, select, textarea, button'); label.add(fields).css('opacity', enabled ? '' : 0.7); inputs.map((index, input) => { let isSelectize = input.selectize; input = $(input); if (isSelectize) { isSelectize[enabled ? 'enable' : 'disable'](); } else { input.prop('disabled', !enabled); } }); }); this.form.find(query).trigger('change'); } _attachDisabledFields() { let prefix = '.form-field-toggleable .form-data'; let query = []; ['input', 'select', 'label[for]', 'textarea', '.selectize-control'].forEach((item) => { query.push(`${prefix} ${item}`); }); this.form.on('mousedown', query.join(', '), (event) => { let input = $(event.target); let isFor = input.prop('for'); let isSelectize = (input.hasClass('selectize-control') || input.parents('.selectize-control')).length; if (isFor) { input = $(`[id="${isFor}"]`); } if (isSelectize) { input = input.closest('.selectize-control').siblings('select[name]'); } if (!input.prop('disabled')) { return true; } let toggle = input.closest('.form-field').find('[data-grav-field="toggleable"] input[type="checkbox"]'); toggle.trigger('click'); }); } _submitUncheckedFields() { let submitted = false; this.form.each((index, form) => { form = $(form); form.on('submit', () => { // workaround for MS Edge, submitting multiple forms at the same time if (submitted) { return false; } let formId = form.attr('id'); let unchecked = form.find('input[type="checkbox"]:not(:checked):not(:disabled)'); let submit = form.find('[type="submit"]').add(`[form="${formId}"][type="submit"]`); if (!unchecked.length) { return true; } submit.addClass('pointer-events-disabled'); unchecked.each((index, element) => { element = $(element); let name = element.prop('name'); let fake = $(`<input type="hidden" name="${name}" value="0" />`); form.append(fake); }); submitted = true; return true; }); }); } addedNodes(mutations) { mutations.forEach((mutation) => { if (mutation.type !== 'childList' || !mutation.addedNodes) { return; } $('body').trigger('mutation._grav', mutation.target, mutation, this); }); } } export let Instance = new Form('form#blueprints');
exports.defineAutoTests = function () { describe('Whois (window.Whois)', function () { it('should exist', function (done) { expect(window.Whois).toBeDefined(); done(); }); }); describe('Success callback', function () { it('should take an argument that is an array of results', function (done) { var w, success, err; w = new window.Whois(); success = function (r) { expect(r).toBeDefined(); expect(r.length > 0).toBe(true); expect(r[0].query).toBe('apache.org@whois.pir.org'); expect(r[0].status).toBe('success'); expect(typeof r[0].result).toBe('string'); done(); }; err = function (e) { console.log(e); }; w.whois(['apache.org@whois.pir.org'], success, err); }); }); };
Ext.override(Rally.ui.cardboard.CardBoard,{ _buildColumnsFromModel: function() { var me = this; var model = this.models[0]; if (model) { if ( this.attribute === "Iteration" ) { var retrievedColumns = []; retrievedColumns.push({ value: null, columnHeaderConfig: { headerTpl: "{name}", headerData: { name: "Backlog" } } }); this._getLocalIterations(retrievedColumns); } } }, _getLocalIterations: function(retrievedColumns) { var me = this; var start_date = this.startIteration.get('formattedStartDate'); var filters = [{property:'StartDate',operator:'>=',value:start_date}]; var iteration_names = []; Ext.create('Rally.data.WsapiDataStore',{ model:me.attribute, autoLoad: true, filters: filters, context: { projectScopeUp: false, projectScopeDown: false }, sorters: [ { property: 'EndDate', direction: 'ASC' } ], fetch: ['Name','EndDate','StartDate','PlannedVelocity'], listeners: { load: function(store,records) { Ext.Array.each(records, function(record){ iteration_names.push(record.get('Name')); retrievedColumns.push({ value: record, columnHeaderConfig: { headerTpl: "{name}", headerData: { name: record.get('Name') } } }); }); this._getAllIterations(retrievedColumns,iteration_names); }, scope: this } }); }, _getAllIterations: function(retrievedColumns,iteration_names) { var me = this; var today_iso = Rally.util.DateTime.toIsoString(new Date(),false); var filters = [{property:'EndDate',operator:'>',value:today_iso}]; Ext.create('Rally.data.WsapiDataStore',{ model:me.attribute, autoLoad: true, filters: filters, sorters: [ { property: 'EndDate', direction: 'ASC' } ], fetch: ['Name','Project','PlannedVelocity','Children','Parent', 'ObjectID'], listeners: { load: function(store,records) { var current_project = null; if ( this.context ) { current_project = this.context.getProject(); } this.fireEvent('columnsretrieved',this,retrievedColumns); this.columnDefinitions = []; _.map(retrievedColumns,this.addColumn,this); this._renderColumns(); }, scope: this } }); } }); Ext.override(Rally.ui.cardboard.Column,{ getStoreFilter: function(model) { var property = this.attribute; var value = this.getValue(); if ( this.attribute == "Iteration" ) { property = "Iteration.Name"; if ( value ) { value = value.get('Name'); } } return { property:property, operator: '=', value: value }; }, isMatchingRecord: function(record) { var recordValue = record.get(this.attribute); if (recordValue) { recordValue = recordValue.Name; } var columnValue = this.getValue(); if ( columnValue ) { columnValue = columnValue.get('Name'); } return (columnValue === recordValue ); }, addCard: function(card, index, highlight) { var record = card.getRecord(); var target_value = this.getValue(); if ( target_value && typeof(target_value.get) === "function" ) { target_value = this.getValue().get('_ref'); } record.set(this.attribute,target_value); if (!Ext.isNumber(index)) { //find where it should go var records = Ext.clone(this.getRecords()); records.push(record); this._sortRecords(records); var recordIndex = 0; for (var iIndex = 0, l = records.length; iIndex < l; iIndex++) { var i = records[iIndex]; if (i.get("ObjectID") === record.get("ObjectID")) { recordIndex = iIndex; break; } } index = recordIndex; } this._renderCard(card, index); if (highlight) { card.highlight(); } this.fireEvent('addcard'); card.fireEvent('ready', card); }, _sortRecords: function(records) { var sortProperty = this._getSortProperty(), sortAscending = this._getSortDirection() === 'ASC', valA, valB; // force to new rank style sortProperty = "DragAndDropRank"; records.sort(function(a, b) { valA = a.get(sortProperty); if (valA && valA._refObjectName) { valA = valA._refObjectName; } valB = b.get(sortProperty); if (valB && valB._refObjectName) { valB = valB._refObjectName; } if (valA === valB) { return 0; } if (valA !== null && valA !== undefined) { if (valB === null || valB === undefined) { return sortAscending ? -1 : 1; } else { return valA > valB ? (sortAscending ? 1 : -1) : (sortAscending ? -1 : 1); } } else if (valB !== null && valB !== undefined) { if (valA === null || valA === undefined) { return sortAscending ? 1 : -1; } else { return valB > valA ? (sortAscending ? -1 : 1) : (sortAscending ? 1 : -1); } } //Default case (dates, objects, etc.) return sortAscending ? valA - valB : valB - valA; }); } });
var async = require('async'); var cache = require('memory-cache'); var config = require('./config'); var CronJob = require('cron').CronJob; var GitHubApi = require('github'); var log = require('./logger')(); var api = module.exports = {}; api.init = function init(callback) { var github = this; github.client = new GitHubApi({ version: '3.0.0', protocol: 'https', host: 'api.github.com', timeout: 5000, headers: { 'user-agent': 'glance' } }); if(config.github.auth.type === 'oauth') { github.client.authenticate(config.github.auth); } if(config.github.auth.type === 'basic') { github.client.authenticate(config.github.auth); } if(config.github.org.name) { github.canGetAllReposFromOrg = true; github.canGetAllPullRequestsFromOrg = true; cache.put('org', {name: config.github.org.name}); } else { github.canGetAllReposFromOrg = false; github.canGetAllPullRequestsFromOrg = false; } log.info('Github: Initialized'); callback(null); }; api.start = function start(callback) { var github = this; new CronJob(config.github.cron, function() { if(github.canGetAllReposFromOrg) { log.debug('getAllReposFromOrg CronJob fired, making request'); github.canGetAllReposFromOrg = false; github.getAllReposFromOrg(function() { github.canGetAllReposFromOrg = true; }); } else { log.warn('getAllReposFromOrg CronJob fired, but last request still pending'); } }, null, true); new CronJob(config.github.cron, function() { if(github.canGetAllPullRequestsFromOrg) { log.debug('getAllPullRequestsFromOrg CronJob fired, making request'); github.canGetAllPullRequestsFromOrg = false; github.getAllPullRequestsFromOrg(function() { github.canGetAllPullRequestsFromOrg = true; }); } else { log.warn('getAllPullRequestsFromOrg CronJob fired, but last request still pending'); } }, null, true); callback(null); }; api.getAllReposFromOrg = function getAllReposFromOrg(callback) { var github = this; var req = { org: config.github.org.name, type: 'all', sort: 'full_name', direction: 'asc', page: 0, per_page: 100 }; github.client.repos.getFromOrg(req, function(err, res) { if(err) { log.error({error: err.message}, 'Error - Github: getAllReposFromOrg'); callback(err.message); } else { var reposFromOrg = []; async.each(res, function(r, cb) { var repo = { id: r.id, name: r.name, full_name: r.full_name, description: r.description, private: r.private, open_issues_count: r.open_issues_count, open_issues: r.open_issues, size: r.size, created_at: r.created_at, updated_at: r.updated_at, pushed_at: r.pushed_at }; reposFromOrg.push(repo); cb(null); }, function(err) { if(err) { log.error({error: err}, 'Error - Github: parsing getAllReposFromOrg'); callback(err.message); } else { log.info({reposFromOrg: reposFromOrg.length}, 'Github: getAllReposFromOrg'); log.trace({reposFromOrg: reposFromOrg}, 'Github: getAllReposFromOrg'); cache.put('reposFromOrg', reposFromOrg); callback(null); } }); } }); }; api.getAllPullRequestsFromOrg = function getAllPullRequestsFromOrg(callback) { var github = this; var repos = cache.get('reposFromOrg') || []; var req = { user: config.github.org.name, repo: 'repo', sort: 'created', direction: 'asc', page: 0, per_page: 100 }; var pullRequestsFromOrg = []; async.each(repos, function(r, cb) { req.repo = r.name; github.client.pullRequests.getAll(req, function(err, res) { if(err) { log.error({error: err.message}, 'Error - Github: getAllPullRequestsFromOrg'); cb(err.message); } else { for(var i = 0; i < res.length; i++) { var pr = { id: res[i].id, title: res[i].title, repo_id: res[i].head.repo.id, repo_name: res[i].head.repo.name, state: res[i].state, number: res[i].number, user: res[i].user.login, created_at: res[i].created_at, updated_at: res[i].updated_at, closed_at: res[i].closed_at, merged_at: res[i].merged_at, } pullRequestsFromOrg.push(pr); } cb(null); } }); }, function(err) { if(err) { log.error({error: err}, 'Error - Github: parsing getAllPullRequestsFromOrg'); callback(err.message); } else { log.info({pullRequestsFromOrg: pullRequestsFromOrg.length}, 'Github: getAllPullRequestsFromOrg'); log.trace({pullRequestsFromOrg: pullRequestsFromOrg}, 'Github: getAllPullRequestsFromOrg'); cache.put('pullRequestsFromOrg', pullRequestsFromOrg); callback(null); } }); };
var DOM = module.DOM = Class.extend({ initNode: function (element, classSet, attributes, dataSet) { var classes = classSet, cl; extend(element, attributes); extend(element.dataset, dataSet); if (Array.isArray(classSet)) { classes = classSet.join(' '); } else if (classSet && typeof classSet === 'object') { classes = []; for (cl in classSet) { if (classSet.hasOwnProperty(cl) && classSet[cl]) { classes.push(cl); } } classes = classes.join(' '); } if (classes) { element.className = classes; } return element; }, findClosestViewNode: function (element, attribute) { var attributeValue; do { attributeValue = element.getAttribute(attribute); if (attributeValue != null) { return attributeValue; } element = element.parentNode; } while (element !== document); }, attachNodeToParent: function (childNode, parentNode, index) { if (typeof index === 'number') { parentNode.insertBefore(childNode, parentNode.children[index]); } else { parentNode.appendChild(childNode); } } });
/*Generated By KISSY Module Compiler*/ config({ 'component/plugin/drag': {requires: ['rich-base','dd']} });
'use strict'; (function (angular) { angular.module('seminarNotesPluginContent') .constant('TAG_NAMES', { SEMINAR_INFO: 'seminarInfo', SEMINAR_ITEMS: "seminarItems", SEMINAR_BOOKMARKS: "seminarBookmarks", SEMINAR_NOTES: "seminarNotes" }) .constant('STATUS_CODE', { INSERTED: 'inserted', UPDATED: 'updated', NOT_FOUND: 'NOTFOUND', UNDEFINED_DATA: 'UNDEFINED_DATA', UNDEFINED_OPTIONS: 'UNDEFINED_OPTIONS', UNDEFINED_ID: 'UNDEFINED_ID', ITEM_ARRAY_FOUND: 'ITEM_ARRAY_FOUND', NOT_ITEM_ARRAY: 'NOT_ITEM_ARRAY' }) .constant('STATUS_MESSAGES', { UNDEFINED_DATA: 'Undefined data provided', UNDEFINED_OPTIONS: 'Undefined options provided', UNDEFINED_ID: 'Undefined id provided', NOT_ITEM_ARRAY: 'Array of Items not provided', ITEM_ARRAY_FOUND: 'Array of Items provided' }) .constant('LAYOUTS', { itemListLayout: [ {name: "Item_List_1"}, {name: "Item_List_2"}, {name: "Item_List_3"}, {name: "Item_List_4"}, {name: "Item_List_5"} ] }) .constant('PAGINATION', { itemCount: 10 }) .constant('SORT', { MANUALLY: 'Manually', ITEM_TITLE_A_Z: 'Item title A-Z', ITEM_TITLE_Z_A: 'Item title Z-A', NEWEST_PUBLICATION_DATE: 'Newest pub. date first', OLDEST_PUBLICATION_DATE: 'Oldest pub. date first', NEWEST_FIRST: 'Newest entry first', OLDEST_FIRST: 'Oldest entry first', _limit: 10, _maxLimit: 19, _skip: 0 }); })(window.angular);
var minesweeper = require('./solver.js'); var WIDTH = 16; var HEIGHT = 16; var MINES = 40; function play () { var field = new minesweeper.Field(WIDTH, HEIGHT, MINES); var solver = new minesweeper.Solver(field); try { solver.solve(); } catch (exc) { return false; } return true; } function test (n) { var successful = 0; for (var i = 0; i < n; i++) { if (play()) { successful++; } } var percentage = Math.round(1000*(successful/n))/10; console.log( "Percentage of successful games on a " + WIDTH + "x" + HEIGHT + " field with " + MINES + " mines: " + percentage + "%." ); } test(10000);
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'indent', 'si', { indent: 'අතර පරතරය වැඩිකරන්න', outdent: 'අතර පරතරය අඩුකරන්න' } );
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- * Please make sure to make edits in the .ts file at https://github.com/Microsoft/vscode-loader/ *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------*/ 'use strict'; var NLSLoaderPlugin; (function (NLSLoaderPlugin) { var Environment = /** @class */ (function () { function Environment() { this._detected = false; this._isPseudo = false; } Object.defineProperty(Environment.prototype, "isPseudo", { get: function () { this._detect(); return this._isPseudo; }, enumerable: true, configurable: true }); Environment.prototype._detect = function () { if (this._detected) { return; } this._detected = true; this._isPseudo = (typeof document !== 'undefined' && document.location && document.location.hash.indexOf('pseudo=true') >= 0); }; return Environment; }()); function _format(message, args, env) { var result; if (args.length === 0) { result = message; } else { result = message.replace(/\{(\d+)\}/g, function (match, rest) { var index = rest[0]; return typeof args[index] !== 'undefined' ? args[index] : match; }); } if (env.isPseudo) { // FF3B and FF3D is the Unicode zenkaku representation for [ and ] result = '\uFF3B' + result.replace(/[aouei]/g, '$&$&') + '\uFF3D'; } return result; } function findLanguageForModule(config, name) { var result = config[name]; if (result) return result; result = config['*']; if (result) return result; return null; } function localize(env, data, message) { var args = []; for (var _i = 3; _i < arguments.length; _i++) { args[_i - 3] = arguments[_i]; } return _format(message, args, env); } function createScopedLocalize(scope, env) { return function (idx, defaultValue) { var restArgs = Array.prototype.slice.call(arguments, 2); return _format(scope[idx], restArgs, env); }; } var NLSPlugin = /** @class */ (function () { function NLSPlugin(env) { var _this = this; this._env = env; this.localize = function (data, message) { var args = []; for (var _i = 2; _i < arguments.length; _i++) { args[_i - 2] = arguments[_i]; } return localize.apply(void 0, [_this._env, data, message].concat(args)); }; } NLSPlugin.prototype.setPseudoTranslation = function (value) { this._env._isPseudo = value; }; NLSPlugin.prototype.create = function (key, data) { return { localize: createScopedLocalize(data[key], this._env) }; }; NLSPlugin.prototype.load = function (name, req, load, config) { var _this = this; config = config || {}; if (!name || name.length === 0) { load({ localize: this.localize }); } else { var pluginConfig = config['vs/nls'] || {}; var language = pluginConfig.availableLanguages ? findLanguageForModule(pluginConfig.availableLanguages, name) : null; var suffix = '.nls'; if (language !== null && language !== NLSPlugin.DEFAULT_TAG) { suffix = suffix + '.' + language; } var messagesLoaded_1 = function (messages) { if (Array.isArray(messages)) { messages.localize = createScopedLocalize(messages, _this._env); } else { messages.localize = createScopedLocalize(messages[name], _this._env); } load(messages); }; if (typeof pluginConfig.loadBundle === 'function') { pluginConfig.loadBundle(name, language, function (err, messages) { // We have an error. Load the English default strings to not fail if (err) { req([name + '.nls'], messagesLoaded_1); } else { messagesLoaded_1(messages); } }); } else { req([name + suffix], messagesLoaded_1); } } }; NLSPlugin.DEFAULT_TAG = 'i-default'; return NLSPlugin; }()); NLSLoaderPlugin.NLSPlugin = NLSPlugin; define('vs/nls', new NLSPlugin(new Environment())); })(NLSLoaderPlugin || (NLSLoaderPlugin = {}));